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 +6 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__init__.py +122 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_bvp.py +1154 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_cubature.py +728 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so +3 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py +8 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py +290 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py +478 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py +451 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py +193 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py +748 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py +224 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py +572 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py +601 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py +1268 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_rk.py +37 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_lebedev.py +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so +3 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ode.py +1388 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so +3 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py +273 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py +682 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so +3 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py +1279 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quadrature.py +1336 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py +12 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc +0 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py +518 -0
- evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py +202 -0
.gitattributes
CHANGED
|
@@ -826,3 +826,9 @@ infer_4_47_1/lib/libasan.so filter=lfs diff=lfs merge=lfs -text
|
|
| 826 |
infer_4_47_1/lib/libitm.so.1 filter=lfs diff=lfs merge=lfs -text
|
| 827 |
infer_4_47_1/lib/libncursesw.so.6 filter=lfs diff=lfs merge=lfs -text
|
| 828 |
infer_4_47_1/lib/libbz2.so.1.0.8 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 826 |
infer_4_47_1/lib/libitm.so.1 filter=lfs diff=lfs merge=lfs -text
|
| 827 |
infer_4_47_1/lib/libncursesw.so.6 filter=lfs diff=lfs merge=lfs -text
|
| 828 |
infer_4_47_1/lib/libbz2.so.1.0.8 filter=lfs diff=lfs merge=lfs -text
|
| 829 |
+
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 830 |
+
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 831 |
+
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 832 |
+
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_vode.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 833 |
+
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 834 |
+
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__init__.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
=============================================
|
| 3 |
+
Integration and ODEs (:mod:`scipy.integrate`)
|
| 4 |
+
=============================================
|
| 5 |
+
|
| 6 |
+
.. currentmodule:: scipy.integrate
|
| 7 |
+
|
| 8 |
+
Integrating functions, given function object
|
| 9 |
+
============================================
|
| 10 |
+
|
| 11 |
+
.. autosummary::
|
| 12 |
+
:toctree: generated/
|
| 13 |
+
|
| 14 |
+
quad -- General purpose integration
|
| 15 |
+
quad_vec -- General purpose integration of vector-valued functions
|
| 16 |
+
cubature -- General purpose multi-dimensional integration of array-valued functions
|
| 17 |
+
dblquad -- General purpose double integration
|
| 18 |
+
tplquad -- General purpose triple integration
|
| 19 |
+
nquad -- General purpose N-D integration
|
| 20 |
+
tanhsinh -- General purpose elementwise integration
|
| 21 |
+
fixed_quad -- Integrate func(x) using Gaussian quadrature of order n
|
| 22 |
+
newton_cotes -- Weights and error coefficient for Newton-Cotes integration
|
| 23 |
+
lebedev_rule
|
| 24 |
+
qmc_quad -- N-D integration using Quasi-Monte Carlo quadrature
|
| 25 |
+
IntegrationWarning -- Warning on issues during integration
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
Integrating functions, given fixed samples
|
| 29 |
+
==========================================
|
| 30 |
+
|
| 31 |
+
.. autosummary::
|
| 32 |
+
:toctree: generated/
|
| 33 |
+
|
| 34 |
+
trapezoid -- Use trapezoidal rule to compute integral.
|
| 35 |
+
cumulative_trapezoid -- Use trapezoidal rule to cumulatively compute integral.
|
| 36 |
+
simpson -- Use Simpson's rule to compute integral from samples.
|
| 37 |
+
cumulative_simpson -- Use Simpson's rule to cumulatively compute integral from samples.
|
| 38 |
+
romb -- Use Romberg Integration to compute integral from
|
| 39 |
+
-- (2**k + 1) evenly-spaced samples.
|
| 40 |
+
|
| 41 |
+
.. seealso::
|
| 42 |
+
|
| 43 |
+
:mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
|
| 44 |
+
quadrature roots and weights for other weighting factors and regions.
|
| 45 |
+
|
| 46 |
+
Summation
|
| 47 |
+
=========
|
| 48 |
+
|
| 49 |
+
.. autosummary::
|
| 50 |
+
:toctree: generated/
|
| 51 |
+
|
| 52 |
+
nsum
|
| 53 |
+
|
| 54 |
+
Solving initial value problems for ODE systems
|
| 55 |
+
==============================================
|
| 56 |
+
|
| 57 |
+
The solvers are implemented as individual classes, which can be used directly
|
| 58 |
+
(low-level usage) or through a convenience function.
|
| 59 |
+
|
| 60 |
+
.. autosummary::
|
| 61 |
+
:toctree: generated/
|
| 62 |
+
|
| 63 |
+
solve_ivp -- Convenient function for ODE integration.
|
| 64 |
+
RK23 -- Explicit Runge-Kutta solver of order 3(2).
|
| 65 |
+
RK45 -- Explicit Runge-Kutta solver of order 5(4).
|
| 66 |
+
DOP853 -- Explicit Runge-Kutta solver of order 8.
|
| 67 |
+
Radau -- Implicit Runge-Kutta solver of order 5.
|
| 68 |
+
BDF -- Implicit multi-step variable order (1 to 5) solver.
|
| 69 |
+
LSODA -- LSODA solver from ODEPACK Fortran package.
|
| 70 |
+
OdeSolver -- Base class for ODE solvers.
|
| 71 |
+
DenseOutput -- Local interpolant for computing a dense output.
|
| 72 |
+
OdeSolution -- Class which represents a continuous ODE solution.
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
Old API
|
| 76 |
+
-------
|
| 77 |
+
|
| 78 |
+
These are the routines developed earlier for SciPy. They wrap older solvers
|
| 79 |
+
implemented in Fortran (mostly ODEPACK). While the interface to them is not
|
| 80 |
+
particularly convenient and certain features are missing compared to the new
|
| 81 |
+
API, the solvers themselves are of good quality and work fast as compiled
|
| 82 |
+
Fortran code. In some cases, it might be worth using this old API.
|
| 83 |
+
|
| 84 |
+
.. autosummary::
|
| 85 |
+
:toctree: generated/
|
| 86 |
+
|
| 87 |
+
odeint -- General integration of ordinary differential equations.
|
| 88 |
+
ode -- Integrate ODE using VODE and ZVODE routines.
|
| 89 |
+
complex_ode -- Convert a complex-valued ODE to real-valued and integrate.
|
| 90 |
+
ODEintWarning -- Warning raised during the execution of `odeint`.
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
Solving boundary value problems for ODE systems
|
| 94 |
+
===============================================
|
| 95 |
+
|
| 96 |
+
.. autosummary::
|
| 97 |
+
:toctree: generated/
|
| 98 |
+
|
| 99 |
+
solve_bvp -- Solve a boundary value problem for a system of ODEs.
|
| 100 |
+
""" # noqa: E501
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
from ._quadrature import *
|
| 104 |
+
from ._odepack_py import *
|
| 105 |
+
from ._quadpack_py import *
|
| 106 |
+
from ._ode import *
|
| 107 |
+
from ._bvp import solve_bvp
|
| 108 |
+
from ._ivp import (solve_ivp, OdeSolution, DenseOutput,
|
| 109 |
+
OdeSolver, RK23, RK45, DOP853, Radau, BDF, LSODA)
|
| 110 |
+
from ._quad_vec import quad_vec
|
| 111 |
+
from ._tanhsinh import nsum, tanhsinh
|
| 112 |
+
from ._cubature import cubature
|
| 113 |
+
from ._lebedev import lebedev_rule
|
| 114 |
+
|
| 115 |
+
# Deprecated namespaces, to be removed in v2.0.0
|
| 116 |
+
from . import dop, lsoda, vode, odepack, quadpack
|
| 117 |
+
|
| 118 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
| 119 |
+
|
| 120 |
+
from scipy._lib._testutils import PytestTester
|
| 121 |
+
test = PytestTester(__name__)
|
| 122 |
+
del PytestTester
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc
ADDED
|
Binary file (35.7 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc
ADDED
|
Binary file (38.4 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc
ADDED
|
Binary file (621 Bytes). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc
ADDED
|
Binary file (624 Bytes). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_bvp.py
ADDED
|
@@ -0,0 +1,1154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Boundary value problem solver."""
|
| 2 |
+
from warnings import warn
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.linalg import pinv
|
| 6 |
+
|
| 7 |
+
from scipy.sparse import coo_matrix, csc_matrix
|
| 8 |
+
from scipy.sparse.linalg import splu
|
| 9 |
+
from scipy.optimize import OptimizeResult
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
EPS = np.finfo(float).eps
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def estimate_fun_jac(fun, x, y, p, f0=None):
|
| 16 |
+
"""Estimate derivatives of an ODE system rhs with forward differences.
|
| 17 |
+
|
| 18 |
+
Returns
|
| 19 |
+
-------
|
| 20 |
+
df_dy : ndarray, shape (n, n, m)
|
| 21 |
+
Derivatives with respect to y. An element (i, j, q) corresponds to
|
| 22 |
+
d f_i(x_q, y_q) / d (y_q)_j.
|
| 23 |
+
df_dp : ndarray with shape (n, k, m) or None
|
| 24 |
+
Derivatives with respect to p. An element (i, j, q) corresponds to
|
| 25 |
+
d f_i(x_q, y_q, p) / d p_j. If `p` is empty, None is returned.
|
| 26 |
+
"""
|
| 27 |
+
n, m = y.shape
|
| 28 |
+
if f0 is None:
|
| 29 |
+
f0 = fun(x, y, p)
|
| 30 |
+
|
| 31 |
+
dtype = y.dtype
|
| 32 |
+
|
| 33 |
+
df_dy = np.empty((n, n, m), dtype=dtype)
|
| 34 |
+
h = EPS**0.5 * (1 + np.abs(y))
|
| 35 |
+
for i in range(n):
|
| 36 |
+
y_new = y.copy()
|
| 37 |
+
y_new[i] += h[i]
|
| 38 |
+
hi = y_new[i] - y[i]
|
| 39 |
+
f_new = fun(x, y_new, p)
|
| 40 |
+
df_dy[:, i, :] = (f_new - f0) / hi
|
| 41 |
+
|
| 42 |
+
k = p.shape[0]
|
| 43 |
+
if k == 0:
|
| 44 |
+
df_dp = None
|
| 45 |
+
else:
|
| 46 |
+
df_dp = np.empty((n, k, m), dtype=dtype)
|
| 47 |
+
h = EPS**0.5 * (1 + np.abs(p))
|
| 48 |
+
for i in range(k):
|
| 49 |
+
p_new = p.copy()
|
| 50 |
+
p_new[i] += h[i]
|
| 51 |
+
hi = p_new[i] - p[i]
|
| 52 |
+
f_new = fun(x, y, p_new)
|
| 53 |
+
df_dp[:, i, :] = (f_new - f0) / hi
|
| 54 |
+
|
| 55 |
+
return df_dy, df_dp
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def estimate_bc_jac(bc, ya, yb, p, bc0=None):
|
| 59 |
+
"""Estimate derivatives of boundary conditions with forward differences.
|
| 60 |
+
|
| 61 |
+
Returns
|
| 62 |
+
-------
|
| 63 |
+
dbc_dya : ndarray, shape (n + k, n)
|
| 64 |
+
Derivatives with respect to ya. An element (i, j) corresponds to
|
| 65 |
+
d bc_i / d ya_j.
|
| 66 |
+
dbc_dyb : ndarray, shape (n + k, n)
|
| 67 |
+
Derivatives with respect to yb. An element (i, j) corresponds to
|
| 68 |
+
d bc_i / d ya_j.
|
| 69 |
+
dbc_dp : ndarray with shape (n + k, k) or None
|
| 70 |
+
Derivatives with respect to p. An element (i, j) corresponds to
|
| 71 |
+
d bc_i / d p_j. If `p` is empty, None is returned.
|
| 72 |
+
"""
|
| 73 |
+
n = ya.shape[0]
|
| 74 |
+
k = p.shape[0]
|
| 75 |
+
|
| 76 |
+
if bc0 is None:
|
| 77 |
+
bc0 = bc(ya, yb, p)
|
| 78 |
+
|
| 79 |
+
dtype = ya.dtype
|
| 80 |
+
|
| 81 |
+
dbc_dya = np.empty((n, n + k), dtype=dtype)
|
| 82 |
+
h = EPS**0.5 * (1 + np.abs(ya))
|
| 83 |
+
for i in range(n):
|
| 84 |
+
ya_new = ya.copy()
|
| 85 |
+
ya_new[i] += h[i]
|
| 86 |
+
hi = ya_new[i] - ya[i]
|
| 87 |
+
bc_new = bc(ya_new, yb, p)
|
| 88 |
+
dbc_dya[i] = (bc_new - bc0) / hi
|
| 89 |
+
dbc_dya = dbc_dya.T
|
| 90 |
+
|
| 91 |
+
h = EPS**0.5 * (1 + np.abs(yb))
|
| 92 |
+
dbc_dyb = np.empty((n, n + k), dtype=dtype)
|
| 93 |
+
for i in range(n):
|
| 94 |
+
yb_new = yb.copy()
|
| 95 |
+
yb_new[i] += h[i]
|
| 96 |
+
hi = yb_new[i] - yb[i]
|
| 97 |
+
bc_new = bc(ya, yb_new, p)
|
| 98 |
+
dbc_dyb[i] = (bc_new - bc0) / hi
|
| 99 |
+
dbc_dyb = dbc_dyb.T
|
| 100 |
+
|
| 101 |
+
if k == 0:
|
| 102 |
+
dbc_dp = None
|
| 103 |
+
else:
|
| 104 |
+
h = EPS**0.5 * (1 + np.abs(p))
|
| 105 |
+
dbc_dp = np.empty((k, n + k), dtype=dtype)
|
| 106 |
+
for i in range(k):
|
| 107 |
+
p_new = p.copy()
|
| 108 |
+
p_new[i] += h[i]
|
| 109 |
+
hi = p_new[i] - p[i]
|
| 110 |
+
bc_new = bc(ya, yb, p_new)
|
| 111 |
+
dbc_dp[i] = (bc_new - bc0) / hi
|
| 112 |
+
dbc_dp = dbc_dp.T
|
| 113 |
+
|
| 114 |
+
return dbc_dya, dbc_dyb, dbc_dp
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def compute_jac_indices(n, m, k):
|
| 118 |
+
"""Compute indices for the collocation system Jacobian construction.
|
| 119 |
+
|
| 120 |
+
See `construct_global_jac` for the explanation.
|
| 121 |
+
"""
|
| 122 |
+
i_col = np.repeat(np.arange((m - 1) * n), n)
|
| 123 |
+
j_col = (np.tile(np.arange(n), n * (m - 1)) +
|
| 124 |
+
np.repeat(np.arange(m - 1) * n, n**2))
|
| 125 |
+
|
| 126 |
+
i_bc = np.repeat(np.arange((m - 1) * n, m * n + k), n)
|
| 127 |
+
j_bc = np.tile(np.arange(n), n + k)
|
| 128 |
+
|
| 129 |
+
i_p_col = np.repeat(np.arange((m - 1) * n), k)
|
| 130 |
+
j_p_col = np.tile(np.arange(m * n, m * n + k), (m - 1) * n)
|
| 131 |
+
|
| 132 |
+
i_p_bc = np.repeat(np.arange((m - 1) * n, m * n + k), k)
|
| 133 |
+
j_p_bc = np.tile(np.arange(m * n, m * n + k), n + k)
|
| 134 |
+
|
| 135 |
+
i = np.hstack((i_col, i_col, i_bc, i_bc, i_p_col, i_p_bc))
|
| 136 |
+
j = np.hstack((j_col, j_col + n,
|
| 137 |
+
j_bc, j_bc + (m - 1) * n,
|
| 138 |
+
j_p_col, j_p_bc))
|
| 139 |
+
|
| 140 |
+
return i, j
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def stacked_matmul(a, b):
|
| 144 |
+
"""Stacked matrix multiply: out[i,:,:] = np.dot(a[i,:,:], b[i,:,:]).
|
| 145 |
+
|
| 146 |
+
Empirical optimization. Use outer Python loop and BLAS for large
|
| 147 |
+
matrices, otherwise use a single einsum call.
|
| 148 |
+
"""
|
| 149 |
+
if a.shape[1] > 50:
|
| 150 |
+
out = np.empty((a.shape[0], a.shape[1], b.shape[2]))
|
| 151 |
+
for i in range(a.shape[0]):
|
| 152 |
+
out[i] = np.dot(a[i], b[i])
|
| 153 |
+
return out
|
| 154 |
+
else:
|
| 155 |
+
return np.einsum('...ij,...jk->...ik', a, b)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy, df_dy_middle, df_dp,
|
| 159 |
+
df_dp_middle, dbc_dya, dbc_dyb, dbc_dp):
|
| 160 |
+
"""Construct the Jacobian of the collocation system.
|
| 161 |
+
|
| 162 |
+
There are n * m + k functions: m - 1 collocations residuals, each
|
| 163 |
+
containing n components, followed by n + k boundary condition residuals.
|
| 164 |
+
|
| 165 |
+
There are n * m + k variables: m vectors of y, each containing n
|
| 166 |
+
components, followed by k values of vector p.
|
| 167 |
+
|
| 168 |
+
For example, let m = 4, n = 2 and k = 1, then the Jacobian will have
|
| 169 |
+
the following sparsity structure:
|
| 170 |
+
|
| 171 |
+
1 1 2 2 0 0 0 0 5
|
| 172 |
+
1 1 2 2 0 0 0 0 5
|
| 173 |
+
0 0 1 1 2 2 0 0 5
|
| 174 |
+
0 0 1 1 2 2 0 0 5
|
| 175 |
+
0 0 0 0 1 1 2 2 5
|
| 176 |
+
0 0 0 0 1 1 2 2 5
|
| 177 |
+
|
| 178 |
+
3 3 0 0 0 0 4 4 6
|
| 179 |
+
3 3 0 0 0 0 4 4 6
|
| 180 |
+
3 3 0 0 0 0 4 4 6
|
| 181 |
+
|
| 182 |
+
Zeros denote identically zero values, other values denote different kinds
|
| 183 |
+
of blocks in the matrix (see below). The blank row indicates the separation
|
| 184 |
+
of collocation residuals from boundary conditions. And the blank column
|
| 185 |
+
indicates the separation of y values from p values.
|
| 186 |
+
|
| 187 |
+
Refer to [1]_ (p. 306) for the formula of n x n blocks for derivatives
|
| 188 |
+
of collocation residuals with respect to y.
|
| 189 |
+
|
| 190 |
+
Parameters
|
| 191 |
+
----------
|
| 192 |
+
n : int
|
| 193 |
+
Number of equations in the ODE system.
|
| 194 |
+
m : int
|
| 195 |
+
Number of nodes in the mesh.
|
| 196 |
+
k : int
|
| 197 |
+
Number of the unknown parameters.
|
| 198 |
+
i_jac, j_jac : ndarray
|
| 199 |
+
Row and column indices returned by `compute_jac_indices`. They
|
| 200 |
+
represent different blocks in the Jacobian matrix in the following
|
| 201 |
+
order (see the scheme above):
|
| 202 |
+
|
| 203 |
+
* 1: m - 1 diagonal n x n blocks for the collocation residuals.
|
| 204 |
+
* 2: m - 1 off-diagonal n x n blocks for the collocation residuals.
|
| 205 |
+
* 3 : (n + k) x n block for the dependency of the boundary
|
| 206 |
+
conditions on ya.
|
| 207 |
+
* 4: (n + k) x n block for the dependency of the boundary
|
| 208 |
+
conditions on yb.
|
| 209 |
+
* 5: (m - 1) * n x k block for the dependency of the collocation
|
| 210 |
+
residuals on p.
|
| 211 |
+
* 6: (n + k) x k block for the dependency of the boundary
|
| 212 |
+
conditions on p.
|
| 213 |
+
|
| 214 |
+
df_dy : ndarray, shape (n, n, m)
|
| 215 |
+
Jacobian of f with respect to y computed at the mesh nodes.
|
| 216 |
+
df_dy_middle : ndarray, shape (n, n, m - 1)
|
| 217 |
+
Jacobian of f with respect to y computed at the middle between the
|
| 218 |
+
mesh nodes.
|
| 219 |
+
df_dp : ndarray with shape (n, k, m) or None
|
| 220 |
+
Jacobian of f with respect to p computed at the mesh nodes.
|
| 221 |
+
df_dp_middle : ndarray with shape (n, k, m - 1) or None
|
| 222 |
+
Jacobian of f with respect to p computed at the middle between the
|
| 223 |
+
mesh nodes.
|
| 224 |
+
dbc_dya, dbc_dyb : ndarray, shape (n, n)
|
| 225 |
+
Jacobian of bc with respect to ya and yb.
|
| 226 |
+
dbc_dp : ndarray with shape (n, k) or None
|
| 227 |
+
Jacobian of bc with respect to p.
|
| 228 |
+
|
| 229 |
+
Returns
|
| 230 |
+
-------
|
| 231 |
+
J : csc_matrix, shape (n * m + k, n * m + k)
|
| 232 |
+
Jacobian of the collocation system in a sparse form.
|
| 233 |
+
|
| 234 |
+
References
|
| 235 |
+
----------
|
| 236 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 237 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 238 |
+
Number 3, pp. 299-316, 2001.
|
| 239 |
+
"""
|
| 240 |
+
df_dy = np.transpose(df_dy, (2, 0, 1))
|
| 241 |
+
df_dy_middle = np.transpose(df_dy_middle, (2, 0, 1))
|
| 242 |
+
|
| 243 |
+
h = h[:, np.newaxis, np.newaxis]
|
| 244 |
+
|
| 245 |
+
dtype = df_dy.dtype
|
| 246 |
+
|
| 247 |
+
# Computing diagonal n x n blocks.
|
| 248 |
+
dPhi_dy_0 = np.empty((m - 1, n, n), dtype=dtype)
|
| 249 |
+
dPhi_dy_0[:] = -np.identity(n)
|
| 250 |
+
dPhi_dy_0 -= h / 6 * (df_dy[:-1] + 2 * df_dy_middle)
|
| 251 |
+
T = stacked_matmul(df_dy_middle, df_dy[:-1])
|
| 252 |
+
dPhi_dy_0 -= h**2 / 12 * T
|
| 253 |
+
|
| 254 |
+
# Computing off-diagonal n x n blocks.
|
| 255 |
+
dPhi_dy_1 = np.empty((m - 1, n, n), dtype=dtype)
|
| 256 |
+
dPhi_dy_1[:] = np.identity(n)
|
| 257 |
+
dPhi_dy_1 -= h / 6 * (df_dy[1:] + 2 * df_dy_middle)
|
| 258 |
+
T = stacked_matmul(df_dy_middle, df_dy[1:])
|
| 259 |
+
dPhi_dy_1 += h**2 / 12 * T
|
| 260 |
+
|
| 261 |
+
values = np.hstack((dPhi_dy_0.ravel(), dPhi_dy_1.ravel(), dbc_dya.ravel(),
|
| 262 |
+
dbc_dyb.ravel()))
|
| 263 |
+
|
| 264 |
+
if k > 0:
|
| 265 |
+
df_dp = np.transpose(df_dp, (2, 0, 1))
|
| 266 |
+
df_dp_middle = np.transpose(df_dp_middle, (2, 0, 1))
|
| 267 |
+
T = stacked_matmul(df_dy_middle, df_dp[:-1] - df_dp[1:])
|
| 268 |
+
df_dp_middle += 0.125 * h * T
|
| 269 |
+
dPhi_dp = -h/6 * (df_dp[:-1] + df_dp[1:] + 4 * df_dp_middle)
|
| 270 |
+
values = np.hstack((values, dPhi_dp.ravel(), dbc_dp.ravel()))
|
| 271 |
+
|
| 272 |
+
J = coo_matrix((values, (i_jac, j_jac)))
|
| 273 |
+
return csc_matrix(J)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def collocation_fun(fun, y, p, x, h):
|
| 277 |
+
"""Evaluate collocation residuals.
|
| 278 |
+
|
| 279 |
+
This function lies in the core of the method. The solution is sought
|
| 280 |
+
as a cubic C1 continuous spline with derivatives matching the ODE rhs
|
| 281 |
+
at given nodes `x`. Collocation conditions are formed from the equality
|
| 282 |
+
of the spline derivatives and rhs of the ODE system in the middle points
|
| 283 |
+
between nodes.
|
| 284 |
+
|
| 285 |
+
Such method is classified to Lobbato IIIA family in ODE literature.
|
| 286 |
+
Refer to [1]_ for the formula and some discussion.
|
| 287 |
+
|
| 288 |
+
Returns
|
| 289 |
+
-------
|
| 290 |
+
col_res : ndarray, shape (n, m - 1)
|
| 291 |
+
Collocation residuals at the middle points of the mesh intervals.
|
| 292 |
+
y_middle : ndarray, shape (n, m - 1)
|
| 293 |
+
Values of the cubic spline evaluated at the middle points of the mesh
|
| 294 |
+
intervals.
|
| 295 |
+
f : ndarray, shape (n, m)
|
| 296 |
+
RHS of the ODE system evaluated at the mesh nodes.
|
| 297 |
+
f_middle : ndarray, shape (n, m - 1)
|
| 298 |
+
RHS of the ODE system evaluated at the middle points of the mesh
|
| 299 |
+
intervals (and using `y_middle`).
|
| 300 |
+
|
| 301 |
+
References
|
| 302 |
+
----------
|
| 303 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 304 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 305 |
+
Number 3, pp. 299-316, 2001.
|
| 306 |
+
"""
|
| 307 |
+
f = fun(x, y, p)
|
| 308 |
+
y_middle = (0.5 * (y[:, 1:] + y[:, :-1]) -
|
| 309 |
+
0.125 * h * (f[:, 1:] - f[:, :-1]))
|
| 310 |
+
f_middle = fun(x[:-1] + 0.5 * h, y_middle, p)
|
| 311 |
+
col_res = y[:, 1:] - y[:, :-1] - h / 6 * (f[:, :-1] + f[:, 1:] +
|
| 312 |
+
4 * f_middle)
|
| 313 |
+
|
| 314 |
+
return col_res, y_middle, f, f_middle
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def prepare_sys(n, m, k, fun, bc, fun_jac, bc_jac, x, h):
|
| 318 |
+
"""Create the function and the Jacobian for the collocation system."""
|
| 319 |
+
x_middle = x[:-1] + 0.5 * h
|
| 320 |
+
i_jac, j_jac = compute_jac_indices(n, m, k)
|
| 321 |
+
|
| 322 |
+
def col_fun(y, p):
|
| 323 |
+
return collocation_fun(fun, y, p, x, h)
|
| 324 |
+
|
| 325 |
+
def sys_jac(y, p, y_middle, f, f_middle, bc0):
|
| 326 |
+
if fun_jac is None:
|
| 327 |
+
df_dy, df_dp = estimate_fun_jac(fun, x, y, p, f)
|
| 328 |
+
df_dy_middle, df_dp_middle = estimate_fun_jac(
|
| 329 |
+
fun, x_middle, y_middle, p, f_middle)
|
| 330 |
+
else:
|
| 331 |
+
df_dy, df_dp = fun_jac(x, y, p)
|
| 332 |
+
df_dy_middle, df_dp_middle = fun_jac(x_middle, y_middle, p)
|
| 333 |
+
|
| 334 |
+
if bc_jac is None:
|
| 335 |
+
dbc_dya, dbc_dyb, dbc_dp = estimate_bc_jac(bc, y[:, 0], y[:, -1],
|
| 336 |
+
p, bc0)
|
| 337 |
+
else:
|
| 338 |
+
dbc_dya, dbc_dyb, dbc_dp = bc_jac(y[:, 0], y[:, -1], p)
|
| 339 |
+
|
| 340 |
+
return construct_global_jac(n, m, k, i_jac, j_jac, h, df_dy,
|
| 341 |
+
df_dy_middle, df_dp, df_dp_middle, dbc_dya,
|
| 342 |
+
dbc_dyb, dbc_dp)
|
| 343 |
+
|
| 344 |
+
return col_fun, sys_jac
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def solve_newton(n, m, h, col_fun, bc, jac, y, p, B, bvp_tol, bc_tol):
|
| 348 |
+
"""Solve the nonlinear collocation system by a Newton method.
|
| 349 |
+
|
| 350 |
+
This is a simple Newton method with a backtracking line search. As
|
| 351 |
+
advised in [1]_, an affine-invariant criterion function F = ||J^-1 r||^2
|
| 352 |
+
is used, where J is the Jacobian matrix at the current iteration and r is
|
| 353 |
+
the vector or collocation residuals (values of the system lhs).
|
| 354 |
+
|
| 355 |
+
The method alters between full Newton iterations and the fixed-Jacobian
|
| 356 |
+
iterations based
|
| 357 |
+
|
| 358 |
+
There are other tricks proposed in [1]_, but they are not used as they
|
| 359 |
+
don't seem to improve anything significantly, and even break the
|
| 360 |
+
convergence on some test problems I tried.
|
| 361 |
+
|
| 362 |
+
All important parameters of the algorithm are defined inside the function.
|
| 363 |
+
|
| 364 |
+
Parameters
|
| 365 |
+
----------
|
| 366 |
+
n : int
|
| 367 |
+
Number of equations in the ODE system.
|
| 368 |
+
m : int
|
| 369 |
+
Number of nodes in the mesh.
|
| 370 |
+
h : ndarray, shape (m-1,)
|
| 371 |
+
Mesh intervals.
|
| 372 |
+
col_fun : callable
|
| 373 |
+
Function computing collocation residuals.
|
| 374 |
+
bc : callable
|
| 375 |
+
Function computing boundary condition residuals.
|
| 376 |
+
jac : callable
|
| 377 |
+
Function computing the Jacobian of the whole system (including
|
| 378 |
+
collocation and boundary condition residuals). It is supposed to
|
| 379 |
+
return csc_matrix.
|
| 380 |
+
y : ndarray, shape (n, m)
|
| 381 |
+
Initial guess for the function values at the mesh nodes.
|
| 382 |
+
p : ndarray, shape (k,)
|
| 383 |
+
Initial guess for the unknown parameters.
|
| 384 |
+
B : ndarray with shape (n, n) or None
|
| 385 |
+
Matrix to force the S y(a) = 0 condition for a problems with the
|
| 386 |
+
singular term. If None, the singular term is assumed to be absent.
|
| 387 |
+
bvp_tol : float
|
| 388 |
+
Tolerance to which we want to solve a BVP.
|
| 389 |
+
bc_tol : float
|
| 390 |
+
Tolerance to which we want to satisfy the boundary conditions.
|
| 391 |
+
|
| 392 |
+
Returns
|
| 393 |
+
-------
|
| 394 |
+
y : ndarray, shape (n, m)
|
| 395 |
+
Final iterate for the function values at the mesh nodes.
|
| 396 |
+
p : ndarray, shape (k,)
|
| 397 |
+
Final iterate for the unknown parameters.
|
| 398 |
+
singular : bool
|
| 399 |
+
True, if the LU decomposition failed because Jacobian turned out
|
| 400 |
+
to be singular.
|
| 401 |
+
|
| 402 |
+
References
|
| 403 |
+
----------
|
| 404 |
+
.. [1] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
|
| 405 |
+
Boundary Value Problems for Ordinary Differential Equations"
|
| 406 |
+
"""
|
| 407 |
+
# We know that the solution residuals at the middle points of the mesh
|
| 408 |
+
# are connected with collocation residuals r_middle = 1.5 * col_res / h.
|
| 409 |
+
# As our BVP solver tries to decrease relative residuals below a certain
|
| 410 |
+
# tolerance, it seems reasonable to terminated Newton iterations by
|
| 411 |
+
# comparison of r_middle / (1 + np.abs(f_middle)) with a certain threshold,
|
| 412 |
+
# which we choose to be 1.5 orders lower than the BVP tolerance. We rewrite
|
| 413 |
+
# the condition as col_res < tol_r * (1 + np.abs(f_middle)), then tol_r
|
| 414 |
+
# should be computed as follows:
|
| 415 |
+
tol_r = 2/3 * h * 5e-2 * bvp_tol
|
| 416 |
+
|
| 417 |
+
# Maximum allowed number of Jacobian evaluation and factorization, in
|
| 418 |
+
# other words, the maximum number of full Newton iterations. A small value
|
| 419 |
+
# is recommended in the literature.
|
| 420 |
+
max_njev = 4
|
| 421 |
+
|
| 422 |
+
# Maximum number of iterations, considering that some of them can be
|
| 423 |
+
# performed with the fixed Jacobian. In theory, such iterations are cheap,
|
| 424 |
+
# but it's not that simple in Python.
|
| 425 |
+
max_iter = 8
|
| 426 |
+
|
| 427 |
+
# Minimum relative improvement of the criterion function to accept the
|
| 428 |
+
# step (Armijo constant).
|
| 429 |
+
sigma = 0.2
|
| 430 |
+
|
| 431 |
+
# Step size decrease factor for backtracking.
|
| 432 |
+
tau = 0.5
|
| 433 |
+
|
| 434 |
+
# Maximum number of backtracking steps, the minimum step is then
|
| 435 |
+
# tau ** n_trial.
|
| 436 |
+
n_trial = 4
|
| 437 |
+
|
| 438 |
+
col_res, y_middle, f, f_middle = col_fun(y, p)
|
| 439 |
+
bc_res = bc(y[:, 0], y[:, -1], p)
|
| 440 |
+
res = np.hstack((col_res.ravel(order='F'), bc_res))
|
| 441 |
+
|
| 442 |
+
njev = 0
|
| 443 |
+
singular = False
|
| 444 |
+
recompute_jac = True
|
| 445 |
+
for iteration in range(max_iter):
|
| 446 |
+
if recompute_jac:
|
| 447 |
+
J = jac(y, p, y_middle, f, f_middle, bc_res)
|
| 448 |
+
njev += 1
|
| 449 |
+
try:
|
| 450 |
+
LU = splu(J)
|
| 451 |
+
except RuntimeError:
|
| 452 |
+
singular = True
|
| 453 |
+
break
|
| 454 |
+
|
| 455 |
+
step = LU.solve(res)
|
| 456 |
+
cost = np.dot(step, step)
|
| 457 |
+
|
| 458 |
+
y_step = step[:m * n].reshape((n, m), order='F')
|
| 459 |
+
p_step = step[m * n:]
|
| 460 |
+
|
| 461 |
+
alpha = 1
|
| 462 |
+
for trial in range(n_trial + 1):
|
| 463 |
+
y_new = y - alpha * y_step
|
| 464 |
+
if B is not None:
|
| 465 |
+
y_new[:, 0] = np.dot(B, y_new[:, 0])
|
| 466 |
+
p_new = p - alpha * p_step
|
| 467 |
+
|
| 468 |
+
col_res, y_middle, f, f_middle = col_fun(y_new, p_new)
|
| 469 |
+
bc_res = bc(y_new[:, 0], y_new[:, -1], p_new)
|
| 470 |
+
res = np.hstack((col_res.ravel(order='F'), bc_res))
|
| 471 |
+
|
| 472 |
+
step_new = LU.solve(res)
|
| 473 |
+
cost_new = np.dot(step_new, step_new)
|
| 474 |
+
if cost_new < (1 - 2 * alpha * sigma) * cost:
|
| 475 |
+
break
|
| 476 |
+
|
| 477 |
+
if trial < n_trial:
|
| 478 |
+
alpha *= tau
|
| 479 |
+
|
| 480 |
+
y = y_new
|
| 481 |
+
p = p_new
|
| 482 |
+
|
| 483 |
+
if njev == max_njev:
|
| 484 |
+
break
|
| 485 |
+
|
| 486 |
+
if (np.all(np.abs(col_res) < tol_r * (1 + np.abs(f_middle))) and
|
| 487 |
+
np.all(np.abs(bc_res) < bc_tol)):
|
| 488 |
+
break
|
| 489 |
+
|
| 490 |
+
# If the full step was taken, then we are going to continue with
|
| 491 |
+
# the same Jacobian. This is the approach of BVP_SOLVER.
|
| 492 |
+
if alpha == 1:
|
| 493 |
+
step = step_new
|
| 494 |
+
cost = cost_new
|
| 495 |
+
recompute_jac = False
|
| 496 |
+
else:
|
| 497 |
+
recompute_jac = True
|
| 498 |
+
|
| 499 |
+
return y, p, singular
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def print_iteration_header():
|
| 503 |
+
print(f"{'Iteration':^15}{'Max residual':^15}{'Max BC residual':^15}"
|
| 504 |
+
f"{'Total nodes':^15}{'Nodes added':^15}")
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def print_iteration_progress(iteration, residual, bc_residual, total_nodes,
|
| 508 |
+
nodes_added):
|
| 509 |
+
print(f"{iteration:^15}{residual:^15.2e}{bc_residual:^15.2e}"
|
| 510 |
+
f"{total_nodes:^15}{nodes_added:^15}")
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class BVPResult(OptimizeResult):
|
| 514 |
+
pass
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
TERMINATION_MESSAGES = {
|
| 518 |
+
0: "The algorithm converged to the desired accuracy.",
|
| 519 |
+
1: "The maximum number of mesh nodes is exceeded.",
|
| 520 |
+
2: "A singular Jacobian encountered when solving the collocation system.",
|
| 521 |
+
3: "The solver was unable to satisfy boundary conditions tolerance on iteration 10."
|
| 522 |
+
}
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
def estimate_rms_residuals(fun, sol, x, h, p, r_middle, f_middle):
|
| 526 |
+
"""Estimate rms values of collocation residuals using Lobatto quadrature.
|
| 527 |
+
|
| 528 |
+
The residuals are defined as the difference between the derivatives of
|
| 529 |
+
our solution and rhs of the ODE system. We use relative residuals, i.e.,
|
| 530 |
+
normalized by 1 + np.abs(f). RMS values are computed as sqrt from the
|
| 531 |
+
normalized integrals of the squared relative residuals over each interval.
|
| 532 |
+
Integrals are estimated using 5-point Lobatto quadrature [1]_, we use the
|
| 533 |
+
fact that residuals at the mesh nodes are identically zero.
|
| 534 |
+
|
| 535 |
+
In [2] they don't normalize integrals by interval lengths, which gives
|
| 536 |
+
a higher rate of convergence of the residuals by the factor of h**0.5.
|
| 537 |
+
I chose to do such normalization for an ease of interpretation of return
|
| 538 |
+
values as RMS estimates.
|
| 539 |
+
|
| 540 |
+
Returns
|
| 541 |
+
-------
|
| 542 |
+
rms_res : ndarray, shape (m - 1,)
|
| 543 |
+
Estimated rms values of the relative residuals over each interval.
|
| 544 |
+
|
| 545 |
+
References
|
| 546 |
+
----------
|
| 547 |
+
.. [1] http://mathworld.wolfram.com/LobattoQuadrature.html
|
| 548 |
+
.. [2] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 549 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 550 |
+
Number 3, pp. 299-316, 2001.
|
| 551 |
+
"""
|
| 552 |
+
x_middle = x[:-1] + 0.5 * h
|
| 553 |
+
s = 0.5 * h * (3/7)**0.5
|
| 554 |
+
x1 = x_middle + s
|
| 555 |
+
x2 = x_middle - s
|
| 556 |
+
y1 = sol(x1)
|
| 557 |
+
y2 = sol(x2)
|
| 558 |
+
y1_prime = sol(x1, 1)
|
| 559 |
+
y2_prime = sol(x2, 1)
|
| 560 |
+
f1 = fun(x1, y1, p)
|
| 561 |
+
f2 = fun(x2, y2, p)
|
| 562 |
+
r1 = y1_prime - f1
|
| 563 |
+
r2 = y2_prime - f2
|
| 564 |
+
|
| 565 |
+
r_middle /= 1 + np.abs(f_middle)
|
| 566 |
+
r1 /= 1 + np.abs(f1)
|
| 567 |
+
r2 /= 1 + np.abs(f2)
|
| 568 |
+
|
| 569 |
+
r1 = np.sum(np.real(r1 * np.conj(r1)), axis=0)
|
| 570 |
+
r2 = np.sum(np.real(r2 * np.conj(r2)), axis=0)
|
| 571 |
+
r_middle = np.sum(np.real(r_middle * np.conj(r_middle)), axis=0)
|
| 572 |
+
|
| 573 |
+
return (0.5 * (32 / 45 * r_middle + 49 / 90 * (r1 + r2))) ** 0.5
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def create_spline(y, yp, x, h):
|
| 577 |
+
"""Create a cubic spline given values and derivatives.
|
| 578 |
+
|
| 579 |
+
Formulas for the coefficients are taken from interpolate.CubicSpline.
|
| 580 |
+
|
| 581 |
+
Returns
|
| 582 |
+
-------
|
| 583 |
+
sol : PPoly
|
| 584 |
+
Constructed spline as a PPoly instance.
|
| 585 |
+
"""
|
| 586 |
+
from scipy.interpolate import PPoly
|
| 587 |
+
|
| 588 |
+
n, m = y.shape
|
| 589 |
+
c = np.empty((4, n, m - 1), dtype=y.dtype)
|
| 590 |
+
slope = (y[:, 1:] - y[:, :-1]) / h
|
| 591 |
+
t = (yp[:, :-1] + yp[:, 1:] - 2 * slope) / h
|
| 592 |
+
c[0] = t / h
|
| 593 |
+
c[1] = (slope - yp[:, :-1]) / h - t
|
| 594 |
+
c[2] = yp[:, :-1]
|
| 595 |
+
c[3] = y[:, :-1]
|
| 596 |
+
c = np.moveaxis(c, 1, 0)
|
| 597 |
+
|
| 598 |
+
return PPoly(c, x, extrapolate=True, axis=1)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def modify_mesh(x, insert_1, insert_2):
|
| 602 |
+
"""Insert nodes into a mesh.
|
| 603 |
+
|
| 604 |
+
Nodes removal logic is not established, its impact on the solver is
|
| 605 |
+
presumably negligible. So, only insertion is done in this function.
|
| 606 |
+
|
| 607 |
+
Parameters
|
| 608 |
+
----------
|
| 609 |
+
x : ndarray, shape (m,)
|
| 610 |
+
Mesh nodes.
|
| 611 |
+
insert_1 : ndarray
|
| 612 |
+
Intervals to each insert 1 new node in the middle.
|
| 613 |
+
insert_2 : ndarray
|
| 614 |
+
Intervals to each insert 2 new nodes, such that divide an interval
|
| 615 |
+
into 3 equal parts.
|
| 616 |
+
|
| 617 |
+
Returns
|
| 618 |
+
-------
|
| 619 |
+
x_new : ndarray
|
| 620 |
+
New mesh nodes.
|
| 621 |
+
|
| 622 |
+
Notes
|
| 623 |
+
-----
|
| 624 |
+
`insert_1` and `insert_2` should not have common values.
|
| 625 |
+
"""
|
| 626 |
+
# Because np.insert implementation apparently varies with a version of
|
| 627 |
+
# NumPy, we use a simple and reliable approach with sorting.
|
| 628 |
+
return np.sort(np.hstack((
|
| 629 |
+
x,
|
| 630 |
+
0.5 * (x[insert_1] + x[insert_1 + 1]),
|
| 631 |
+
(2 * x[insert_2] + x[insert_2 + 1]) / 3,
|
| 632 |
+
(x[insert_2] + 2 * x[insert_2 + 1]) / 3
|
| 633 |
+
)))
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
def wrap_functions(fun, bc, fun_jac, bc_jac, k, a, S, D, dtype):
|
| 637 |
+
"""Wrap functions for unified usage in the solver."""
|
| 638 |
+
if fun_jac is None:
|
| 639 |
+
fun_jac_wrapped = None
|
| 640 |
+
|
| 641 |
+
if bc_jac is None:
|
| 642 |
+
bc_jac_wrapped = None
|
| 643 |
+
|
| 644 |
+
if k == 0:
|
| 645 |
+
def fun_p(x, y, _):
|
| 646 |
+
return np.asarray(fun(x, y), dtype)
|
| 647 |
+
|
| 648 |
+
def bc_wrapped(ya, yb, _):
|
| 649 |
+
return np.asarray(bc(ya, yb), dtype)
|
| 650 |
+
|
| 651 |
+
if fun_jac is not None:
|
| 652 |
+
def fun_jac_p(x, y, _):
|
| 653 |
+
return np.asarray(fun_jac(x, y), dtype), None
|
| 654 |
+
|
| 655 |
+
if bc_jac is not None:
|
| 656 |
+
def bc_jac_wrapped(ya, yb, _):
|
| 657 |
+
dbc_dya, dbc_dyb = bc_jac(ya, yb)
|
| 658 |
+
return (np.asarray(dbc_dya, dtype),
|
| 659 |
+
np.asarray(dbc_dyb, dtype), None)
|
| 660 |
+
else:
|
| 661 |
+
def fun_p(x, y, p):
|
| 662 |
+
return np.asarray(fun(x, y, p), dtype)
|
| 663 |
+
|
| 664 |
+
def bc_wrapped(x, y, p):
|
| 665 |
+
return np.asarray(bc(x, y, p), dtype)
|
| 666 |
+
|
| 667 |
+
if fun_jac is not None:
|
| 668 |
+
def fun_jac_p(x, y, p):
|
| 669 |
+
df_dy, df_dp = fun_jac(x, y, p)
|
| 670 |
+
return np.asarray(df_dy, dtype), np.asarray(df_dp, dtype)
|
| 671 |
+
|
| 672 |
+
if bc_jac is not None:
|
| 673 |
+
def bc_jac_wrapped(ya, yb, p):
|
| 674 |
+
dbc_dya, dbc_dyb, dbc_dp = bc_jac(ya, yb, p)
|
| 675 |
+
return (np.asarray(dbc_dya, dtype), np.asarray(dbc_dyb, dtype),
|
| 676 |
+
np.asarray(dbc_dp, dtype))
|
| 677 |
+
|
| 678 |
+
if S is None:
|
| 679 |
+
fun_wrapped = fun_p
|
| 680 |
+
else:
|
| 681 |
+
def fun_wrapped(x, y, p):
|
| 682 |
+
f = fun_p(x, y, p)
|
| 683 |
+
if x[0] == a:
|
| 684 |
+
f[:, 0] = np.dot(D, f[:, 0])
|
| 685 |
+
f[:, 1:] += np.dot(S, y[:, 1:]) / (x[1:] - a)
|
| 686 |
+
else:
|
| 687 |
+
f += np.dot(S, y) / (x - a)
|
| 688 |
+
return f
|
| 689 |
+
|
| 690 |
+
if fun_jac is not None:
|
| 691 |
+
if S is None:
|
| 692 |
+
fun_jac_wrapped = fun_jac_p
|
| 693 |
+
else:
|
| 694 |
+
Sr = S[:, :, np.newaxis]
|
| 695 |
+
|
| 696 |
+
def fun_jac_wrapped(x, y, p):
|
| 697 |
+
df_dy, df_dp = fun_jac_p(x, y, p)
|
| 698 |
+
if x[0] == a:
|
| 699 |
+
df_dy[:, :, 0] = np.dot(D, df_dy[:, :, 0])
|
| 700 |
+
df_dy[:, :, 1:] += Sr / (x[1:] - a)
|
| 701 |
+
else:
|
| 702 |
+
df_dy += Sr / (x - a)
|
| 703 |
+
|
| 704 |
+
return df_dy, df_dp
|
| 705 |
+
|
| 706 |
+
return fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
def solve_bvp(fun, bc, x, y, p=None, S=None, fun_jac=None, bc_jac=None,
|
| 710 |
+
tol=1e-3, max_nodes=1000, verbose=0, bc_tol=None):
|
| 711 |
+
"""Solve a boundary value problem for a system of ODEs.
|
| 712 |
+
|
| 713 |
+
This function numerically solves a first order system of ODEs subject to
|
| 714 |
+
two-point boundary conditions::
|
| 715 |
+
|
| 716 |
+
dy / dx = f(x, y, p) + S * y / (x - a), a <= x <= b
|
| 717 |
+
bc(y(a), y(b), p) = 0
|
| 718 |
+
|
| 719 |
+
Here x is a 1-D independent variable, y(x) is an n-D
|
| 720 |
+
vector-valued function and p is a k-D vector of unknown
|
| 721 |
+
parameters which is to be found along with y(x). For the problem to be
|
| 722 |
+
determined, there must be n + k boundary conditions, i.e., bc must be an
|
| 723 |
+
(n + k)-D function.
|
| 724 |
+
|
| 725 |
+
The last singular term on the right-hand side of the system is optional.
|
| 726 |
+
It is defined by an n-by-n matrix S, such that the solution must satisfy
|
| 727 |
+
S y(a) = 0. This condition will be forced during iterations, so it must not
|
| 728 |
+
contradict boundary conditions. See [2]_ for the explanation how this term
|
| 729 |
+
is handled when solving BVPs numerically.
|
| 730 |
+
|
| 731 |
+
Problems in a complex domain can be solved as well. In this case, y and p
|
| 732 |
+
are considered to be complex, and f and bc are assumed to be complex-valued
|
| 733 |
+
functions, but x stays real. Note that f and bc must be complex
|
| 734 |
+
differentiable (satisfy Cauchy-Riemann equations [4]_), otherwise you
|
| 735 |
+
should rewrite your problem for real and imaginary parts separately. To
|
| 736 |
+
solve a problem in a complex domain, pass an initial guess for y with a
|
| 737 |
+
complex data type (see below).
|
| 738 |
+
|
| 739 |
+
Parameters
|
| 740 |
+
----------
|
| 741 |
+
fun : callable
|
| 742 |
+
Right-hand side of the system. The calling signature is ``fun(x, y)``,
|
| 743 |
+
or ``fun(x, y, p)`` if parameters are present. All arguments are
|
| 744 |
+
ndarray: ``x`` with shape (m,), ``y`` with shape (n, m), meaning that
|
| 745 |
+
``y[:, i]`` corresponds to ``x[i]``, and ``p`` with shape (k,). The
|
| 746 |
+
return value must be an array with shape (n, m) and with the same
|
| 747 |
+
layout as ``y``.
|
| 748 |
+
bc : callable
|
| 749 |
+
Function evaluating residuals of the boundary conditions. The calling
|
| 750 |
+
signature is ``bc(ya, yb)``, or ``bc(ya, yb, p)`` if parameters are
|
| 751 |
+
present. All arguments are ndarray: ``ya`` and ``yb`` with shape (n,),
|
| 752 |
+
and ``p`` with shape (k,). The return value must be an array with
|
| 753 |
+
shape (n + k,).
|
| 754 |
+
x : array_like, shape (m,)
|
| 755 |
+
Initial mesh. Must be a strictly increasing sequence of real numbers
|
| 756 |
+
with ``x[0]=a`` and ``x[-1]=b``.
|
| 757 |
+
y : array_like, shape (n, m)
|
| 758 |
+
Initial guess for the function values at the mesh nodes, ith column
|
| 759 |
+
corresponds to ``x[i]``. For problems in a complex domain pass `y`
|
| 760 |
+
with a complex data type (even if the initial guess is purely real).
|
| 761 |
+
p : array_like with shape (k,) or None, optional
|
| 762 |
+
Initial guess for the unknown parameters. If None (default), it is
|
| 763 |
+
assumed that the problem doesn't depend on any parameters.
|
| 764 |
+
S : array_like with shape (n, n) or None
|
| 765 |
+
Matrix defining the singular term. If None (default), the problem is
|
| 766 |
+
solved without the singular term.
|
| 767 |
+
fun_jac : callable or None, optional
|
| 768 |
+
Function computing derivatives of f with respect to y and p. The
|
| 769 |
+
calling signature is ``fun_jac(x, y)``, or ``fun_jac(x, y, p)`` if
|
| 770 |
+
parameters are present. The return must contain 1 or 2 elements in the
|
| 771 |
+
following order:
|
| 772 |
+
|
| 773 |
+
* df_dy : array_like with shape (n, n, m), where an element
|
| 774 |
+
(i, j, q) equals to d f_i(x_q, y_q, p) / d (y_q)_j.
|
| 775 |
+
* df_dp : array_like with shape (n, k, m), where an element
|
| 776 |
+
(i, j, q) equals to d f_i(x_q, y_q, p) / d p_j.
|
| 777 |
+
|
| 778 |
+
Here q numbers nodes at which x and y are defined, whereas i and j
|
| 779 |
+
number vector components. If the problem is solved without unknown
|
| 780 |
+
parameters, df_dp should not be returned.
|
| 781 |
+
|
| 782 |
+
If `fun_jac` is None (default), the derivatives will be estimated
|
| 783 |
+
by the forward finite differences.
|
| 784 |
+
bc_jac : callable or None, optional
|
| 785 |
+
Function computing derivatives of bc with respect to ya, yb, and p.
|
| 786 |
+
The calling signature is ``bc_jac(ya, yb)``, or ``bc_jac(ya, yb, p)``
|
| 787 |
+
if parameters are present. The return must contain 2 or 3 elements in
|
| 788 |
+
the following order:
|
| 789 |
+
|
| 790 |
+
* dbc_dya : array_like with shape (n, n), where an element (i, j)
|
| 791 |
+
equals to d bc_i(ya, yb, p) / d ya_j.
|
| 792 |
+
* dbc_dyb : array_like with shape (n, n), where an element (i, j)
|
| 793 |
+
equals to d bc_i(ya, yb, p) / d yb_j.
|
| 794 |
+
* dbc_dp : array_like with shape (n, k), where an element (i, j)
|
| 795 |
+
equals to d bc_i(ya, yb, p) / d p_j.
|
| 796 |
+
|
| 797 |
+
If the problem is solved without unknown parameters, dbc_dp should not
|
| 798 |
+
be returned.
|
| 799 |
+
|
| 800 |
+
If `bc_jac` is None (default), the derivatives will be estimated by
|
| 801 |
+
the forward finite differences.
|
| 802 |
+
tol : float, optional
|
| 803 |
+
Desired tolerance of the solution. If we define ``r = y' - f(x, y)``,
|
| 804 |
+
where y is the found solution, then the solver tries to achieve on each
|
| 805 |
+
mesh interval ``norm(r / (1 + abs(f)) < tol``, where ``norm`` is
|
| 806 |
+
estimated in a root mean squared sense (using a numerical quadrature
|
| 807 |
+
formula). Default is 1e-3.
|
| 808 |
+
max_nodes : int, optional
|
| 809 |
+
Maximum allowed number of the mesh nodes. If exceeded, the algorithm
|
| 810 |
+
terminates. Default is 1000.
|
| 811 |
+
verbose : {0, 1, 2}, optional
|
| 812 |
+
Level of algorithm's verbosity:
|
| 813 |
+
|
| 814 |
+
* 0 (default) : work silently.
|
| 815 |
+
* 1 : display a termination report.
|
| 816 |
+
* 2 : display progress during iterations.
|
| 817 |
+
bc_tol : float, optional
|
| 818 |
+
Desired absolute tolerance for the boundary condition residuals: `bc`
|
| 819 |
+
value should satisfy ``abs(bc) < bc_tol`` component-wise.
|
| 820 |
+
Equals to `tol` by default. Up to 10 iterations are allowed to achieve this
|
| 821 |
+
tolerance.
|
| 822 |
+
|
| 823 |
+
Returns
|
| 824 |
+
-------
|
| 825 |
+
Bunch object with the following fields defined:
|
| 826 |
+
sol : PPoly
|
| 827 |
+
Found solution for y as `scipy.interpolate.PPoly` instance, a C1
|
| 828 |
+
continuous cubic spline.
|
| 829 |
+
p : ndarray or None, shape (k,)
|
| 830 |
+
Found parameters. None, if the parameters were not present in the
|
| 831 |
+
problem.
|
| 832 |
+
x : ndarray, shape (m,)
|
| 833 |
+
Nodes of the final mesh.
|
| 834 |
+
y : ndarray, shape (n, m)
|
| 835 |
+
Solution values at the mesh nodes.
|
| 836 |
+
yp : ndarray, shape (n, m)
|
| 837 |
+
Solution derivatives at the mesh nodes.
|
| 838 |
+
rms_residuals : ndarray, shape (m - 1,)
|
| 839 |
+
RMS values of the relative residuals over each mesh interval (see the
|
| 840 |
+
description of `tol` parameter).
|
| 841 |
+
niter : int
|
| 842 |
+
Number of completed iterations.
|
| 843 |
+
status : int
|
| 844 |
+
Reason for algorithm termination:
|
| 845 |
+
|
| 846 |
+
* 0: The algorithm converged to the desired accuracy.
|
| 847 |
+
* 1: The maximum number of mesh nodes is exceeded.
|
| 848 |
+
* 2: A singular Jacobian encountered when solving the collocation
|
| 849 |
+
system.
|
| 850 |
+
|
| 851 |
+
message : string
|
| 852 |
+
Verbal description of the termination reason.
|
| 853 |
+
success : bool
|
| 854 |
+
True if the algorithm converged to the desired accuracy (``status=0``).
|
| 855 |
+
|
| 856 |
+
Notes
|
| 857 |
+
-----
|
| 858 |
+
This function implements a 4th order collocation algorithm with the
|
| 859 |
+
control of residuals similar to [1]_. A collocation system is solved
|
| 860 |
+
by a damped Newton method with an affine-invariant criterion function as
|
| 861 |
+
described in [3]_.
|
| 862 |
+
|
| 863 |
+
Note that in [1]_ integral residuals are defined without normalization
|
| 864 |
+
by interval lengths. So, their definition is different by a multiplier of
|
| 865 |
+
h**0.5 (h is an interval length) from the definition used here.
|
| 866 |
+
|
| 867 |
+
.. versionadded:: 0.18.0
|
| 868 |
+
|
| 869 |
+
References
|
| 870 |
+
----------
|
| 871 |
+
.. [1] J. Kierzenka, L. F. Shampine, "A BVP Solver Based on Residual
|
| 872 |
+
Control and the Maltab PSE", ACM Trans. Math. Softw., Vol. 27,
|
| 873 |
+
Number 3, pp. 299-316, 2001.
|
| 874 |
+
.. [2] L.F. Shampine, P. H. Muir and H. Xu, "A User-Friendly Fortran BVP
|
| 875 |
+
Solver".
|
| 876 |
+
.. [3] U. Ascher, R. Mattheij and R. Russell "Numerical Solution of
|
| 877 |
+
Boundary Value Problems for Ordinary Differential Equations".
|
| 878 |
+
.. [4] `Cauchy-Riemann equations
|
| 879 |
+
<https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
|
| 880 |
+
Wikipedia.
|
| 881 |
+
|
| 882 |
+
Examples
|
| 883 |
+
--------
|
| 884 |
+
In the first example, we solve Bratu's problem::
|
| 885 |
+
|
| 886 |
+
y'' + k * exp(y) = 0
|
| 887 |
+
y(0) = y(1) = 0
|
| 888 |
+
|
| 889 |
+
for k = 1.
|
| 890 |
+
|
| 891 |
+
We rewrite the equation as a first-order system and implement its
|
| 892 |
+
right-hand side evaluation::
|
| 893 |
+
|
| 894 |
+
y1' = y2
|
| 895 |
+
y2' = -exp(y1)
|
| 896 |
+
|
| 897 |
+
>>> import numpy as np
|
| 898 |
+
>>> def fun(x, y):
|
| 899 |
+
... return np.vstack((y[1], -np.exp(y[0])))
|
| 900 |
+
|
| 901 |
+
Implement evaluation of the boundary condition residuals:
|
| 902 |
+
|
| 903 |
+
>>> def bc(ya, yb):
|
| 904 |
+
... return np.array([ya[0], yb[0]])
|
| 905 |
+
|
| 906 |
+
Define the initial mesh with 5 nodes:
|
| 907 |
+
|
| 908 |
+
>>> x = np.linspace(0, 1, 5)
|
| 909 |
+
|
| 910 |
+
This problem is known to have two solutions. To obtain both of them, we
|
| 911 |
+
use two different initial guesses for y. We denote them by subscripts
|
| 912 |
+
a and b.
|
| 913 |
+
|
| 914 |
+
>>> y_a = np.zeros((2, x.size))
|
| 915 |
+
>>> y_b = np.zeros((2, x.size))
|
| 916 |
+
>>> y_b[0] = 3
|
| 917 |
+
|
| 918 |
+
Now we are ready to run the solver.
|
| 919 |
+
|
| 920 |
+
>>> from scipy.integrate import solve_bvp
|
| 921 |
+
>>> res_a = solve_bvp(fun, bc, x, y_a)
|
| 922 |
+
>>> res_b = solve_bvp(fun, bc, x, y_b)
|
| 923 |
+
|
| 924 |
+
Let's plot the two found solutions. We take an advantage of having the
|
| 925 |
+
solution in a spline form to produce a smooth plot.
|
| 926 |
+
|
| 927 |
+
>>> x_plot = np.linspace(0, 1, 100)
|
| 928 |
+
>>> y_plot_a = res_a.sol(x_plot)[0]
|
| 929 |
+
>>> y_plot_b = res_b.sol(x_plot)[0]
|
| 930 |
+
>>> import matplotlib.pyplot as plt
|
| 931 |
+
>>> plt.plot(x_plot, y_plot_a, label='y_a')
|
| 932 |
+
>>> plt.plot(x_plot, y_plot_b, label='y_b')
|
| 933 |
+
>>> plt.legend()
|
| 934 |
+
>>> plt.xlabel("x")
|
| 935 |
+
>>> plt.ylabel("y")
|
| 936 |
+
>>> plt.show()
|
| 937 |
+
|
| 938 |
+
We see that the two solutions have similar shape, but differ in scale
|
| 939 |
+
significantly.
|
| 940 |
+
|
| 941 |
+
In the second example, we solve a simple Sturm-Liouville problem::
|
| 942 |
+
|
| 943 |
+
y'' + k**2 * y = 0
|
| 944 |
+
y(0) = y(1) = 0
|
| 945 |
+
|
| 946 |
+
It is known that a non-trivial solution y = A * sin(k * x) is possible for
|
| 947 |
+
k = pi * n, where n is an integer. To establish the normalization constant
|
| 948 |
+
A = 1 we add a boundary condition::
|
| 949 |
+
|
| 950 |
+
y'(0) = k
|
| 951 |
+
|
| 952 |
+
Again, we rewrite our equation as a first-order system and implement its
|
| 953 |
+
right-hand side evaluation::
|
| 954 |
+
|
| 955 |
+
y1' = y2
|
| 956 |
+
y2' = -k**2 * y1
|
| 957 |
+
|
| 958 |
+
>>> def fun(x, y, p):
|
| 959 |
+
... k = p[0]
|
| 960 |
+
... return np.vstack((y[1], -k**2 * y[0]))
|
| 961 |
+
|
| 962 |
+
Note that parameters p are passed as a vector (with one element in our
|
| 963 |
+
case).
|
| 964 |
+
|
| 965 |
+
Implement the boundary conditions:
|
| 966 |
+
|
| 967 |
+
>>> def bc(ya, yb, p):
|
| 968 |
+
... k = p[0]
|
| 969 |
+
... return np.array([ya[0], yb[0], ya[1] - k])
|
| 970 |
+
|
| 971 |
+
Set up the initial mesh and guess for y. We aim to find the solution for
|
| 972 |
+
k = 2 * pi, to achieve that we set values of y to approximately follow
|
| 973 |
+
sin(2 * pi * x):
|
| 974 |
+
|
| 975 |
+
>>> x = np.linspace(0, 1, 5)
|
| 976 |
+
>>> y = np.zeros((2, x.size))
|
| 977 |
+
>>> y[0, 1] = 1
|
| 978 |
+
>>> y[0, 3] = -1
|
| 979 |
+
|
| 980 |
+
Run the solver with 6 as an initial guess for k.
|
| 981 |
+
|
| 982 |
+
>>> sol = solve_bvp(fun, bc, x, y, p=[6])
|
| 983 |
+
|
| 984 |
+
We see that the found k is approximately correct:
|
| 985 |
+
|
| 986 |
+
>>> sol.p[0]
|
| 987 |
+
6.28329460046
|
| 988 |
+
|
| 989 |
+
And, finally, plot the solution to see the anticipated sinusoid:
|
| 990 |
+
|
| 991 |
+
>>> x_plot = np.linspace(0, 1, 100)
|
| 992 |
+
>>> y_plot = sol.sol(x_plot)[0]
|
| 993 |
+
>>> plt.plot(x_plot, y_plot)
|
| 994 |
+
>>> plt.xlabel("x")
|
| 995 |
+
>>> plt.ylabel("y")
|
| 996 |
+
>>> plt.show()
|
| 997 |
+
"""
|
| 998 |
+
x = np.asarray(x, dtype=float)
|
| 999 |
+
if x.ndim != 1:
|
| 1000 |
+
raise ValueError("`x` must be 1 dimensional.")
|
| 1001 |
+
h = np.diff(x)
|
| 1002 |
+
if np.any(h <= 0):
|
| 1003 |
+
raise ValueError("`x` must be strictly increasing.")
|
| 1004 |
+
a = x[0]
|
| 1005 |
+
|
| 1006 |
+
y = np.asarray(y)
|
| 1007 |
+
if np.issubdtype(y.dtype, np.complexfloating):
|
| 1008 |
+
dtype = complex
|
| 1009 |
+
else:
|
| 1010 |
+
dtype = float
|
| 1011 |
+
y = y.astype(dtype, copy=False)
|
| 1012 |
+
|
| 1013 |
+
if y.ndim != 2:
|
| 1014 |
+
raise ValueError("`y` must be 2 dimensional.")
|
| 1015 |
+
if y.shape[1] != x.shape[0]:
|
| 1016 |
+
raise ValueError(f"`y` is expected to have {x.shape[0]} columns, but actually "
|
| 1017 |
+
f"has {y.shape[1]}.")
|
| 1018 |
+
|
| 1019 |
+
if p is None:
|
| 1020 |
+
p = np.array([])
|
| 1021 |
+
else:
|
| 1022 |
+
p = np.asarray(p, dtype=dtype)
|
| 1023 |
+
if p.ndim != 1:
|
| 1024 |
+
raise ValueError("`p` must be 1 dimensional.")
|
| 1025 |
+
|
| 1026 |
+
if tol < 100 * EPS:
|
| 1027 |
+
warn(f"`tol` is too low, setting to {100 * EPS:.2e}", stacklevel=2)
|
| 1028 |
+
tol = 100 * EPS
|
| 1029 |
+
|
| 1030 |
+
if verbose not in [0, 1, 2]:
|
| 1031 |
+
raise ValueError("`verbose` must be in [0, 1, 2].")
|
| 1032 |
+
|
| 1033 |
+
n = y.shape[0]
|
| 1034 |
+
k = p.shape[0]
|
| 1035 |
+
|
| 1036 |
+
if S is not None:
|
| 1037 |
+
S = np.asarray(S, dtype=dtype)
|
| 1038 |
+
if S.shape != (n, n):
|
| 1039 |
+
raise ValueError(f"`S` is expected to have shape {(n, n)}, "
|
| 1040 |
+
f"but actually has {S.shape}")
|
| 1041 |
+
|
| 1042 |
+
# Compute I - S^+ S to impose necessary boundary conditions.
|
| 1043 |
+
B = np.identity(n) - np.dot(pinv(S), S)
|
| 1044 |
+
|
| 1045 |
+
y[:, 0] = np.dot(B, y[:, 0])
|
| 1046 |
+
|
| 1047 |
+
# Compute (I - S)^+ to correct derivatives at x=a.
|
| 1048 |
+
D = pinv(np.identity(n) - S)
|
| 1049 |
+
else:
|
| 1050 |
+
B = None
|
| 1051 |
+
D = None
|
| 1052 |
+
|
| 1053 |
+
if bc_tol is None:
|
| 1054 |
+
bc_tol = tol
|
| 1055 |
+
|
| 1056 |
+
# Maximum number of iterations
|
| 1057 |
+
max_iteration = 10
|
| 1058 |
+
|
| 1059 |
+
fun_wrapped, bc_wrapped, fun_jac_wrapped, bc_jac_wrapped = wrap_functions(
|
| 1060 |
+
fun, bc, fun_jac, bc_jac, k, a, S, D, dtype)
|
| 1061 |
+
|
| 1062 |
+
f = fun_wrapped(x, y, p)
|
| 1063 |
+
if f.shape != y.shape:
|
| 1064 |
+
raise ValueError(f"`fun` return is expected to have shape {y.shape}, "
|
| 1065 |
+
f"but actually has {f.shape}.")
|
| 1066 |
+
|
| 1067 |
+
bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
|
| 1068 |
+
if bc_res.shape != (n + k,):
|
| 1069 |
+
raise ValueError(f"`bc` return is expected to have shape {(n + k,)}, "
|
| 1070 |
+
f"but actually has {bc_res.shape}.")
|
| 1071 |
+
|
| 1072 |
+
status = 0
|
| 1073 |
+
iteration = 0
|
| 1074 |
+
if verbose == 2:
|
| 1075 |
+
print_iteration_header()
|
| 1076 |
+
|
| 1077 |
+
while True:
|
| 1078 |
+
m = x.shape[0]
|
| 1079 |
+
|
| 1080 |
+
col_fun, jac_sys = prepare_sys(n, m, k, fun_wrapped, bc_wrapped,
|
| 1081 |
+
fun_jac_wrapped, bc_jac_wrapped, x, h)
|
| 1082 |
+
y, p, singular = solve_newton(n, m, h, col_fun, bc_wrapped, jac_sys,
|
| 1083 |
+
y, p, B, tol, bc_tol)
|
| 1084 |
+
iteration += 1
|
| 1085 |
+
|
| 1086 |
+
col_res, y_middle, f, f_middle = collocation_fun(fun_wrapped, y,
|
| 1087 |
+
p, x, h)
|
| 1088 |
+
bc_res = bc_wrapped(y[:, 0], y[:, -1], p)
|
| 1089 |
+
max_bc_res = np.max(abs(bc_res))
|
| 1090 |
+
|
| 1091 |
+
# This relation is not trivial, but can be verified.
|
| 1092 |
+
r_middle = 1.5 * col_res / h
|
| 1093 |
+
sol = create_spline(y, f, x, h)
|
| 1094 |
+
rms_res = estimate_rms_residuals(fun_wrapped, sol, x, h, p,
|
| 1095 |
+
r_middle, f_middle)
|
| 1096 |
+
max_rms_res = np.max(rms_res)
|
| 1097 |
+
|
| 1098 |
+
if singular:
|
| 1099 |
+
status = 2
|
| 1100 |
+
break
|
| 1101 |
+
|
| 1102 |
+
insert_1, = np.nonzero((rms_res > tol) & (rms_res < 100 * tol))
|
| 1103 |
+
insert_2, = np.nonzero(rms_res >= 100 * tol)
|
| 1104 |
+
nodes_added = insert_1.shape[0] + 2 * insert_2.shape[0]
|
| 1105 |
+
|
| 1106 |
+
if m + nodes_added > max_nodes:
|
| 1107 |
+
status = 1
|
| 1108 |
+
if verbose == 2:
|
| 1109 |
+
nodes_added = f"({nodes_added})"
|
| 1110 |
+
print_iteration_progress(iteration, max_rms_res, max_bc_res,
|
| 1111 |
+
m, nodes_added)
|
| 1112 |
+
break
|
| 1113 |
+
|
| 1114 |
+
if verbose == 2:
|
| 1115 |
+
print_iteration_progress(iteration, max_rms_res, max_bc_res, m,
|
| 1116 |
+
nodes_added)
|
| 1117 |
+
|
| 1118 |
+
if nodes_added > 0:
|
| 1119 |
+
x = modify_mesh(x, insert_1, insert_2)
|
| 1120 |
+
h = np.diff(x)
|
| 1121 |
+
y = sol(x)
|
| 1122 |
+
elif max_bc_res <= bc_tol:
|
| 1123 |
+
status = 0
|
| 1124 |
+
break
|
| 1125 |
+
elif iteration >= max_iteration:
|
| 1126 |
+
status = 3
|
| 1127 |
+
break
|
| 1128 |
+
|
| 1129 |
+
if verbose > 0:
|
| 1130 |
+
if status == 0:
|
| 1131 |
+
print(f"Solved in {iteration} iterations, number of nodes {x.shape[0]}. \n"
|
| 1132 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1133 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1134 |
+
elif status == 1:
|
| 1135 |
+
print(f"Number of nodes is exceeded after iteration {iteration}. \n"
|
| 1136 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1137 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1138 |
+
elif status == 2:
|
| 1139 |
+
print("Singular Jacobian encountered when solving the collocation "
|
| 1140 |
+
f"system on iteration {iteration}. \n"
|
| 1141 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1142 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1143 |
+
elif status == 3:
|
| 1144 |
+
print("The solver was unable to satisfy boundary conditions "
|
| 1145 |
+
f"tolerance on iteration {iteration}. \n"
|
| 1146 |
+
f"Maximum relative residual: {max_rms_res:.2e} \n"
|
| 1147 |
+
f"Maximum boundary residual: {max_bc_res:.2e}")
|
| 1148 |
+
|
| 1149 |
+
if p.size == 0:
|
| 1150 |
+
p = None
|
| 1151 |
+
|
| 1152 |
+
return BVPResult(sol=sol, p=p, x=x, y=y, yp=f, rms_residuals=rms_res,
|
| 1153 |
+
niter=iteration, status=status,
|
| 1154 |
+
message=TERMINATION_MESSAGES[status], success=status == 0)
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_cubature.py
ADDED
|
@@ -0,0 +1,728 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 1 |
+
import math
|
| 2 |
+
import heapq
|
| 3 |
+
import itertools
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from types import ModuleType
|
| 7 |
+
from typing import Any, TypeAlias
|
| 8 |
+
|
| 9 |
+
from scipy._lib._array_api import (
|
| 10 |
+
array_namespace,
|
| 11 |
+
xp_size,
|
| 12 |
+
xp_copy,
|
| 13 |
+
xp_broadcast_promote
|
| 14 |
+
)
|
| 15 |
+
from scipy._lib._util import MapWrapper
|
| 16 |
+
|
| 17 |
+
from scipy.integrate._rules import (
|
| 18 |
+
ProductNestedFixed,
|
| 19 |
+
GaussKronrodQuadrature,
|
| 20 |
+
GenzMalikCubature,
|
| 21 |
+
)
|
| 22 |
+
from scipy.integrate._rules._base import _split_subregion
|
| 23 |
+
|
| 24 |
+
__all__ = ['cubature']
|
| 25 |
+
|
| 26 |
+
Array: TypeAlias = Any # To be changed to an array-api-typing Protocol later
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class CubatureRegion:
|
| 31 |
+
estimate: Array
|
| 32 |
+
error: Array
|
| 33 |
+
a: Array
|
| 34 |
+
b: Array
|
| 35 |
+
_xp: ModuleType = field(repr=False)
|
| 36 |
+
|
| 37 |
+
def __lt__(self, other):
|
| 38 |
+
# Consider regions with higher error estimates as being "less than" regions with
|
| 39 |
+
# lower order estimates, so that regions with high error estimates are placed at
|
| 40 |
+
# the top of the heap.
|
| 41 |
+
|
| 42 |
+
this_err = self._xp.max(self._xp.abs(self.error))
|
| 43 |
+
other_err = self._xp.max(self._xp.abs(other.error))
|
| 44 |
+
|
| 45 |
+
return this_err > other_err
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class CubatureResult:
|
| 50 |
+
estimate: Array
|
| 51 |
+
error: Array
|
| 52 |
+
status: str
|
| 53 |
+
regions: list[CubatureRegion]
|
| 54 |
+
subdivisions: int
|
| 55 |
+
atol: float
|
| 56 |
+
rtol: float
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def cubature(f, a, b, *, rule="gk21", rtol=1e-8, atol=0, max_subdivisions=10000,
|
| 60 |
+
args=(), workers=1, points=None):
|
| 61 |
+
r"""
|
| 62 |
+
Adaptive cubature of multidimensional array-valued function.
|
| 63 |
+
|
| 64 |
+
Given an arbitrary integration rule, this function returns an estimate of the
|
| 65 |
+
integral to the requested tolerance over the region defined by the arrays `a` and
|
| 66 |
+
`b` specifying the corners of a hypercube.
|
| 67 |
+
|
| 68 |
+
Convergence is not guaranteed for all integrals.
|
| 69 |
+
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
f : callable
|
| 73 |
+
Function to integrate. `f` must have the signature::
|
| 74 |
+
|
| 75 |
+
f(x : ndarray, *args) -> ndarray
|
| 76 |
+
|
| 77 |
+
`f` should accept arrays ``x`` of shape::
|
| 78 |
+
|
| 79 |
+
(npoints, ndim)
|
| 80 |
+
|
| 81 |
+
and output arrays of shape::
|
| 82 |
+
|
| 83 |
+
(npoints, output_dim_1, ..., output_dim_n)
|
| 84 |
+
|
| 85 |
+
In this case, `cubature` will return arrays of shape::
|
| 86 |
+
|
| 87 |
+
(output_dim_1, ..., output_dim_n)
|
| 88 |
+
a, b : array_like
|
| 89 |
+
Lower and upper limits of integration as 1D arrays specifying the left and right
|
| 90 |
+
endpoints of the intervals being integrated over. Limits can be infinite.
|
| 91 |
+
rule : str, optional
|
| 92 |
+
Rule used to estimate the integral. If passing a string, the options are
|
| 93 |
+
"gauss-kronrod" (21 node), or "genz-malik" (degree 7). If a rule like
|
| 94 |
+
"gauss-kronrod" is specified for an ``n``-dim integrand, the corresponding
|
| 95 |
+
Cartesian product rule is used. "gk21", "gk15" are also supported for
|
| 96 |
+
compatibility with `quad_vec`. See Notes.
|
| 97 |
+
rtol, atol : float, optional
|
| 98 |
+
Relative and absolute tolerances. Iterations are performed until the error is
|
| 99 |
+
estimated to be less than ``atol + rtol * abs(est)``. Here `rtol` controls
|
| 100 |
+
relative accuracy (number of correct digits), while `atol` controls absolute
|
| 101 |
+
accuracy (number of correct decimal places). To achieve the desired `rtol`, set
|
| 102 |
+
`atol` to be smaller than the smallest value that can be expected from
|
| 103 |
+
``rtol * abs(y)`` so that `rtol` dominates the allowable error. If `atol` is
|
| 104 |
+
larger than ``rtol * abs(y)`` the number of correct digits is not guaranteed.
|
| 105 |
+
Conversely, to achieve the desired `atol`, set `rtol` such that
|
| 106 |
+
``rtol * abs(y)`` is always smaller than `atol`. Default values are 1e-8 for
|
| 107 |
+
`rtol` and 0 for `atol`.
|
| 108 |
+
max_subdivisions : int, optional
|
| 109 |
+
Upper bound on the number of subdivisions to perform. Default is 10,000.
|
| 110 |
+
args : tuple, optional
|
| 111 |
+
Additional positional args passed to `f`, if any.
|
| 112 |
+
workers : int or map-like callable, optional
|
| 113 |
+
If `workers` is an integer, part of the computation is done in parallel
|
| 114 |
+
subdivided to this many tasks (using :class:`python:multiprocessing.pool.Pool`).
|
| 115 |
+
Supply `-1` to use all cores available to the Process. Alternatively, supply a
|
| 116 |
+
map-like callable, such as :meth:`python:multiprocessing.pool.Pool.map` for
|
| 117 |
+
evaluating the population in parallel. This evaluation is carried out as
|
| 118 |
+
``workers(func, iterable)``.
|
| 119 |
+
points : list of array_like, optional
|
| 120 |
+
List of points to avoid evaluating `f` at, under the condition that the rule
|
| 121 |
+
being used does not evaluate `f` on the boundary of a region (which is the
|
| 122 |
+
case for all Genz-Malik and Gauss-Kronrod rules). This can be useful if `f` has
|
| 123 |
+
a singularity at the specified point. This should be a list of array-likes where
|
| 124 |
+
each element has length ``ndim``. Default is empty. See Examples.
|
| 125 |
+
|
| 126 |
+
Returns
|
| 127 |
+
-------
|
| 128 |
+
res : object
|
| 129 |
+
Object containing the results of the estimation. It has the following
|
| 130 |
+
attributes:
|
| 131 |
+
|
| 132 |
+
estimate : ndarray
|
| 133 |
+
Estimate of the value of the integral over the overall region specified.
|
| 134 |
+
error : ndarray
|
| 135 |
+
Estimate of the error of the approximation over the overall region
|
| 136 |
+
specified.
|
| 137 |
+
status : str
|
| 138 |
+
Whether the estimation was successful. Can be either: "converged",
|
| 139 |
+
"not_converged".
|
| 140 |
+
subdivisions : int
|
| 141 |
+
Number of subdivisions performed.
|
| 142 |
+
atol, rtol : float
|
| 143 |
+
Requested tolerances for the approximation.
|
| 144 |
+
regions: list of object
|
| 145 |
+
List of objects containing the estimates of the integral over smaller
|
| 146 |
+
regions of the domain.
|
| 147 |
+
|
| 148 |
+
Each object in ``regions`` has the following attributes:
|
| 149 |
+
|
| 150 |
+
a, b : ndarray
|
| 151 |
+
Points describing the corners of the region. If the original integral
|
| 152 |
+
contained infinite limits or was over a region described by `region`,
|
| 153 |
+
then `a` and `b` are in the transformed coordinates.
|
| 154 |
+
estimate : ndarray
|
| 155 |
+
Estimate of the value of the integral over this region.
|
| 156 |
+
error : ndarray
|
| 157 |
+
Estimate of the error of the approximation over this region.
|
| 158 |
+
|
| 159 |
+
Notes
|
| 160 |
+
-----
|
| 161 |
+
The algorithm uses a similar algorithm to `quad_vec`, which itself is based on the
|
| 162 |
+
implementation of QUADPACK's DQAG* algorithms, implementing global error control and
|
| 163 |
+
adaptive subdivision.
|
| 164 |
+
|
| 165 |
+
The source of the nodes and weights used for Gauss-Kronrod quadrature can be found
|
| 166 |
+
in [1]_, and the algorithm for calculating the nodes and weights in Genz-Malik
|
| 167 |
+
cubature can be found in [2]_.
|
| 168 |
+
|
| 169 |
+
The rules currently supported via the `rule` argument are:
|
| 170 |
+
|
| 171 |
+
- ``"gauss-kronrod"``, 21-node Gauss-Kronrod
|
| 172 |
+
- ``"genz-malik"``, n-node Genz-Malik
|
| 173 |
+
|
| 174 |
+
If using Gauss-Kronrod for an ``n``-dim integrand where ``n > 2``, then the
|
| 175 |
+
corresponding Cartesian product rule will be found by taking the Cartesian product
|
| 176 |
+
of the nodes in the 1D case. This means that the number of nodes scales
|
| 177 |
+
exponentially as ``21^n`` in the Gauss-Kronrod case, which may be problematic in a
|
| 178 |
+
moderate number of dimensions.
|
| 179 |
+
|
| 180 |
+
Genz-Malik is typically less accurate than Gauss-Kronrod but has much fewer nodes,
|
| 181 |
+
so in this situation using "genz-malik" might be preferable.
|
| 182 |
+
|
| 183 |
+
Infinite limits are handled with an appropriate variable transformation. Assuming
|
| 184 |
+
``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
|
| 185 |
+
|
| 186 |
+
If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 187 |
+
will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
|
| 188 |
+
|
| 189 |
+
If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 190 |
+
will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
|
| 191 |
+
:math:`t \in (0, 1)`.
|
| 192 |
+
|
| 193 |
+
If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
|
| 194 |
+
variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
|
| 195 |
+
:math:`t \in (0, 1)`.
|
| 196 |
+
|
| 197 |
+
References
|
| 198 |
+
----------
|
| 199 |
+
.. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
|
| 200 |
+
Integration, files: dqk21.f, dqk15.f (1983).
|
| 201 |
+
|
| 202 |
+
.. [2] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
|
| 203 |
+
numerical integration over an N-dimensional rectangular region, Journal of
|
| 204 |
+
Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
|
| 205 |
+
ISSN 0377-0427
|
| 206 |
+
:doi:`10.1016/0771-050X(80)90039-X`
|
| 207 |
+
|
| 208 |
+
Examples
|
| 209 |
+
--------
|
| 210 |
+
**1D integral with vector output**:
|
| 211 |
+
|
| 212 |
+
.. math::
|
| 213 |
+
|
| 214 |
+
\int^1_0 \mathbf f(x) \text dx
|
| 215 |
+
|
| 216 |
+
Where ``f(x) = x^n`` and ``n = np.arange(10)`` is a vector. Since no rule is
|
| 217 |
+
specified, the default "gk21" is used, which corresponds to Gauss-Kronrod
|
| 218 |
+
integration with 21 nodes.
|
| 219 |
+
|
| 220 |
+
>>> import numpy as np
|
| 221 |
+
>>> from scipy.integrate import cubature
|
| 222 |
+
>>> def f(x, n):
|
| 223 |
+
... # Make sure x and n are broadcastable
|
| 224 |
+
... return x[:, np.newaxis]**n[np.newaxis, :]
|
| 225 |
+
>>> res = cubature(
|
| 226 |
+
... f,
|
| 227 |
+
... a=[0],
|
| 228 |
+
... b=[1],
|
| 229 |
+
... args=(np.arange(10),),
|
| 230 |
+
... )
|
| 231 |
+
>>> res.estimate
|
| 232 |
+
array([1. , 0.5 , 0.33333333, 0.25 , 0.2 ,
|
| 233 |
+
0.16666667, 0.14285714, 0.125 , 0.11111111, 0.1 ])
|
| 234 |
+
|
| 235 |
+
**7D integral with arbitrary-shaped array output**::
|
| 236 |
+
|
| 237 |
+
f(x) = cos(2*pi*r + alphas @ x)
|
| 238 |
+
|
| 239 |
+
for some ``r`` and ``alphas``, and the integral is performed over the unit
|
| 240 |
+
hybercube, :math:`[0, 1]^7`. Since the integral is in a moderate number of
|
| 241 |
+
dimensions, "genz-malik" is used rather than the default "gauss-kronrod" to
|
| 242 |
+
avoid constructing a product rule with :math:`21^7 \approx 2 \times 10^9` nodes.
|
| 243 |
+
|
| 244 |
+
>>> import numpy as np
|
| 245 |
+
>>> from scipy.integrate import cubature
|
| 246 |
+
>>> def f(x, r, alphas):
|
| 247 |
+
... # f(x) = cos(2*pi*r + alphas @ x)
|
| 248 |
+
... # Need to allow r and alphas to be arbitrary shape
|
| 249 |
+
... npoints, ndim = x.shape[0], x.shape[-1]
|
| 250 |
+
... alphas = alphas[np.newaxis, ...]
|
| 251 |
+
... x = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
|
| 252 |
+
... return np.cos(2*np.pi*r + np.sum(alphas * x, axis=-1))
|
| 253 |
+
>>> rng = np.random.default_rng()
|
| 254 |
+
>>> r, alphas = rng.random((2, 3)), rng.random((2, 3, 7))
|
| 255 |
+
>>> res = cubature(
|
| 256 |
+
... f=f,
|
| 257 |
+
... a=np.array([0, 0, 0, 0, 0, 0, 0]),
|
| 258 |
+
... b=np.array([1, 1, 1, 1, 1, 1, 1]),
|
| 259 |
+
... rtol=1e-5,
|
| 260 |
+
... rule="genz-malik",
|
| 261 |
+
... args=(r, alphas),
|
| 262 |
+
... )
|
| 263 |
+
>>> res.estimate
|
| 264 |
+
array([[-0.79812452, 0.35246913, -0.52273628],
|
| 265 |
+
[ 0.88392779, 0.59139899, 0.41895111]])
|
| 266 |
+
|
| 267 |
+
**Parallel computation with** `workers`:
|
| 268 |
+
|
| 269 |
+
>>> from concurrent.futures import ThreadPoolExecutor
|
| 270 |
+
>>> with ThreadPoolExecutor() as executor:
|
| 271 |
+
... res = cubature(
|
| 272 |
+
... f=f,
|
| 273 |
+
... a=np.array([0, 0, 0, 0, 0, 0, 0]),
|
| 274 |
+
... b=np.array([1, 1, 1, 1, 1, 1, 1]),
|
| 275 |
+
... rtol=1e-5,
|
| 276 |
+
... rule="genz-malik",
|
| 277 |
+
... args=(r, alphas),
|
| 278 |
+
... workers=executor.map,
|
| 279 |
+
... )
|
| 280 |
+
>>> res.estimate
|
| 281 |
+
array([[-0.79812452, 0.35246913, -0.52273628],
|
| 282 |
+
[ 0.88392779, 0.59139899, 0.41895111]])
|
| 283 |
+
|
| 284 |
+
**2D integral with infinite limits**:
|
| 285 |
+
|
| 286 |
+
.. math::
|
| 287 |
+
|
| 288 |
+
\int^{ \infty }_{ -\infty }
|
| 289 |
+
\int^{ \infty }_{ -\infty }
|
| 290 |
+
e^{-x^2-y^2}
|
| 291 |
+
\text dy
|
| 292 |
+
\text dx
|
| 293 |
+
|
| 294 |
+
>>> def gaussian(x):
|
| 295 |
+
... return np.exp(-np.sum(x**2, axis=-1))
|
| 296 |
+
>>> res = cubature(gaussian, [-np.inf, -np.inf], [np.inf, np.inf])
|
| 297 |
+
>>> res.estimate
|
| 298 |
+
3.1415926
|
| 299 |
+
|
| 300 |
+
**1D integral with singularities avoided using** `points`:
|
| 301 |
+
|
| 302 |
+
.. math::
|
| 303 |
+
|
| 304 |
+
\int^{ 1 }_{ -1 }
|
| 305 |
+
\frac{\sin(x)}{x}
|
| 306 |
+
\text dx
|
| 307 |
+
|
| 308 |
+
It is necessary to use the `points` parameter to avoid evaluating `f` at the origin.
|
| 309 |
+
|
| 310 |
+
>>> def sinc(x):
|
| 311 |
+
... return np.sin(x)/x
|
| 312 |
+
>>> res = cubature(sinc, [-1], [1], points=[[0]])
|
| 313 |
+
>>> res.estimate
|
| 314 |
+
1.8921661
|
| 315 |
+
"""
|
| 316 |
+
|
| 317 |
+
# It is also possible to use a custom rule, but this is not yet part of the public
|
| 318 |
+
# API. An example of this can be found in the class scipy.integrate._rules.Rule.
|
| 319 |
+
|
| 320 |
+
xp = array_namespace(a, b)
|
| 321 |
+
max_subdivisions = float("inf") if max_subdivisions is None else max_subdivisions
|
| 322 |
+
points = [] if points is None else points
|
| 323 |
+
|
| 324 |
+
# Convert a and b to arrays and convert each point in points to an array, promoting
|
| 325 |
+
# each to a common floating dtype.
|
| 326 |
+
a, b, *points = xp_broadcast_promote(a, b, *points, force_floating=True)
|
| 327 |
+
result_dtype = a.dtype
|
| 328 |
+
|
| 329 |
+
if xp_size(a) == 0 or xp_size(b) == 0:
|
| 330 |
+
raise ValueError("`a` and `b` must be nonempty")
|
| 331 |
+
|
| 332 |
+
if a.ndim != 1 or b.ndim != 1:
|
| 333 |
+
raise ValueError("`a` and `b` must be 1D arrays")
|
| 334 |
+
|
| 335 |
+
# If the rule is a string, convert to a corresponding product rule
|
| 336 |
+
if isinstance(rule, str):
|
| 337 |
+
ndim = xp_size(a)
|
| 338 |
+
|
| 339 |
+
if rule == "genz-malik":
|
| 340 |
+
rule = GenzMalikCubature(ndim, xp=xp)
|
| 341 |
+
else:
|
| 342 |
+
quadratues = {
|
| 343 |
+
"gauss-kronrod": GaussKronrodQuadrature(21, xp=xp),
|
| 344 |
+
|
| 345 |
+
# Also allow names quad_vec uses:
|
| 346 |
+
"gk21": GaussKronrodQuadrature(21, xp=xp),
|
| 347 |
+
"gk15": GaussKronrodQuadrature(15, xp=xp),
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
base_rule = quadratues.get(rule)
|
| 351 |
+
|
| 352 |
+
if base_rule is None:
|
| 353 |
+
raise ValueError(f"unknown rule {rule}")
|
| 354 |
+
|
| 355 |
+
rule = ProductNestedFixed([base_rule] * ndim)
|
| 356 |
+
|
| 357 |
+
# If any of limits are the wrong way around (a > b), flip them and keep track of
|
| 358 |
+
# the sign.
|
| 359 |
+
sign = (-1) ** xp.sum(xp.astype(a > b, xp.int8), dtype=result_dtype)
|
| 360 |
+
|
| 361 |
+
a_flipped = xp.min(xp.stack([a, b]), axis=0)
|
| 362 |
+
b_flipped = xp.max(xp.stack([a, b]), axis=0)
|
| 363 |
+
|
| 364 |
+
a, b = a_flipped, b_flipped
|
| 365 |
+
|
| 366 |
+
# If any of the limits are infinite, apply a transformation
|
| 367 |
+
if xp.any(xp.isinf(a)) or xp.any(xp.isinf(b)):
|
| 368 |
+
f = _InfiniteLimitsTransform(f, a, b, xp=xp)
|
| 369 |
+
a, b = f.transformed_limits
|
| 370 |
+
|
| 371 |
+
# Map points from the original coordinates to the new transformed coordinates.
|
| 372 |
+
#
|
| 373 |
+
# `points` is a list of arrays of shape (ndim,), but transformations are applied
|
| 374 |
+
# to arrays of shape (npoints, ndim).
|
| 375 |
+
#
|
| 376 |
+
# It is not possible to combine all the points into one array and then apply
|
| 377 |
+
# f.inv to all of them at once since `points` needs to remain iterable.
|
| 378 |
+
# Instead, each point is reshaped to an array of shape (1, ndim), `f.inv` is
|
| 379 |
+
# applied, and then each is reshaped back to (ndim,).
|
| 380 |
+
points = [xp.reshape(point, (1, -1)) for point in points]
|
| 381 |
+
points = [f.inv(point) for point in points]
|
| 382 |
+
points = [xp.reshape(point, (-1,)) for point in points]
|
| 383 |
+
|
| 384 |
+
# Include any problematic points introduced by the transformation
|
| 385 |
+
points.extend(f.points)
|
| 386 |
+
|
| 387 |
+
# If any problematic points are specified, divide the initial region so that these
|
| 388 |
+
# points lie on the edge of a subregion.
|
| 389 |
+
#
|
| 390 |
+
# This means ``f`` won't be evaluated there if the rule being used has no evaluation
|
| 391 |
+
# points on the boundary.
|
| 392 |
+
if len(points) == 0:
|
| 393 |
+
initial_regions = [(a, b)]
|
| 394 |
+
else:
|
| 395 |
+
initial_regions = _split_region_at_points(a, b, points, xp)
|
| 396 |
+
|
| 397 |
+
regions = []
|
| 398 |
+
est = 0.0
|
| 399 |
+
err = 0.0
|
| 400 |
+
|
| 401 |
+
for a_k, b_k in initial_regions:
|
| 402 |
+
est_k = rule.estimate(f, a_k, b_k, args)
|
| 403 |
+
err_k = rule.estimate_error(f, a_k, b_k, args)
|
| 404 |
+
regions.append(CubatureRegion(est_k, err_k, a_k, b_k, xp))
|
| 405 |
+
|
| 406 |
+
est += est_k
|
| 407 |
+
err += err_k
|
| 408 |
+
|
| 409 |
+
subdivisions = 0
|
| 410 |
+
success = True
|
| 411 |
+
|
| 412 |
+
with MapWrapper(workers) as mapwrapper:
|
| 413 |
+
while xp.any(err > atol + rtol * xp.abs(est)):
|
| 414 |
+
# region_k is the region with highest estimated error
|
| 415 |
+
region_k = heapq.heappop(regions)
|
| 416 |
+
|
| 417 |
+
est_k = region_k.estimate
|
| 418 |
+
err_k = region_k.error
|
| 419 |
+
|
| 420 |
+
a_k, b_k = region_k.a, region_k.b
|
| 421 |
+
|
| 422 |
+
# Subtract the estimate of the integral and its error over this region from
|
| 423 |
+
# the current global estimates, since these will be refined in the loop over
|
| 424 |
+
# all subregions.
|
| 425 |
+
est -= est_k
|
| 426 |
+
err -= err_k
|
| 427 |
+
|
| 428 |
+
# Find all 2^ndim subregions formed by splitting region_k along each axis,
|
| 429 |
+
# e.g. for 1D integrals this splits an estimate over an interval into an
|
| 430 |
+
# estimate over two subintervals, for 3D integrals this splits an estimate
|
| 431 |
+
# over a cube into 8 subcubes.
|
| 432 |
+
#
|
| 433 |
+
# For each of the new subregions, calculate an estimate for the integral and
|
| 434 |
+
# the error there, and push these regions onto the heap for potential
|
| 435 |
+
# further subdividing.
|
| 436 |
+
|
| 437 |
+
executor_args = zip(
|
| 438 |
+
itertools.repeat(f),
|
| 439 |
+
itertools.repeat(rule),
|
| 440 |
+
itertools.repeat(args),
|
| 441 |
+
_split_subregion(a_k, b_k, xp),
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
for subdivision_result in mapwrapper(_process_subregion, executor_args):
|
| 445 |
+
a_k_sub, b_k_sub, est_sub, err_sub = subdivision_result
|
| 446 |
+
|
| 447 |
+
est += est_sub
|
| 448 |
+
err += err_sub
|
| 449 |
+
|
| 450 |
+
new_region = CubatureRegion(est_sub, err_sub, a_k_sub, b_k_sub, xp)
|
| 451 |
+
|
| 452 |
+
heapq.heappush(regions, new_region)
|
| 453 |
+
|
| 454 |
+
subdivisions += 1
|
| 455 |
+
|
| 456 |
+
if subdivisions >= max_subdivisions:
|
| 457 |
+
success = False
|
| 458 |
+
break
|
| 459 |
+
|
| 460 |
+
status = "converged" if success else "not_converged"
|
| 461 |
+
|
| 462 |
+
# Apply sign change to handle any limits which were initially flipped.
|
| 463 |
+
est = sign * est
|
| 464 |
+
|
| 465 |
+
return CubatureResult(
|
| 466 |
+
estimate=est,
|
| 467 |
+
error=err,
|
| 468 |
+
status=status,
|
| 469 |
+
subdivisions=subdivisions,
|
| 470 |
+
regions=regions,
|
| 471 |
+
atol=atol,
|
| 472 |
+
rtol=rtol,
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def _process_subregion(data):
|
| 477 |
+
f, rule, args, coord = data
|
| 478 |
+
a_k_sub, b_k_sub = coord
|
| 479 |
+
|
| 480 |
+
est_sub = rule.estimate(f, a_k_sub, b_k_sub, args)
|
| 481 |
+
err_sub = rule.estimate_error(f, a_k_sub, b_k_sub, args)
|
| 482 |
+
|
| 483 |
+
return a_k_sub, b_k_sub, est_sub, err_sub
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _is_strictly_in_region(a, b, point, xp):
|
| 487 |
+
if xp.all(point == a) or xp.all(point == b):
|
| 488 |
+
return False
|
| 489 |
+
|
| 490 |
+
return xp.all(a <= point) and xp.all(point <= b)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def _split_region_at_points(a, b, points, xp):
|
| 494 |
+
"""
|
| 495 |
+
Given the integration limits `a` and `b` describing a rectangular region and a list
|
| 496 |
+
of `points`, find the list of ``[(a_1, b_1), ..., (a_l, b_l)]`` which breaks up the
|
| 497 |
+
initial region into smaller subregion such that no `points` lie strictly inside
|
| 498 |
+
any of the subregions.
|
| 499 |
+
"""
|
| 500 |
+
|
| 501 |
+
regions = [(a, b)]
|
| 502 |
+
|
| 503 |
+
for point in points:
|
| 504 |
+
if xp.any(xp.isinf(point)):
|
| 505 |
+
# If a point is specified at infinity, ignore.
|
| 506 |
+
#
|
| 507 |
+
# This case occurs when points are given by the user to avoid, but after
|
| 508 |
+
# applying a transformation, they are removed.
|
| 509 |
+
continue
|
| 510 |
+
|
| 511 |
+
new_subregions = []
|
| 512 |
+
|
| 513 |
+
for a_k, b_k in regions:
|
| 514 |
+
if _is_strictly_in_region(a_k, b_k, point, xp):
|
| 515 |
+
subregions = _split_subregion(a_k, b_k, xp, point)
|
| 516 |
+
|
| 517 |
+
for left, right in subregions:
|
| 518 |
+
# Skip any zero-width regions.
|
| 519 |
+
if xp.any(left == right):
|
| 520 |
+
continue
|
| 521 |
+
else:
|
| 522 |
+
new_subregions.append((left, right))
|
| 523 |
+
|
| 524 |
+
new_subregions.extend(subregions)
|
| 525 |
+
|
| 526 |
+
else:
|
| 527 |
+
new_subregions.append((a_k, b_k))
|
| 528 |
+
|
| 529 |
+
regions = new_subregions
|
| 530 |
+
|
| 531 |
+
return regions
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
class _VariableTransform:
|
| 535 |
+
"""
|
| 536 |
+
A transformation that can be applied to an integral.
|
| 537 |
+
"""
|
| 538 |
+
|
| 539 |
+
@property
|
| 540 |
+
def transformed_limits(self):
|
| 541 |
+
"""
|
| 542 |
+
New limits of integration after applying the transformation.
|
| 543 |
+
"""
|
| 544 |
+
|
| 545 |
+
raise NotImplementedError
|
| 546 |
+
|
| 547 |
+
@property
|
| 548 |
+
def points(self):
|
| 549 |
+
"""
|
| 550 |
+
Any problematic points introduced by the transformation.
|
| 551 |
+
|
| 552 |
+
These should be specified as points where ``_VariableTransform(f)(self, point)``
|
| 553 |
+
would be problematic.
|
| 554 |
+
|
| 555 |
+
For example, if the transformation ``x = 1/((1-t)(1+t))`` is applied to a
|
| 556 |
+
univariate integral, then points should return ``[ [1], [-1] ]``.
|
| 557 |
+
"""
|
| 558 |
+
|
| 559 |
+
return []
|
| 560 |
+
|
| 561 |
+
def inv(self, x):
|
| 562 |
+
"""
|
| 563 |
+
Map points ``x`` to ``t`` such that if ``f`` is the original function and ``g``
|
| 564 |
+
is the function after the transformation is applied, then::
|
| 565 |
+
|
| 566 |
+
f(x) = g(self.inv(x))
|
| 567 |
+
"""
|
| 568 |
+
|
| 569 |
+
raise NotImplementedError
|
| 570 |
+
|
| 571 |
+
def __call__(self, t, *args, **kwargs):
|
| 572 |
+
"""
|
| 573 |
+
Apply the transformation to ``f`` and multiply by the Jacobian determinant.
|
| 574 |
+
This should be the new integrand after the transformation has been applied so
|
| 575 |
+
that the following is satisfied::
|
| 576 |
+
|
| 577 |
+
f_transformed = _VariableTransform(f)
|
| 578 |
+
|
| 579 |
+
cubature(f, a, b) == cubature(
|
| 580 |
+
f_transformed,
|
| 581 |
+
*f_transformed.transformed_limits(a, b),
|
| 582 |
+
)
|
| 583 |
+
"""
|
| 584 |
+
|
| 585 |
+
raise NotImplementedError
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
class _InfiniteLimitsTransform(_VariableTransform):
|
| 589 |
+
r"""
|
| 590 |
+
Transformation for handling infinite limits.
|
| 591 |
+
|
| 592 |
+
Assuming ``a = [a_1, ..., a_n]`` and ``b = [b_1, ..., b_n]``:
|
| 593 |
+
|
| 594 |
+
If :math:`a_i = -\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 595 |
+
will use the transformation :math:`x = \frac{1-|t|}{t}` and :math:`t \in (-1, 1)`.
|
| 596 |
+
|
| 597 |
+
If :math:`a_i \ne \pm\infty` and :math:`b_i = \infty`, the i-th integration variable
|
| 598 |
+
will use the transformation :math:`x = a_i + \frac{1-t}{t}` and
|
| 599 |
+
:math:`t \in (0, 1)`.
|
| 600 |
+
|
| 601 |
+
If :math:`a_i = -\infty` and :math:`b_i \ne \pm\infty`, the i-th integration
|
| 602 |
+
variable will use the transformation :math:`x = b_i - \frac{1-t}{t}` and
|
| 603 |
+
:math:`t \in (0, 1)`.
|
| 604 |
+
"""
|
| 605 |
+
|
| 606 |
+
def __init__(self, f, a, b, xp):
|
| 607 |
+
self._xp = xp
|
| 608 |
+
|
| 609 |
+
self._f = f
|
| 610 |
+
self._orig_a = a
|
| 611 |
+
self._orig_b = b
|
| 612 |
+
|
| 613 |
+
# (-oo, oo) will be mapped to (-1, 1).
|
| 614 |
+
self._double_inf_pos = (a == -math.inf) & (b == math.inf)
|
| 615 |
+
|
| 616 |
+
# (start, oo) will be mapped to (0, 1).
|
| 617 |
+
start_inf_mask = (a != -math.inf) & (b == math.inf)
|
| 618 |
+
|
| 619 |
+
# (-oo, end) will be mapped to (0, 1).
|
| 620 |
+
inf_end_mask = (a == -math.inf) & (b != math.inf)
|
| 621 |
+
|
| 622 |
+
# This is handled by making the transformation t = -x and reducing it to
|
| 623 |
+
# the other semi-infinite case.
|
| 624 |
+
self._semi_inf_pos = start_inf_mask | inf_end_mask
|
| 625 |
+
|
| 626 |
+
# Since we flip the limits, we don't need to separately multiply the
|
| 627 |
+
# integrand by -1.
|
| 628 |
+
self._orig_a[inf_end_mask] = -b[inf_end_mask]
|
| 629 |
+
self._orig_b[inf_end_mask] = -a[inf_end_mask]
|
| 630 |
+
|
| 631 |
+
self._num_inf = self._xp.sum(
|
| 632 |
+
self._xp.astype(self._double_inf_pos | self._semi_inf_pos, self._xp.int64),
|
| 633 |
+
).__int__()
|
| 634 |
+
|
| 635 |
+
@property
|
| 636 |
+
def transformed_limits(self):
|
| 637 |
+
a = xp_copy(self._orig_a)
|
| 638 |
+
b = xp_copy(self._orig_b)
|
| 639 |
+
|
| 640 |
+
a[self._double_inf_pos] = -1
|
| 641 |
+
b[self._double_inf_pos] = 1
|
| 642 |
+
|
| 643 |
+
a[self._semi_inf_pos] = 0
|
| 644 |
+
b[self._semi_inf_pos] = 1
|
| 645 |
+
|
| 646 |
+
return a, b
|
| 647 |
+
|
| 648 |
+
@property
|
| 649 |
+
def points(self):
|
| 650 |
+
# If there are infinite limits, then the origin becomes a problematic point
|
| 651 |
+
# due to a division by zero there.
|
| 652 |
+
|
| 653 |
+
# If the function using this class only wraps f when a and b contain infinite
|
| 654 |
+
# limits, this condition will always be met (as is the case with cubature).
|
| 655 |
+
#
|
| 656 |
+
# If a and b do not contain infinite limits but f is still wrapped with this
|
| 657 |
+
# class, then without this condition the initial region of integration will
|
| 658 |
+
# be split around the origin unnecessarily.
|
| 659 |
+
if self._num_inf != 0:
|
| 660 |
+
return [self._xp.zeros(self._orig_a.shape)]
|
| 661 |
+
else:
|
| 662 |
+
return []
|
| 663 |
+
|
| 664 |
+
def inv(self, x):
|
| 665 |
+
t = xp_copy(x)
|
| 666 |
+
npoints = x.shape[0]
|
| 667 |
+
|
| 668 |
+
double_inf_mask = self._xp.tile(
|
| 669 |
+
self._double_inf_pos[self._xp.newaxis, :],
|
| 670 |
+
(npoints, 1),
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
semi_inf_mask = self._xp.tile(
|
| 674 |
+
self._semi_inf_pos[self._xp.newaxis, :],
|
| 675 |
+
(npoints, 1),
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# If any components of x are 0, then this component will be mapped to infinity
|
| 679 |
+
# under the transformation used for doubly-infinite limits.
|
| 680 |
+
#
|
| 681 |
+
# Handle the zero values and non-zero values separately to avoid division by
|
| 682 |
+
# zero.
|
| 683 |
+
zero_mask = x[double_inf_mask] == 0
|
| 684 |
+
non_zero_mask = double_inf_mask & ~zero_mask
|
| 685 |
+
t[zero_mask] = math.inf
|
| 686 |
+
t[non_zero_mask] = 1/(x[non_zero_mask] + self._xp.sign(x[non_zero_mask]))
|
| 687 |
+
|
| 688 |
+
start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
|
| 689 |
+
t[semi_inf_mask] = 1/(x[semi_inf_mask] - start + 1)
|
| 690 |
+
|
| 691 |
+
return t
|
| 692 |
+
|
| 693 |
+
def __call__(self, t, *args, **kwargs):
|
| 694 |
+
x = xp_copy(t)
|
| 695 |
+
npoints = t.shape[0]
|
| 696 |
+
|
| 697 |
+
double_inf_mask = self._xp.tile(
|
| 698 |
+
self._double_inf_pos[self._xp.newaxis, :],
|
| 699 |
+
(npoints, 1),
|
| 700 |
+
)
|
| 701 |
+
|
| 702 |
+
semi_inf_mask = self._xp.tile(
|
| 703 |
+
self._semi_inf_pos[self._xp.newaxis, :],
|
| 704 |
+
(npoints, 1),
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
# For (-oo, oo) -> (-1, 1), use the transformation x = (1-|t|)/t.
|
| 708 |
+
x[double_inf_mask] = (
|
| 709 |
+
(1 - self._xp.abs(t[double_inf_mask])) / t[double_inf_mask]
|
| 710 |
+
)
|
| 711 |
+
|
| 712 |
+
start = self._xp.tile(self._orig_a[self._semi_inf_pos], (npoints,))
|
| 713 |
+
|
| 714 |
+
# For (start, oo) -> (0, 1), use the transformation x = start + (1-t)/t.
|
| 715 |
+
x[semi_inf_mask] = start + (1 - t[semi_inf_mask]) / t[semi_inf_mask]
|
| 716 |
+
|
| 717 |
+
jacobian_det = 1/self._xp.prod(
|
| 718 |
+
self._xp.reshape(
|
| 719 |
+
t[semi_inf_mask | double_inf_mask]**2,
|
| 720 |
+
(-1, self._num_inf),
|
| 721 |
+
),
|
| 722 |
+
axis=-1,
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
f_x = self._f(x, *args, **kwargs)
|
| 726 |
+
jacobian_det = self._xp.reshape(jacobian_det, (-1, *([1]*(len(f_x.shape) - 1))))
|
| 727 |
+
|
| 728 |
+
return f_x * jacobian_det
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9d2ae0102227169f215e6fcea4a55e39b893876371e913db713a6b426ddc1304
|
| 3 |
+
size 116977
|
evalkit_eagle/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
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (542 Bytes). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/base.cpython-310.pyc
ADDED
|
Binary file (10.8 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/bdf.cpython-310.pyc
ADDED
|
Binary file (14.7 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc
ADDED
|
Binary file (4.92 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc
ADDED
|
Binary file (29.3 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc
ADDED
|
Binary file (8.5 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/rk.cpython-310.pyc
ADDED
|
Binary file (22 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.linalg import lu_factor, lu_solve
|
| 3 |
+
from scipy.sparse import issparse, csc_matrix, eye
|
| 4 |
+
from scipy.sparse.linalg import splu
|
| 5 |
+
from scipy.optimize._numdiff import group_columns
|
| 6 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
| 7 |
+
norm, EPS, num_jac, validate_first_step,
|
| 8 |
+
warn_extraneous)
|
| 9 |
+
from .base import OdeSolver, DenseOutput
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
MAX_ORDER = 5
|
| 13 |
+
NEWTON_MAXITER = 4
|
| 14 |
+
MIN_FACTOR = 0.2
|
| 15 |
+
MAX_FACTOR = 10
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def compute_R(order, factor):
|
| 19 |
+
"""Compute the matrix for changing the differences array."""
|
| 20 |
+
I = np.arange(1, order + 1)[:, None]
|
| 21 |
+
J = np.arange(1, order + 1)
|
| 22 |
+
M = np.zeros((order + 1, order + 1))
|
| 23 |
+
M[1:, 1:] = (I - 1 - factor * J) / I
|
| 24 |
+
M[0] = 1
|
| 25 |
+
return np.cumprod(M, axis=0)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def change_D(D, order, factor):
|
| 29 |
+
"""Change differences array in-place when step size is changed."""
|
| 30 |
+
R = compute_R(order, factor)
|
| 31 |
+
U = compute_R(order, 1)
|
| 32 |
+
RU = R.dot(U)
|
| 33 |
+
D[:order + 1] = np.dot(RU.T, D[:order + 1])
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def solve_bdf_system(fun, t_new, y_predict, c, psi, LU, solve_lu, scale, tol):
|
| 37 |
+
"""Solve the algebraic system resulting from BDF method."""
|
| 38 |
+
d = 0
|
| 39 |
+
y = y_predict.copy()
|
| 40 |
+
dy_norm_old = None
|
| 41 |
+
converged = False
|
| 42 |
+
for k in range(NEWTON_MAXITER):
|
| 43 |
+
f = fun(t_new, y)
|
| 44 |
+
if not np.all(np.isfinite(f)):
|
| 45 |
+
break
|
| 46 |
+
|
| 47 |
+
dy = solve_lu(LU, c * f - psi - d)
|
| 48 |
+
dy_norm = norm(dy / scale)
|
| 49 |
+
|
| 50 |
+
if dy_norm_old is None:
|
| 51 |
+
rate = None
|
| 52 |
+
else:
|
| 53 |
+
rate = dy_norm / dy_norm_old
|
| 54 |
+
|
| 55 |
+
if (rate is not None and (rate >= 1 or
|
| 56 |
+
rate ** (NEWTON_MAXITER - k) / (1 - rate) * dy_norm > tol)):
|
| 57 |
+
break
|
| 58 |
+
|
| 59 |
+
y += dy
|
| 60 |
+
d += dy
|
| 61 |
+
|
| 62 |
+
if (dy_norm == 0 or
|
| 63 |
+
rate is not None and rate / (1 - rate) * dy_norm < tol):
|
| 64 |
+
converged = True
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
dy_norm_old = dy_norm
|
| 68 |
+
|
| 69 |
+
return converged, k + 1, y, d
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class BDF(OdeSolver):
|
| 73 |
+
"""Implicit method based on backward-differentiation formulas.
|
| 74 |
+
|
| 75 |
+
This is a variable order method with the order varying automatically from
|
| 76 |
+
1 to 5. The general framework of the BDF algorithm is described in [1]_.
|
| 77 |
+
This class implements a quasi-constant step size as explained in [2]_.
|
| 78 |
+
The error estimation strategy for the constant-step BDF is derived in [3]_.
|
| 79 |
+
An accuracy enhancement using modified formulas (NDF) [2]_ is also implemented.
|
| 80 |
+
|
| 81 |
+
Can be applied in the complex domain.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
fun : callable
|
| 86 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 87 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 88 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 89 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 90 |
+
information.
|
| 91 |
+
t0 : float
|
| 92 |
+
Initial time.
|
| 93 |
+
y0 : array_like, shape (n,)
|
| 94 |
+
Initial state.
|
| 95 |
+
t_bound : float
|
| 96 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 97 |
+
determines the direction of the integration.
|
| 98 |
+
first_step : float or None, optional
|
| 99 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 100 |
+
should choose.
|
| 101 |
+
max_step : float, optional
|
| 102 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 103 |
+
bounded and determined solely by the solver.
|
| 104 |
+
rtol, atol : float and array_like, optional
|
| 105 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 106 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 107 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 108 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 109 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 110 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 111 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 112 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 113 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 114 |
+
than `atol`. If components of y have different scales, it might be
|
| 115 |
+
beneficial to set different `atol` values for different components by
|
| 116 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 117 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 118 |
+
jac : {None, array_like, sparse_matrix, callable}, optional
|
| 119 |
+
Jacobian matrix of the right-hand side of the system with respect to y,
|
| 120 |
+
required by this method. The Jacobian matrix has shape (n, n) and its
|
| 121 |
+
element (i, j) is equal to ``d f_i / d y_j``.
|
| 122 |
+
There are three ways to define the Jacobian:
|
| 123 |
+
|
| 124 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
| 125 |
+
be constant.
|
| 126 |
+
* If callable, the Jacobian is assumed to depend on both
|
| 127 |
+
t and y; it will be called as ``jac(t, y)`` as necessary.
|
| 128 |
+
For the 'Radau' and 'BDF' methods, the return value might be a
|
| 129 |
+
sparse matrix.
|
| 130 |
+
* If None (default), the Jacobian will be approximated by
|
| 131 |
+
finite differences.
|
| 132 |
+
|
| 133 |
+
It is generally recommended to provide the Jacobian rather than
|
| 134 |
+
relying on a finite-difference approximation.
|
| 135 |
+
jac_sparsity : {None, array_like, sparse matrix}, optional
|
| 136 |
+
Defines a sparsity structure of the Jacobian matrix for a
|
| 137 |
+
finite-difference approximation. Its shape must be (n, n). This argument
|
| 138 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
|
| 139 |
+
elements in *each* row, providing the sparsity structure will greatly
|
| 140 |
+
speed up the computations [4]_. A zero entry means that a corresponding
|
| 141 |
+
element in the Jacobian is always zero. If None (default), the Jacobian
|
| 142 |
+
is assumed to be dense.
|
| 143 |
+
vectorized : bool, optional
|
| 144 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
| 145 |
+
|
| 146 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 147 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 148 |
+
|
| 149 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 150 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 151 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 152 |
+
the returned array is the time derivative of the state corresponding
|
| 153 |
+
with a column of ``y``).
|
| 154 |
+
|
| 155 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 156 |
+
approximation of the Jacobian by this method, but may result in slower
|
| 157 |
+
execution overall in some circumstances (e.g. small ``len(y0)``).
|
| 158 |
+
|
| 159 |
+
Attributes
|
| 160 |
+
----------
|
| 161 |
+
n : int
|
| 162 |
+
Number of equations.
|
| 163 |
+
status : string
|
| 164 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 165 |
+
t_bound : float
|
| 166 |
+
Boundary time.
|
| 167 |
+
direction : float
|
| 168 |
+
Integration direction: +1 or -1.
|
| 169 |
+
t : float
|
| 170 |
+
Current time.
|
| 171 |
+
y : ndarray
|
| 172 |
+
Current state.
|
| 173 |
+
t_old : float
|
| 174 |
+
Previous time. None if no steps were made yet.
|
| 175 |
+
step_size : float
|
| 176 |
+
Size of the last successful step. None if no steps were made yet.
|
| 177 |
+
nfev : int
|
| 178 |
+
Number of evaluations of the right-hand side.
|
| 179 |
+
njev : int
|
| 180 |
+
Number of evaluations of the Jacobian.
|
| 181 |
+
nlu : int
|
| 182 |
+
Number of LU decompositions.
|
| 183 |
+
|
| 184 |
+
References
|
| 185 |
+
----------
|
| 186 |
+
.. [1] G. D. Byrne, A. C. Hindmarsh, "A Polyalgorithm for the Numerical
|
| 187 |
+
Solution of Ordinary Differential Equations", ACM Transactions on
|
| 188 |
+
Mathematical Software, Vol. 1, No. 1, pp. 71-96, March 1975.
|
| 189 |
+
.. [2] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
|
| 190 |
+
COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
|
| 191 |
+
.. [3] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations I:
|
| 192 |
+
Nonstiff Problems", Sec. III.2.
|
| 193 |
+
.. [4] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
| 194 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
| 195 |
+
and its Applications, 13, pp. 117-120, 1974.
|
| 196 |
+
"""
|
| 197 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
| 198 |
+
rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
|
| 199 |
+
vectorized=False, first_step=None, **extraneous):
|
| 200 |
+
warn_extraneous(extraneous)
|
| 201 |
+
super().__init__(fun, t0, y0, t_bound, vectorized,
|
| 202 |
+
support_complex=True)
|
| 203 |
+
self.max_step = validate_max_step(max_step)
|
| 204 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
| 205 |
+
f = self.fun(self.t, self.y)
|
| 206 |
+
if first_step is None:
|
| 207 |
+
self.h_abs = select_initial_step(self.fun, self.t, self.y,
|
| 208 |
+
t_bound, max_step, f,
|
| 209 |
+
self.direction, 1,
|
| 210 |
+
self.rtol, self.atol)
|
| 211 |
+
else:
|
| 212 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
| 213 |
+
self.h_abs_old = None
|
| 214 |
+
self.error_norm_old = None
|
| 215 |
+
|
| 216 |
+
self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
|
| 217 |
+
|
| 218 |
+
self.jac_factor = None
|
| 219 |
+
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
|
| 220 |
+
if issparse(self.J):
|
| 221 |
+
def lu(A):
|
| 222 |
+
self.nlu += 1
|
| 223 |
+
return splu(A)
|
| 224 |
+
|
| 225 |
+
def solve_lu(LU, b):
|
| 226 |
+
return LU.solve(b)
|
| 227 |
+
|
| 228 |
+
I = eye(self.n, format='csc', dtype=self.y.dtype)
|
| 229 |
+
else:
|
| 230 |
+
def lu(A):
|
| 231 |
+
self.nlu += 1
|
| 232 |
+
return lu_factor(A, overwrite_a=True)
|
| 233 |
+
|
| 234 |
+
def solve_lu(LU, b):
|
| 235 |
+
return lu_solve(LU, b, overwrite_b=True)
|
| 236 |
+
|
| 237 |
+
I = np.identity(self.n, dtype=self.y.dtype)
|
| 238 |
+
|
| 239 |
+
self.lu = lu
|
| 240 |
+
self.solve_lu = solve_lu
|
| 241 |
+
self.I = I
|
| 242 |
+
|
| 243 |
+
kappa = np.array([0, -0.1850, -1/9, -0.0823, -0.0415, 0])
|
| 244 |
+
self.gamma = np.hstack((0, np.cumsum(1 / np.arange(1, MAX_ORDER + 1))))
|
| 245 |
+
self.alpha = (1 - kappa) * self.gamma
|
| 246 |
+
self.error_const = kappa * self.gamma + 1 / np.arange(1, MAX_ORDER + 2)
|
| 247 |
+
|
| 248 |
+
D = np.empty((MAX_ORDER + 3, self.n), dtype=self.y.dtype)
|
| 249 |
+
D[0] = self.y
|
| 250 |
+
D[1] = f * self.h_abs * self.direction
|
| 251 |
+
self.D = D
|
| 252 |
+
|
| 253 |
+
self.order = 1
|
| 254 |
+
self.n_equal_steps = 0
|
| 255 |
+
self.LU = None
|
| 256 |
+
|
| 257 |
+
def _validate_jac(self, jac, sparsity):
|
| 258 |
+
t0 = self.t
|
| 259 |
+
y0 = self.y
|
| 260 |
+
|
| 261 |
+
if jac is None:
|
| 262 |
+
if sparsity is not None:
|
| 263 |
+
if issparse(sparsity):
|
| 264 |
+
sparsity = csc_matrix(sparsity)
|
| 265 |
+
groups = group_columns(sparsity)
|
| 266 |
+
sparsity = (sparsity, groups)
|
| 267 |
+
|
| 268 |
+
def jac_wrapped(t, y):
|
| 269 |
+
self.njev += 1
|
| 270 |
+
f = self.fun_single(t, y)
|
| 271 |
+
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
|
| 272 |
+
self.atol, self.jac_factor,
|
| 273 |
+
sparsity)
|
| 274 |
+
return J
|
| 275 |
+
J = jac_wrapped(t0, y0)
|
| 276 |
+
elif callable(jac):
|
| 277 |
+
J = jac(t0, y0)
|
| 278 |
+
self.njev += 1
|
| 279 |
+
if issparse(J):
|
| 280 |
+
J = csc_matrix(J, dtype=y0.dtype)
|
| 281 |
+
|
| 282 |
+
def jac_wrapped(t, y):
|
| 283 |
+
self.njev += 1
|
| 284 |
+
return csc_matrix(jac(t, y), dtype=y0.dtype)
|
| 285 |
+
else:
|
| 286 |
+
J = np.asarray(J, dtype=y0.dtype)
|
| 287 |
+
|
| 288 |
+
def jac_wrapped(t, y):
|
| 289 |
+
self.njev += 1
|
| 290 |
+
return np.asarray(jac(t, y), dtype=y0.dtype)
|
| 291 |
+
|
| 292 |
+
if J.shape != (self.n, self.n):
|
| 293 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 294 |
+
f" but actually has {J.shape}.")
|
| 295 |
+
else:
|
| 296 |
+
if issparse(jac):
|
| 297 |
+
J = csc_matrix(jac, dtype=y0.dtype)
|
| 298 |
+
else:
|
| 299 |
+
J = np.asarray(jac, dtype=y0.dtype)
|
| 300 |
+
|
| 301 |
+
if J.shape != (self.n, self.n):
|
| 302 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 303 |
+
f" but actually has {J.shape}.")
|
| 304 |
+
jac_wrapped = None
|
| 305 |
+
|
| 306 |
+
return jac_wrapped, J
|
| 307 |
+
|
| 308 |
+
def _step_impl(self):
|
| 309 |
+
t = self.t
|
| 310 |
+
D = self.D
|
| 311 |
+
|
| 312 |
+
max_step = self.max_step
|
| 313 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
| 314 |
+
if self.h_abs > max_step:
|
| 315 |
+
h_abs = max_step
|
| 316 |
+
change_D(D, self.order, max_step / self.h_abs)
|
| 317 |
+
self.n_equal_steps = 0
|
| 318 |
+
elif self.h_abs < min_step:
|
| 319 |
+
h_abs = min_step
|
| 320 |
+
change_D(D, self.order, min_step / self.h_abs)
|
| 321 |
+
self.n_equal_steps = 0
|
| 322 |
+
else:
|
| 323 |
+
h_abs = self.h_abs
|
| 324 |
+
|
| 325 |
+
atol = self.atol
|
| 326 |
+
rtol = self.rtol
|
| 327 |
+
order = self.order
|
| 328 |
+
|
| 329 |
+
alpha = self.alpha
|
| 330 |
+
gamma = self.gamma
|
| 331 |
+
error_const = self.error_const
|
| 332 |
+
|
| 333 |
+
J = self.J
|
| 334 |
+
LU = self.LU
|
| 335 |
+
current_jac = self.jac is None
|
| 336 |
+
|
| 337 |
+
step_accepted = False
|
| 338 |
+
while not step_accepted:
|
| 339 |
+
if h_abs < min_step:
|
| 340 |
+
return False, self.TOO_SMALL_STEP
|
| 341 |
+
|
| 342 |
+
h = h_abs * self.direction
|
| 343 |
+
t_new = t + h
|
| 344 |
+
|
| 345 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
| 346 |
+
t_new = self.t_bound
|
| 347 |
+
change_D(D, order, np.abs(t_new - t) / h_abs)
|
| 348 |
+
self.n_equal_steps = 0
|
| 349 |
+
LU = None
|
| 350 |
+
|
| 351 |
+
h = t_new - t
|
| 352 |
+
h_abs = np.abs(h)
|
| 353 |
+
|
| 354 |
+
y_predict = np.sum(D[:order + 1], axis=0)
|
| 355 |
+
|
| 356 |
+
scale = atol + rtol * np.abs(y_predict)
|
| 357 |
+
psi = np.dot(D[1: order + 1].T, gamma[1: order + 1]) / alpha[order]
|
| 358 |
+
|
| 359 |
+
converged = False
|
| 360 |
+
c = h / alpha[order]
|
| 361 |
+
while not converged:
|
| 362 |
+
if LU is None:
|
| 363 |
+
LU = self.lu(self.I - c * J)
|
| 364 |
+
|
| 365 |
+
converged, n_iter, y_new, d = solve_bdf_system(
|
| 366 |
+
self.fun, t_new, y_predict, c, psi, LU, self.solve_lu,
|
| 367 |
+
scale, self.newton_tol)
|
| 368 |
+
|
| 369 |
+
if not converged:
|
| 370 |
+
if current_jac:
|
| 371 |
+
break
|
| 372 |
+
J = self.jac(t_new, y_predict)
|
| 373 |
+
LU = None
|
| 374 |
+
current_jac = True
|
| 375 |
+
|
| 376 |
+
if not converged:
|
| 377 |
+
factor = 0.5
|
| 378 |
+
h_abs *= factor
|
| 379 |
+
change_D(D, order, factor)
|
| 380 |
+
self.n_equal_steps = 0
|
| 381 |
+
LU = None
|
| 382 |
+
continue
|
| 383 |
+
|
| 384 |
+
safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
|
| 385 |
+
+ n_iter)
|
| 386 |
+
|
| 387 |
+
scale = atol + rtol * np.abs(y_new)
|
| 388 |
+
error = error_const[order] * d
|
| 389 |
+
error_norm = norm(error / scale)
|
| 390 |
+
|
| 391 |
+
if error_norm > 1:
|
| 392 |
+
factor = max(MIN_FACTOR,
|
| 393 |
+
safety * error_norm ** (-1 / (order + 1)))
|
| 394 |
+
h_abs *= factor
|
| 395 |
+
change_D(D, order, factor)
|
| 396 |
+
self.n_equal_steps = 0
|
| 397 |
+
# As we didn't have problems with convergence, we don't
|
| 398 |
+
# reset LU here.
|
| 399 |
+
else:
|
| 400 |
+
step_accepted = True
|
| 401 |
+
|
| 402 |
+
self.n_equal_steps += 1
|
| 403 |
+
|
| 404 |
+
self.t = t_new
|
| 405 |
+
self.y = y_new
|
| 406 |
+
|
| 407 |
+
self.h_abs = h_abs
|
| 408 |
+
self.J = J
|
| 409 |
+
self.LU = LU
|
| 410 |
+
|
| 411 |
+
# Update differences. The principal relation here is
|
| 412 |
+
# D^{j + 1} y_n = D^{j} y_n - D^{j} y_{n - 1}. Keep in mind that D
|
| 413 |
+
# contained difference for previous interpolating polynomial and
|
| 414 |
+
# d = D^{k + 1} y_n. Thus this elegant code follows.
|
| 415 |
+
D[order + 2] = d - D[order + 1]
|
| 416 |
+
D[order + 1] = d
|
| 417 |
+
for i in reversed(range(order + 1)):
|
| 418 |
+
D[i] += D[i + 1]
|
| 419 |
+
|
| 420 |
+
if self.n_equal_steps < order + 1:
|
| 421 |
+
return True, None
|
| 422 |
+
|
| 423 |
+
if order > 1:
|
| 424 |
+
error_m = error_const[order - 1] * D[order]
|
| 425 |
+
error_m_norm = norm(error_m / scale)
|
| 426 |
+
else:
|
| 427 |
+
error_m_norm = np.inf
|
| 428 |
+
|
| 429 |
+
if order < MAX_ORDER:
|
| 430 |
+
error_p = error_const[order + 1] * D[order + 2]
|
| 431 |
+
error_p_norm = norm(error_p / scale)
|
| 432 |
+
else:
|
| 433 |
+
error_p_norm = np.inf
|
| 434 |
+
|
| 435 |
+
error_norms = np.array([error_m_norm, error_norm, error_p_norm])
|
| 436 |
+
with np.errstate(divide='ignore'):
|
| 437 |
+
factors = error_norms ** (-1 / np.arange(order, order + 3))
|
| 438 |
+
|
| 439 |
+
delta_order = np.argmax(factors) - 1
|
| 440 |
+
order += delta_order
|
| 441 |
+
self.order = order
|
| 442 |
+
|
| 443 |
+
factor = min(MAX_FACTOR, safety * np.max(factors))
|
| 444 |
+
self.h_abs *= factor
|
| 445 |
+
change_D(D, order, factor)
|
| 446 |
+
self.n_equal_steps = 0
|
| 447 |
+
self.LU = None
|
| 448 |
+
|
| 449 |
+
return True, None
|
| 450 |
+
|
| 451 |
+
def _dense_output_impl(self):
|
| 452 |
+
return BdfDenseOutput(self.t_old, self.t, self.h_abs * self.direction,
|
| 453 |
+
self.order, self.D[:self.order + 1].copy())
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
class BdfDenseOutput(DenseOutput):
|
| 457 |
+
def __init__(self, t_old, t, h, order, D):
|
| 458 |
+
super().__init__(t_old, t)
|
| 459 |
+
self.order = order
|
| 460 |
+
self.t_shift = self.t - h * np.arange(self.order)
|
| 461 |
+
self.denom = h * (1 + np.arange(self.order))
|
| 462 |
+
self.D = D
|
| 463 |
+
|
| 464 |
+
def _call_impl(self, t):
|
| 465 |
+
if t.ndim == 0:
|
| 466 |
+
x = (t - self.t_shift) / self.denom
|
| 467 |
+
p = np.cumprod(x)
|
| 468 |
+
else:
|
| 469 |
+
x = (t - self.t_shift[:, None]) / self.denom[:, None]
|
| 470 |
+
p = np.cumprod(x, axis=0)
|
| 471 |
+
|
| 472 |
+
y = np.dot(self.D[1:].T, p)
|
| 473 |
+
if y.ndim == 1:
|
| 474 |
+
y += self.D[0]
|
| 475 |
+
else:
|
| 476 |
+
y += self.D[0, :, None]
|
| 477 |
+
|
| 478 |
+
return y
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import groupby
|
| 2 |
+
from warnings import warn
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy.sparse import find, coo_matrix
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
EPS = np.finfo(float).eps
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def validate_first_step(first_step, t0, t_bound):
|
| 11 |
+
"""Assert that first_step is valid and return it."""
|
| 12 |
+
if first_step <= 0:
|
| 13 |
+
raise ValueError("`first_step` must be positive.")
|
| 14 |
+
if first_step > np.abs(t_bound - t0):
|
| 15 |
+
raise ValueError("`first_step` exceeds bounds.")
|
| 16 |
+
return first_step
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_max_step(max_step):
|
| 20 |
+
"""Assert that max_Step is valid and return it."""
|
| 21 |
+
if max_step <= 0:
|
| 22 |
+
raise ValueError("`max_step` must be positive.")
|
| 23 |
+
return max_step
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def warn_extraneous(extraneous):
|
| 27 |
+
"""Display a warning for extraneous keyword arguments.
|
| 28 |
+
|
| 29 |
+
The initializer of each solver class is expected to collect keyword
|
| 30 |
+
arguments that it doesn't understand and warn about them. This function
|
| 31 |
+
prints a warning for each key in the supplied dictionary.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
extraneous : dict
|
| 36 |
+
Extraneous keyword arguments
|
| 37 |
+
"""
|
| 38 |
+
if extraneous:
|
| 39 |
+
warn("The following arguments have no effect for a chosen solver: "
|
| 40 |
+
f"{', '.join(f'`{x}`' for x in extraneous)}.",
|
| 41 |
+
stacklevel=3)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def validate_tol(rtol, atol, n):
|
| 45 |
+
"""Validate tolerance values."""
|
| 46 |
+
|
| 47 |
+
if np.any(rtol < 100 * EPS):
|
| 48 |
+
warn("At least one element of `rtol` is too small. "
|
| 49 |
+
f"Setting `rtol = np.maximum(rtol, {100 * EPS})`.",
|
| 50 |
+
stacklevel=3)
|
| 51 |
+
rtol = np.maximum(rtol, 100 * EPS)
|
| 52 |
+
|
| 53 |
+
atol = np.asarray(atol)
|
| 54 |
+
if atol.ndim > 0 and atol.shape != (n,):
|
| 55 |
+
raise ValueError("`atol` has wrong shape.")
|
| 56 |
+
|
| 57 |
+
if np.any(atol < 0):
|
| 58 |
+
raise ValueError("`atol` must be positive.")
|
| 59 |
+
|
| 60 |
+
return rtol, atol
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def norm(x):
|
| 64 |
+
"""Compute RMS norm."""
|
| 65 |
+
return np.linalg.norm(x) / x.size ** 0.5
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def select_initial_step(fun, t0, y0, t_bound,
|
| 69 |
+
max_step, f0, direction, order, rtol, atol):
|
| 70 |
+
"""Empirically select a good initial step.
|
| 71 |
+
|
| 72 |
+
The algorithm is described in [1]_.
|
| 73 |
+
|
| 74 |
+
Parameters
|
| 75 |
+
----------
|
| 76 |
+
fun : callable
|
| 77 |
+
Right-hand side of the system.
|
| 78 |
+
t0 : float
|
| 79 |
+
Initial value of the independent variable.
|
| 80 |
+
y0 : ndarray, shape (n,)
|
| 81 |
+
Initial value of the dependent variable.
|
| 82 |
+
t_bound : float
|
| 83 |
+
End-point of integration interval; used to ensure that t0+step<=tbound
|
| 84 |
+
and that fun is only evaluated in the interval [t0,tbound]
|
| 85 |
+
max_step : float
|
| 86 |
+
Maximum allowable step size.
|
| 87 |
+
f0 : ndarray, shape (n,)
|
| 88 |
+
Initial value of the derivative, i.e., ``fun(t0, y0)``.
|
| 89 |
+
direction : float
|
| 90 |
+
Integration direction.
|
| 91 |
+
order : float
|
| 92 |
+
Error estimator order. It means that the error controlled by the
|
| 93 |
+
algorithm is proportional to ``step_size ** (order + 1)`.
|
| 94 |
+
rtol : float
|
| 95 |
+
Desired relative tolerance.
|
| 96 |
+
atol : float
|
| 97 |
+
Desired absolute tolerance.
|
| 98 |
+
|
| 99 |
+
Returns
|
| 100 |
+
-------
|
| 101 |
+
h_abs : float
|
| 102 |
+
Absolute value of the suggested initial step.
|
| 103 |
+
|
| 104 |
+
References
|
| 105 |
+
----------
|
| 106 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
| 107 |
+
Equations I: Nonstiff Problems", Sec. II.4.
|
| 108 |
+
"""
|
| 109 |
+
if y0.size == 0:
|
| 110 |
+
return np.inf
|
| 111 |
+
|
| 112 |
+
interval_length = abs(t_bound - t0)
|
| 113 |
+
if interval_length == 0.0:
|
| 114 |
+
return 0.0
|
| 115 |
+
|
| 116 |
+
scale = atol + np.abs(y0) * rtol
|
| 117 |
+
d0 = norm(y0 / scale)
|
| 118 |
+
d1 = norm(f0 / scale)
|
| 119 |
+
if d0 < 1e-5 or d1 < 1e-5:
|
| 120 |
+
h0 = 1e-6
|
| 121 |
+
else:
|
| 122 |
+
h0 = 0.01 * d0 / d1
|
| 123 |
+
# Check t0+h0*direction doesn't take us beyond t_bound
|
| 124 |
+
h0 = min(h0, interval_length)
|
| 125 |
+
y1 = y0 + h0 * direction * f0
|
| 126 |
+
f1 = fun(t0 + h0 * direction, y1)
|
| 127 |
+
d2 = norm((f1 - f0) / scale) / h0
|
| 128 |
+
|
| 129 |
+
if d1 <= 1e-15 and d2 <= 1e-15:
|
| 130 |
+
h1 = max(1e-6, h0 * 1e-3)
|
| 131 |
+
else:
|
| 132 |
+
h1 = (0.01 / max(d1, d2)) ** (1 / (order + 1))
|
| 133 |
+
|
| 134 |
+
return min(100 * h0, h1, interval_length, max_step)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class OdeSolution:
|
| 138 |
+
"""Continuous ODE solution.
|
| 139 |
+
|
| 140 |
+
It is organized as a collection of `DenseOutput` objects which represent
|
| 141 |
+
local interpolants. It provides an algorithm to select a right interpolant
|
| 142 |
+
for each given point.
|
| 143 |
+
|
| 144 |
+
The interpolants cover the range between `t_min` and `t_max` (see
|
| 145 |
+
Attributes below). Evaluation outside this interval is not forbidden, but
|
| 146 |
+
the accuracy is not guaranteed.
|
| 147 |
+
|
| 148 |
+
When evaluating at a breakpoint (one of the values in `ts`) a segment with
|
| 149 |
+
the lower index is selected.
|
| 150 |
+
|
| 151 |
+
Parameters
|
| 152 |
+
----------
|
| 153 |
+
ts : array_like, shape (n_segments + 1,)
|
| 154 |
+
Time instants between which local interpolants are defined. Must
|
| 155 |
+
be strictly increasing or decreasing (zero segment with two points is
|
| 156 |
+
also allowed).
|
| 157 |
+
interpolants : list of DenseOutput with n_segments elements
|
| 158 |
+
Local interpolants. An i-th interpolant is assumed to be defined
|
| 159 |
+
between ``ts[i]`` and ``ts[i + 1]``.
|
| 160 |
+
alt_segment : boolean
|
| 161 |
+
Requests the alternative interpolant segment selection scheme. At each
|
| 162 |
+
solver integration point, two interpolant segments are available. The
|
| 163 |
+
default (False) and alternative (True) behaviours select the segment
|
| 164 |
+
for which the requested time corresponded to ``t`` and ``t_old``,
|
| 165 |
+
respectively. This functionality is only relevant for testing the
|
| 166 |
+
interpolants' accuracy: different integrators use different
|
| 167 |
+
construction strategies.
|
| 168 |
+
|
| 169 |
+
Attributes
|
| 170 |
+
----------
|
| 171 |
+
t_min, t_max : float
|
| 172 |
+
Time range of the interpolation.
|
| 173 |
+
"""
|
| 174 |
+
def __init__(self, ts, interpolants, alt_segment=False):
|
| 175 |
+
ts = np.asarray(ts)
|
| 176 |
+
d = np.diff(ts)
|
| 177 |
+
# The first case covers integration on zero segment.
|
| 178 |
+
if not ((ts.size == 2 and ts[0] == ts[-1])
|
| 179 |
+
or np.all(d > 0) or np.all(d < 0)):
|
| 180 |
+
raise ValueError("`ts` must be strictly increasing or decreasing.")
|
| 181 |
+
|
| 182 |
+
self.n_segments = len(interpolants)
|
| 183 |
+
if ts.shape != (self.n_segments + 1,):
|
| 184 |
+
raise ValueError("Numbers of time stamps and interpolants "
|
| 185 |
+
"don't match.")
|
| 186 |
+
|
| 187 |
+
self.ts = ts
|
| 188 |
+
self.interpolants = interpolants
|
| 189 |
+
if ts[-1] >= ts[0]:
|
| 190 |
+
self.t_min = ts[0]
|
| 191 |
+
self.t_max = ts[-1]
|
| 192 |
+
self.ascending = True
|
| 193 |
+
self.side = "right" if alt_segment else "left"
|
| 194 |
+
self.ts_sorted = ts
|
| 195 |
+
else:
|
| 196 |
+
self.t_min = ts[-1]
|
| 197 |
+
self.t_max = ts[0]
|
| 198 |
+
self.ascending = False
|
| 199 |
+
self.side = "left" if alt_segment else "right"
|
| 200 |
+
self.ts_sorted = ts[::-1]
|
| 201 |
+
|
| 202 |
+
def _call_single(self, t):
|
| 203 |
+
# Here we preserve a certain symmetry that when t is in self.ts,
|
| 204 |
+
# if alt_segment=False, then we prioritize a segment with a lower
|
| 205 |
+
# index.
|
| 206 |
+
ind = np.searchsorted(self.ts_sorted, t, side=self.side)
|
| 207 |
+
|
| 208 |
+
segment = min(max(ind - 1, 0), self.n_segments - 1)
|
| 209 |
+
if not self.ascending:
|
| 210 |
+
segment = self.n_segments - 1 - segment
|
| 211 |
+
|
| 212 |
+
return self.interpolants[segment](t)
|
| 213 |
+
|
| 214 |
+
def __call__(self, t):
|
| 215 |
+
"""Evaluate the solution.
|
| 216 |
+
|
| 217 |
+
Parameters
|
| 218 |
+
----------
|
| 219 |
+
t : float or array_like with shape (n_points,)
|
| 220 |
+
Points to evaluate at.
|
| 221 |
+
|
| 222 |
+
Returns
|
| 223 |
+
-------
|
| 224 |
+
y : ndarray, shape (n_states,) or (n_states, n_points)
|
| 225 |
+
Computed values. Shape depends on whether `t` is a scalar or a
|
| 226 |
+
1-D array.
|
| 227 |
+
"""
|
| 228 |
+
t = np.asarray(t)
|
| 229 |
+
|
| 230 |
+
if t.ndim == 0:
|
| 231 |
+
return self._call_single(t)
|
| 232 |
+
|
| 233 |
+
order = np.argsort(t)
|
| 234 |
+
reverse = np.empty_like(order)
|
| 235 |
+
reverse[order] = np.arange(order.shape[0])
|
| 236 |
+
t_sorted = t[order]
|
| 237 |
+
|
| 238 |
+
# See comment in self._call_single.
|
| 239 |
+
segments = np.searchsorted(self.ts_sorted, t_sorted, side=self.side)
|
| 240 |
+
segments -= 1
|
| 241 |
+
segments[segments < 0] = 0
|
| 242 |
+
segments[segments > self.n_segments - 1] = self.n_segments - 1
|
| 243 |
+
if not self.ascending:
|
| 244 |
+
segments = self.n_segments - 1 - segments
|
| 245 |
+
|
| 246 |
+
ys = []
|
| 247 |
+
group_start = 0
|
| 248 |
+
for segment, group in groupby(segments):
|
| 249 |
+
group_end = group_start + len(list(group))
|
| 250 |
+
y = self.interpolants[segment](t_sorted[group_start:group_end])
|
| 251 |
+
ys.append(y)
|
| 252 |
+
group_start = group_end
|
| 253 |
+
|
| 254 |
+
ys = np.hstack(ys)
|
| 255 |
+
ys = ys[:, reverse]
|
| 256 |
+
|
| 257 |
+
return ys
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
NUM_JAC_DIFF_REJECT = EPS ** 0.875
|
| 261 |
+
NUM_JAC_DIFF_SMALL = EPS ** 0.75
|
| 262 |
+
NUM_JAC_DIFF_BIG = EPS ** 0.25
|
| 263 |
+
NUM_JAC_MIN_FACTOR = 1e3 * EPS
|
| 264 |
+
NUM_JAC_FACTOR_INCREASE = 10
|
| 265 |
+
NUM_JAC_FACTOR_DECREASE = 0.1
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def num_jac(fun, t, y, f, threshold, factor, sparsity=None):
|
| 269 |
+
"""Finite differences Jacobian approximation tailored for ODE solvers.
|
| 270 |
+
|
| 271 |
+
This function computes finite difference approximation to the Jacobian
|
| 272 |
+
matrix of `fun` with respect to `y` using forward differences.
|
| 273 |
+
The Jacobian matrix has shape (n, n) and its element (i, j) is equal to
|
| 274 |
+
``d f_i / d y_j``.
|
| 275 |
+
|
| 276 |
+
A special feature of this function is the ability to correct the step
|
| 277 |
+
size from iteration to iteration. The main idea is to keep the finite
|
| 278 |
+
difference significantly separated from its round-off error which
|
| 279 |
+
approximately equals ``EPS * np.abs(f)``. It reduces a possibility of a
|
| 280 |
+
huge error and assures that the estimated derivative are reasonably close
|
| 281 |
+
to the true values (i.e., the finite difference approximation is at least
|
| 282 |
+
qualitatively reflects the structure of the true Jacobian).
|
| 283 |
+
|
| 284 |
+
Parameters
|
| 285 |
+
----------
|
| 286 |
+
fun : callable
|
| 287 |
+
Right-hand side of the system implemented in a vectorized fashion.
|
| 288 |
+
t : float
|
| 289 |
+
Current time.
|
| 290 |
+
y : ndarray, shape (n,)
|
| 291 |
+
Current state.
|
| 292 |
+
f : ndarray, shape (n,)
|
| 293 |
+
Value of the right hand side at (t, y).
|
| 294 |
+
threshold : float
|
| 295 |
+
Threshold for `y` value used for computing the step size as
|
| 296 |
+
``factor * np.maximum(np.abs(y), threshold)``. Typically, the value of
|
| 297 |
+
absolute tolerance (atol) for a solver should be passed as `threshold`.
|
| 298 |
+
factor : ndarray with shape (n,) or None
|
| 299 |
+
Factor to use for computing the step size. Pass None for the very
|
| 300 |
+
evaluation, then use the value returned from this function.
|
| 301 |
+
sparsity : tuple (structure, groups) or None
|
| 302 |
+
Sparsity structure of the Jacobian, `structure` must be csc_matrix.
|
| 303 |
+
|
| 304 |
+
Returns
|
| 305 |
+
-------
|
| 306 |
+
J : ndarray or csc_matrix, shape (n, n)
|
| 307 |
+
Jacobian matrix.
|
| 308 |
+
factor : ndarray, shape (n,)
|
| 309 |
+
Suggested `factor` for the next evaluation.
|
| 310 |
+
"""
|
| 311 |
+
y = np.asarray(y)
|
| 312 |
+
n = y.shape[0]
|
| 313 |
+
if n == 0:
|
| 314 |
+
return np.empty((0, 0)), factor
|
| 315 |
+
|
| 316 |
+
if factor is None:
|
| 317 |
+
factor = np.full(n, EPS ** 0.5)
|
| 318 |
+
else:
|
| 319 |
+
factor = factor.copy()
|
| 320 |
+
|
| 321 |
+
# Direct the step as ODE dictates, hoping that such a step won't lead to
|
| 322 |
+
# a problematic region. For complex ODEs it makes sense to use the real
|
| 323 |
+
# part of f as we use steps along real axis.
|
| 324 |
+
f_sign = 2 * (np.real(f) >= 0).astype(float) - 1
|
| 325 |
+
y_scale = f_sign * np.maximum(threshold, np.abs(y))
|
| 326 |
+
h = (y + factor * y_scale) - y
|
| 327 |
+
|
| 328 |
+
# Make sure that the step is not 0 to start with. Not likely it will be
|
| 329 |
+
# executed often.
|
| 330 |
+
for i in np.nonzero(h == 0)[0]:
|
| 331 |
+
while h[i] == 0:
|
| 332 |
+
factor[i] *= 10
|
| 333 |
+
h[i] = (y[i] + factor[i] * y_scale[i]) - y[i]
|
| 334 |
+
|
| 335 |
+
if sparsity is None:
|
| 336 |
+
return _dense_num_jac(fun, t, y, f, h, factor, y_scale)
|
| 337 |
+
else:
|
| 338 |
+
structure, groups = sparsity
|
| 339 |
+
return _sparse_num_jac(fun, t, y, f, h, factor, y_scale,
|
| 340 |
+
structure, groups)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _dense_num_jac(fun, t, y, f, h, factor, y_scale):
|
| 344 |
+
n = y.shape[0]
|
| 345 |
+
h_vecs = np.diag(h)
|
| 346 |
+
f_new = fun(t, y[:, None] + h_vecs)
|
| 347 |
+
diff = f_new - f[:, None]
|
| 348 |
+
max_ind = np.argmax(np.abs(diff), axis=0)
|
| 349 |
+
r = np.arange(n)
|
| 350 |
+
max_diff = np.abs(diff[max_ind, r])
|
| 351 |
+
scale = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
|
| 352 |
+
|
| 353 |
+
diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
|
| 354 |
+
if np.any(diff_too_small):
|
| 355 |
+
ind, = np.nonzero(diff_too_small)
|
| 356 |
+
new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
|
| 357 |
+
h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
|
| 358 |
+
h_vecs[ind, ind] = h_new
|
| 359 |
+
f_new = fun(t, y[:, None] + h_vecs[:, ind])
|
| 360 |
+
diff_new = f_new - f[:, None]
|
| 361 |
+
max_ind = np.argmax(np.abs(diff_new), axis=0)
|
| 362 |
+
r = np.arange(ind.shape[0])
|
| 363 |
+
max_diff_new = np.abs(diff_new[max_ind, r])
|
| 364 |
+
scale_new = np.maximum(np.abs(f[max_ind]), np.abs(f_new[max_ind, r]))
|
| 365 |
+
|
| 366 |
+
update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
|
| 367 |
+
if np.any(update):
|
| 368 |
+
update, = np.nonzero(update)
|
| 369 |
+
update_ind = ind[update]
|
| 370 |
+
factor[update_ind] = new_factor[update]
|
| 371 |
+
h[update_ind] = h_new[update]
|
| 372 |
+
diff[:, update_ind] = diff_new[:, update]
|
| 373 |
+
scale[update_ind] = scale_new[update]
|
| 374 |
+
max_diff[update_ind] = max_diff_new[update]
|
| 375 |
+
|
| 376 |
+
diff /= h
|
| 377 |
+
|
| 378 |
+
factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
|
| 379 |
+
factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
|
| 380 |
+
factor = np.maximum(factor, NUM_JAC_MIN_FACTOR)
|
| 381 |
+
|
| 382 |
+
return diff, factor
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _sparse_num_jac(fun, t, y, f, h, factor, y_scale, structure, groups):
|
| 386 |
+
n = y.shape[0]
|
| 387 |
+
n_groups = np.max(groups) + 1
|
| 388 |
+
h_vecs = np.empty((n_groups, n))
|
| 389 |
+
for group in range(n_groups):
|
| 390 |
+
e = np.equal(group, groups)
|
| 391 |
+
h_vecs[group] = h * e
|
| 392 |
+
h_vecs = h_vecs.T
|
| 393 |
+
|
| 394 |
+
f_new = fun(t, y[:, None] + h_vecs)
|
| 395 |
+
df = f_new - f[:, None]
|
| 396 |
+
|
| 397 |
+
i, j, _ = find(structure)
|
| 398 |
+
diff = coo_matrix((df[i, groups[j]], (i, j)), shape=(n, n)).tocsc()
|
| 399 |
+
max_ind = np.array(abs(diff).argmax(axis=0)).ravel()
|
| 400 |
+
r = np.arange(n)
|
| 401 |
+
max_diff = np.asarray(np.abs(diff[max_ind, r])).ravel()
|
| 402 |
+
scale = np.maximum(np.abs(f[max_ind]),
|
| 403 |
+
np.abs(f_new[max_ind, groups[r]]))
|
| 404 |
+
|
| 405 |
+
diff_too_small = max_diff < NUM_JAC_DIFF_REJECT * scale
|
| 406 |
+
if np.any(diff_too_small):
|
| 407 |
+
ind, = np.nonzero(diff_too_small)
|
| 408 |
+
new_factor = NUM_JAC_FACTOR_INCREASE * factor[ind]
|
| 409 |
+
h_new = (y[ind] + new_factor * y_scale[ind]) - y[ind]
|
| 410 |
+
h_new_all = np.zeros(n)
|
| 411 |
+
h_new_all[ind] = h_new
|
| 412 |
+
|
| 413 |
+
groups_unique = np.unique(groups[ind])
|
| 414 |
+
groups_map = np.empty(n_groups, dtype=int)
|
| 415 |
+
h_vecs = np.empty((groups_unique.shape[0], n))
|
| 416 |
+
for k, group in enumerate(groups_unique):
|
| 417 |
+
e = np.equal(group, groups)
|
| 418 |
+
h_vecs[k] = h_new_all * e
|
| 419 |
+
groups_map[group] = k
|
| 420 |
+
h_vecs = h_vecs.T
|
| 421 |
+
|
| 422 |
+
f_new = fun(t, y[:, None] + h_vecs)
|
| 423 |
+
df = f_new - f[:, None]
|
| 424 |
+
i, j, _ = find(structure[:, ind])
|
| 425 |
+
diff_new = coo_matrix((df[i, groups_map[groups[ind[j]]]],
|
| 426 |
+
(i, j)), shape=(n, ind.shape[0])).tocsc()
|
| 427 |
+
|
| 428 |
+
max_ind_new = np.array(abs(diff_new).argmax(axis=0)).ravel()
|
| 429 |
+
r = np.arange(ind.shape[0])
|
| 430 |
+
max_diff_new = np.asarray(np.abs(diff_new[max_ind_new, r])).ravel()
|
| 431 |
+
scale_new = np.maximum(
|
| 432 |
+
np.abs(f[max_ind_new]),
|
| 433 |
+
np.abs(f_new[max_ind_new, groups_map[groups[ind]]]))
|
| 434 |
+
|
| 435 |
+
update = max_diff[ind] * scale_new < max_diff_new * scale[ind]
|
| 436 |
+
if np.any(update):
|
| 437 |
+
update, = np.nonzero(update)
|
| 438 |
+
update_ind = ind[update]
|
| 439 |
+
factor[update_ind] = new_factor[update]
|
| 440 |
+
h[update_ind] = h_new[update]
|
| 441 |
+
diff[:, update_ind] = diff_new[:, update]
|
| 442 |
+
scale[update_ind] = scale_new[update]
|
| 443 |
+
max_diff[update_ind] = max_diff_new[update]
|
| 444 |
+
|
| 445 |
+
diff.data /= np.repeat(h, np.diff(diff.indptr))
|
| 446 |
+
|
| 447 |
+
factor[max_diff < NUM_JAC_DIFF_SMALL * scale] *= NUM_JAC_FACTOR_INCREASE
|
| 448 |
+
factor[max_diff > NUM_JAC_DIFF_BIG * scale] *= NUM_JAC_FACTOR_DECREASE
|
| 449 |
+
factor = np.maximum(factor, NUM_J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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/ivp.py
ADDED
|
@@ -0,0 +1,748 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import numpy as np
|
| 3 |
+
from .bdf import BDF
|
| 4 |
+
from .radau import Radau
|
| 5 |
+
from .rk import RK23, RK45, DOP853
|
| 6 |
+
from .lsoda import LSODA
|
| 7 |
+
from scipy.optimize import OptimizeResult
|
| 8 |
+
from .common import EPS, OdeSolution
|
| 9 |
+
from .base import OdeSolver
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
METHODS = {'RK23': RK23,
|
| 13 |
+
'RK45': RK45,
|
| 14 |
+
'DOP853': DOP853,
|
| 15 |
+
'Radau': Radau,
|
| 16 |
+
'BDF': BDF,
|
| 17 |
+
'LSODA': LSODA}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
MESSAGES = {0: "The solver successfully reached the end of the integration interval.",
|
| 21 |
+
1: "A termination event occurred."}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class OdeResult(OptimizeResult):
|
| 25 |
+
pass
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def prepare_events(events):
|
| 29 |
+
"""Standardize event functions and extract attributes."""
|
| 30 |
+
if callable(events):
|
| 31 |
+
events = (events,)
|
| 32 |
+
|
| 33 |
+
max_events = np.empty(len(events))
|
| 34 |
+
direction = np.empty(len(events))
|
| 35 |
+
for i, event in enumerate(events):
|
| 36 |
+
terminal = getattr(event, 'terminal', None)
|
| 37 |
+
direction[i] = getattr(event, 'direction', 0)
|
| 38 |
+
|
| 39 |
+
message = ('The `terminal` attribute of each event '
|
| 40 |
+
'must be a boolean or positive integer.')
|
| 41 |
+
if terminal is None or terminal == 0:
|
| 42 |
+
max_events[i] = np.inf
|
| 43 |
+
elif int(terminal) == terminal and terminal > 0:
|
| 44 |
+
max_events[i] = terminal
|
| 45 |
+
else:
|
| 46 |
+
raise ValueError(message)
|
| 47 |
+
|
| 48 |
+
return events, max_events, direction
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def solve_event_equation(event, sol, t_old, t):
|
| 52 |
+
"""Solve an equation corresponding to an ODE event.
|
| 53 |
+
|
| 54 |
+
The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an
|
| 55 |
+
ODE solver using some sort of interpolation. It is solved by
|
| 56 |
+
`scipy.optimize.brentq` with xtol=atol=4*EPS.
|
| 57 |
+
|
| 58 |
+
Parameters
|
| 59 |
+
----------
|
| 60 |
+
event : callable
|
| 61 |
+
Function ``event(t, y)``.
|
| 62 |
+
sol : callable
|
| 63 |
+
Function ``sol(t)`` which evaluates an ODE solution between `t_old`
|
| 64 |
+
and `t`.
|
| 65 |
+
t_old, t : float
|
| 66 |
+
Previous and new values of time. They will be used as a bracketing
|
| 67 |
+
interval.
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
root : float
|
| 72 |
+
Found solution.
|
| 73 |
+
"""
|
| 74 |
+
from scipy.optimize import brentq
|
| 75 |
+
return brentq(lambda t: event(t, sol(t)), t_old, t,
|
| 76 |
+
xtol=4 * EPS, rtol=4 * EPS)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def handle_events(sol, events, active_events, event_count, max_events,
|
| 80 |
+
t_old, t):
|
| 81 |
+
"""Helper function to handle events.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
sol : DenseOutput
|
| 86 |
+
Function ``sol(t)`` which evaluates an ODE solution between `t_old`
|
| 87 |
+
and `t`.
|
| 88 |
+
events : list of callables, length n_events
|
| 89 |
+
Event functions with signatures ``event(t, y)``.
|
| 90 |
+
active_events : ndarray
|
| 91 |
+
Indices of events which occurred.
|
| 92 |
+
event_count : ndarray
|
| 93 |
+
Current number of occurrences for each event.
|
| 94 |
+
max_events : ndarray, shape (n_events,)
|
| 95 |
+
Number of occurrences allowed for each event before integration
|
| 96 |
+
termination is issued.
|
| 97 |
+
t_old, t : float
|
| 98 |
+
Previous and new values of time.
|
| 99 |
+
|
| 100 |
+
Returns
|
| 101 |
+
-------
|
| 102 |
+
root_indices : ndarray
|
| 103 |
+
Indices of events which take zero between `t_old` and `t` and before
|
| 104 |
+
a possible termination.
|
| 105 |
+
roots : ndarray
|
| 106 |
+
Values of t at which events occurred.
|
| 107 |
+
terminate : bool
|
| 108 |
+
Whether a terminal event occurred.
|
| 109 |
+
"""
|
| 110 |
+
roots = [solve_event_equation(events[event_index], sol, t_old, t)
|
| 111 |
+
for event_index in active_events]
|
| 112 |
+
|
| 113 |
+
roots = np.asarray(roots)
|
| 114 |
+
|
| 115 |
+
if np.any(event_count[active_events] >= max_events[active_events]):
|
| 116 |
+
if t > t_old:
|
| 117 |
+
order = np.argsort(roots)
|
| 118 |
+
else:
|
| 119 |
+
order = np.argsort(-roots)
|
| 120 |
+
active_events = active_events[order]
|
| 121 |
+
roots = roots[order]
|
| 122 |
+
t = np.nonzero(event_count[active_events]
|
| 123 |
+
>= max_events[active_events])[0][0]
|
| 124 |
+
active_events = active_events[:t + 1]
|
| 125 |
+
roots = roots[:t + 1]
|
| 126 |
+
terminate = True
|
| 127 |
+
else:
|
| 128 |
+
terminate = False
|
| 129 |
+
|
| 130 |
+
return active_events, roots, terminate
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def find_active_events(g, g_new, direction):
|
| 134 |
+
"""Find which event occurred during an integration step.
|
| 135 |
+
|
| 136 |
+
Parameters
|
| 137 |
+
----------
|
| 138 |
+
g, g_new : array_like, shape (n_events,)
|
| 139 |
+
Values of event functions at a current and next points.
|
| 140 |
+
direction : ndarray, shape (n_events,)
|
| 141 |
+
Event "direction" according to the definition in `solve_ivp`.
|
| 142 |
+
|
| 143 |
+
Returns
|
| 144 |
+
-------
|
| 145 |
+
active_events : ndarray
|
| 146 |
+
Indices of events which occurred during the step.
|
| 147 |
+
"""
|
| 148 |
+
g, g_new = np.asarray(g), np.asarray(g_new)
|
| 149 |
+
up = (g <= 0) & (g_new >= 0)
|
| 150 |
+
down = (g >= 0) & (g_new <= 0)
|
| 151 |
+
either = up | down
|
| 152 |
+
mask = (up & (direction > 0) |
|
| 153 |
+
down & (direction < 0) |
|
| 154 |
+
either & (direction == 0))
|
| 155 |
+
|
| 156 |
+
return np.nonzero(mask)[0]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False,
|
| 160 |
+
events=None, vectorized=False, args=None, **options):
|
| 161 |
+
"""Solve an initial value problem for a system of ODEs.
|
| 162 |
+
|
| 163 |
+
This function numerically integrates a system of ordinary differential
|
| 164 |
+
equations given an initial value::
|
| 165 |
+
|
| 166 |
+
dy / dt = f(t, y)
|
| 167 |
+
y(t0) = y0
|
| 168 |
+
|
| 169 |
+
Here t is a 1-D independent variable (time), y(t) is an
|
| 170 |
+
N-D vector-valued function (state), and an N-D
|
| 171 |
+
vector-valued function f(t, y) determines the differential equations.
|
| 172 |
+
The goal is to find y(t) approximately satisfying the differential
|
| 173 |
+
equations, given an initial value y(t0)=y0.
|
| 174 |
+
|
| 175 |
+
Some of the solvers support integration in the complex domain, but note
|
| 176 |
+
that for stiff ODE solvers, the right-hand side must be
|
| 177 |
+
complex-differentiable (satisfy Cauchy-Riemann equations [11]_).
|
| 178 |
+
To solve a problem in the complex domain, pass y0 with a complex data type.
|
| 179 |
+
Another option always available is to rewrite your problem for real and
|
| 180 |
+
imaginary parts separately.
|
| 181 |
+
|
| 182 |
+
Parameters
|
| 183 |
+
----------
|
| 184 |
+
fun : callable
|
| 185 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 186 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 187 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional
|
| 188 |
+
arguments need to be passed if ``args`` is used (see documentation of
|
| 189 |
+
``args`` argument). ``fun`` must return an array of the same shape as
|
| 190 |
+
``y``. See `vectorized` for more information.
|
| 191 |
+
t_span : 2-member sequence
|
| 192 |
+
Interval of integration (t0, tf). The solver starts with t=t0 and
|
| 193 |
+
integrates until it reaches t=tf. Both t0 and tf must be floats
|
| 194 |
+
or values interpretable by the float conversion function.
|
| 195 |
+
y0 : array_like, shape (n,)
|
| 196 |
+
Initial state. For problems in the complex domain, pass `y0` with a
|
| 197 |
+
complex data type (even if the initial value is purely real).
|
| 198 |
+
method : string or `OdeSolver`, optional
|
| 199 |
+
Integration method to use:
|
| 200 |
+
|
| 201 |
+
* 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_.
|
| 202 |
+
The error is controlled assuming accuracy of the fourth-order
|
| 203 |
+
method, but steps are taken using the fifth-order accurate
|
| 204 |
+
formula (local extrapolation is done). A quartic interpolation
|
| 205 |
+
polynomial is used for the dense output [2]_. Can be applied in
|
| 206 |
+
the complex domain.
|
| 207 |
+
* 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error
|
| 208 |
+
is controlled assuming accuracy of the second-order method, but
|
| 209 |
+
steps are taken using the third-order accurate formula (local
|
| 210 |
+
extrapolation is done). A cubic Hermite polynomial is used for the
|
| 211 |
+
dense output. Can be applied in the complex domain.
|
| 212 |
+
* 'DOP853': Explicit Runge-Kutta method of order 8 [13]_.
|
| 213 |
+
Python implementation of the "DOP853" algorithm originally
|
| 214 |
+
written in Fortran [14]_. A 7-th order interpolation polynomial
|
| 215 |
+
accurate to 7-th order is used for the dense output.
|
| 216 |
+
Can be applied in the complex domain.
|
| 217 |
+
* 'Radau': Implicit Runge-Kutta method of the Radau IIA family of
|
| 218 |
+
order 5 [4]_. The error is controlled with a third-order accurate
|
| 219 |
+
embedded formula. A cubic polynomial which satisfies the
|
| 220 |
+
collocation conditions is used for the dense output.
|
| 221 |
+
* 'BDF': Implicit multi-step variable-order (1 to 5) method based
|
| 222 |
+
on a backward differentiation formula for the derivative
|
| 223 |
+
approximation [5]_. The implementation follows the one described
|
| 224 |
+
in [6]_. A quasi-constant step scheme is used and accuracy is
|
| 225 |
+
enhanced using the NDF modification. Can be applied in the
|
| 226 |
+
complex domain.
|
| 227 |
+
* 'LSODA': Adams/BDF method with automatic stiffness detection and
|
| 228 |
+
switching [7]_, [8]_. This is a wrapper of the Fortran solver
|
| 229 |
+
from ODEPACK.
|
| 230 |
+
|
| 231 |
+
Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used
|
| 232 |
+
for non-stiff problems and implicit methods ('Radau', 'BDF') for
|
| 233 |
+
stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended
|
| 234 |
+
for solving with high precision (low values of `rtol` and `atol`).
|
| 235 |
+
|
| 236 |
+
If not sure, first try to run 'RK45'. If it makes unusually many
|
| 237 |
+
iterations, diverges, or fails, your problem is likely to be stiff and
|
| 238 |
+
you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal
|
| 239 |
+
choice, but it might be somewhat less convenient to work with as it
|
| 240 |
+
wraps old Fortran code.
|
| 241 |
+
|
| 242 |
+
You can also pass an arbitrary class derived from `OdeSolver` which
|
| 243 |
+
implements the solver.
|
| 244 |
+
t_eval : array_like or None, optional
|
| 245 |
+
Times at which to store the computed solution, must be sorted and lie
|
| 246 |
+
within `t_span`. If None (default), use points selected by the solver.
|
| 247 |
+
dense_output : bool, optional
|
| 248 |
+
Whether to compute a continuous solution. Default is False.
|
| 249 |
+
events : callable, or list of callables, optional
|
| 250 |
+
Events to track. If None (default), no events will be tracked.
|
| 251 |
+
Each event occurs at the zeros of a continuous function of time and
|
| 252 |
+
state. Each function must have the signature ``event(t, y)`` where
|
| 253 |
+
additional argument have to be passed if ``args`` is used (see
|
| 254 |
+
documentation of ``args`` argument). Each function must return a
|
| 255 |
+
float. The solver will find an accurate value of `t` at which
|
| 256 |
+
``event(t, y(t)) = 0`` using a root-finding algorithm. By default,
|
| 257 |
+
all zeros will be found. The solver looks for a sign change over
|
| 258 |
+
each step, so if multiple zero crossings occur within one step,
|
| 259 |
+
events may be missed. Additionally each `event` function might
|
| 260 |
+
have the following attributes:
|
| 261 |
+
|
| 262 |
+
terminal: bool or int, optional
|
| 263 |
+
When boolean, whether to terminate integration if this event occurs.
|
| 264 |
+
When integral, termination occurs after the specified the number of
|
| 265 |
+
occurrences of this event.
|
| 266 |
+
Implicitly False if not assigned.
|
| 267 |
+
direction: float, optional
|
| 268 |
+
Direction of a zero crossing. If `direction` is positive,
|
| 269 |
+
`event` will only trigger when going from negative to positive,
|
| 270 |
+
and vice versa if `direction` is negative. If 0, then either
|
| 271 |
+
direction will trigger event. Implicitly 0 if not assigned.
|
| 272 |
+
|
| 273 |
+
You can assign attributes like ``event.terminal = True`` to any
|
| 274 |
+
function in Python.
|
| 275 |
+
vectorized : bool, optional
|
| 276 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
| 277 |
+
|
| 278 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 279 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 280 |
+
|
| 281 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 282 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 283 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 284 |
+
the returned array is the time derivative of the state corresponding
|
| 285 |
+
with a column of ``y``).
|
| 286 |
+
|
| 287 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 288 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
| 289 |
+
will result in slower execution for other methods and for 'Radau' and
|
| 290 |
+
'BDF' in some circumstances (e.g. small ``len(y0)``).
|
| 291 |
+
args : tuple, optional
|
| 292 |
+
Additional arguments to pass to the user-defined functions. If given,
|
| 293 |
+
the additional arguments are passed to all user-defined functions.
|
| 294 |
+
So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``,
|
| 295 |
+
then `jac` (if given) and any event functions must have the same
|
| 296 |
+
signature, and `args` must be a tuple of length 3.
|
| 297 |
+
**options
|
| 298 |
+
Options passed to a chosen solver. All options available for already
|
| 299 |
+
implemented solvers are listed below.
|
| 300 |
+
first_step : float or None, optional
|
| 301 |
+
Initial step size. Default is `None` which means that the algorithm
|
| 302 |
+
should choose.
|
| 303 |
+
max_step : float, optional
|
| 304 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 305 |
+
bounded and determined solely by the solver.
|
| 306 |
+
rtol, atol : float or array_like, optional
|
| 307 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 308 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 309 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 310 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 311 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 312 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 313 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 314 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 315 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 316 |
+
than `atol`. If components of y have different scales, it might be
|
| 317 |
+
beneficial to set different `atol` values for different components by
|
| 318 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 319 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 320 |
+
jac : array_like, sparse_matrix, callable or None, optional
|
| 321 |
+
Jacobian matrix of the right-hand side of the system with respect
|
| 322 |
+
to y, required by the 'Radau', 'BDF' and 'LSODA' method. The
|
| 323 |
+
Jacobian matrix has shape (n, n) and its element (i, j) is equal to
|
| 324 |
+
``d f_i / d y_j``. There are three ways to define the Jacobian:
|
| 325 |
+
|
| 326 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
| 327 |
+
be constant. Not supported by 'LSODA'.
|
| 328 |
+
* If callable, the Jacobian is assumed to depend on both
|
| 329 |
+
t and y; it will be called as ``jac(t, y)``, as necessary.
|
| 330 |
+
Additional arguments have to be passed if ``args`` is
|
| 331 |
+
used (see documentation of ``args`` argument).
|
| 332 |
+
For 'Radau' and 'BDF' methods, the return value might be a
|
| 333 |
+
sparse matrix.
|
| 334 |
+
* If None (default), the Jacobian will be approximated by
|
| 335 |
+
finite differences.
|
| 336 |
+
|
| 337 |
+
It is generally recommended to provide the Jacobian rather than
|
| 338 |
+
relying on a finite-difference approximation.
|
| 339 |
+
jac_sparsity : array_like, sparse matrix or None, optional
|
| 340 |
+
Defines a sparsity structure of the Jacobian matrix for a finite-
|
| 341 |
+
difference approximation. Its shape must be (n, n). This argument
|
| 342 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few
|
| 343 |
+
non-zero elements in *each* row, providing the sparsity structure
|
| 344 |
+
will greatly speed up the computations [10]_. A zero entry means that
|
| 345 |
+
a corresponding element in the Jacobian is always zero. If None
|
| 346 |
+
(default), the Jacobian is assumed to be dense.
|
| 347 |
+
Not supported by 'LSODA', see `lband` and `uband` instead.
|
| 348 |
+
lband, uband : int or None, optional
|
| 349 |
+
Parameters defining the bandwidth of the Jacobian for the 'LSODA'
|
| 350 |
+
method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``.
|
| 351 |
+
Default is None. Setting these requires your jac routine to return the
|
| 352 |
+
Jacobian in the packed format: the returned array must have ``n``
|
| 353 |
+
columns and ``uband + lband + 1`` rows in which Jacobian diagonals are
|
| 354 |
+
written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``.
|
| 355 |
+
The same format is used in `scipy.linalg.solve_banded` (check for an
|
| 356 |
+
illustration). These parameters can be also used with ``jac=None`` to
|
| 357 |
+
reduce the number of Jacobian elements estimated by finite differences.
|
| 358 |
+
min_step : float, optional
|
| 359 |
+
The minimum allowed step size for 'LSODA' method.
|
| 360 |
+
By default `min_step` is zero.
|
| 361 |
+
|
| 362 |
+
Returns
|
| 363 |
+
-------
|
| 364 |
+
Bunch object with the following fields defined:
|
| 365 |
+
t : ndarray, shape (n_points,)
|
| 366 |
+
Time points.
|
| 367 |
+
y : ndarray, shape (n, n_points)
|
| 368 |
+
Values of the solution at `t`.
|
| 369 |
+
sol : `OdeSolution` or None
|
| 370 |
+
Found solution as `OdeSolution` instance; None if `dense_output` was
|
| 371 |
+
set to False.
|
| 372 |
+
t_events : list of ndarray or None
|
| 373 |
+
Contains for each event type a list of arrays at which an event of
|
| 374 |
+
that type event was detected. None if `events` was None.
|
| 375 |
+
y_events : list of ndarray or None
|
| 376 |
+
For each value of `t_events`, the corresponding value of the solution.
|
| 377 |
+
None if `events` was None.
|
| 378 |
+
nfev : int
|
| 379 |
+
Number of evaluations of the right-hand side.
|
| 380 |
+
njev : int
|
| 381 |
+
Number of evaluations of the Jacobian.
|
| 382 |
+
nlu : int
|
| 383 |
+
Number of LU decompositions.
|
| 384 |
+
status : int
|
| 385 |
+
Reason for algorithm termination:
|
| 386 |
+
|
| 387 |
+
* -1: Integration step failed.
|
| 388 |
+
* 0: The solver successfully reached the end of `tspan`.
|
| 389 |
+
* 1: A termination event occurred.
|
| 390 |
+
|
| 391 |
+
message : string
|
| 392 |
+
Human-readable description of the termination reason.
|
| 393 |
+
success : bool
|
| 394 |
+
True if the solver reached the interval end or a termination event
|
| 395 |
+
occurred (``status >= 0``).
|
| 396 |
+
|
| 397 |
+
References
|
| 398 |
+
----------
|
| 399 |
+
.. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
|
| 400 |
+
formulae", Journal of Computational and Applied Mathematics, Vol. 6,
|
| 401 |
+
No. 1, pp. 19-26, 1980.
|
| 402 |
+
.. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
|
| 403 |
+
of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
|
| 404 |
+
.. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
|
| 405 |
+
Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
|
| 406 |
+
.. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
|
| 407 |
+
Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
| 408 |
+
.. [5] `Backward Differentiation Formula
|
| 409 |
+
<https://en.wikipedia.org/wiki/Backward_differentiation_formula>`_
|
| 410 |
+
on Wikipedia.
|
| 411 |
+
.. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
|
| 412 |
+
COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
|
| 413 |
+
.. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
|
| 414 |
+
Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
|
| 415 |
+
pp. 55-64, 1983.
|
| 416 |
+
.. [8] L. Petzold, "Automatic selection of methods for solving stiff and
|
| 417 |
+
nonstiff systems of ordinary differential equations", SIAM Journal
|
| 418 |
+
on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
|
| 419 |
+
1983.
|
| 420 |
+
.. [9] `Stiff equation <https://en.wikipedia.org/wiki/Stiff_equation>`_ on
|
| 421 |
+
Wikipedia.
|
| 422 |
+
.. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
| 423 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
| 424 |
+
and its Applications, 13, pp. 117-120, 1974.
|
| 425 |
+
.. [11] `Cauchy-Riemann equations
|
| 426 |
+
<https://en.wikipedia.org/wiki/Cauchy-Riemann_equations>`_ on
|
| 427 |
+
Wikipedia.
|
| 428 |
+
.. [12] `Lotka-Volterra equations
|
| 429 |
+
<https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations>`_
|
| 430 |
+
on Wikipedia.
|
| 431 |
+
.. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
| 432 |
+
Equations I: Nonstiff Problems", Sec. II.
|
| 433 |
+
.. [14] `Page with original Fortran code of DOP853
|
| 434 |
+
<http://www.unige.ch/~hairer/software.html>`_.
|
| 435 |
+
|
| 436 |
+
Examples
|
| 437 |
+
--------
|
| 438 |
+
Basic exponential decay showing automatically chosen time points.
|
| 439 |
+
|
| 440 |
+
>>> import numpy as np
|
| 441 |
+
>>> from scipy.integrate import solve_ivp
|
| 442 |
+
>>> def exponential_decay(t, y): return -0.5 * y
|
| 443 |
+
>>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8])
|
| 444 |
+
>>> print(sol.t)
|
| 445 |
+
[ 0. 0.11487653 1.26364188 3.06061781 4.81611105 6.57445806
|
| 446 |
+
8.33328988 10. ]
|
| 447 |
+
>>> print(sol.y)
|
| 448 |
+
[[2. 1.88836035 1.06327177 0.43319312 0.18017253 0.07483045
|
| 449 |
+
0.03107158 0.01350781]
|
| 450 |
+
[4. 3.7767207 2.12654355 0.86638624 0.36034507 0.14966091
|
| 451 |
+
0.06214316 0.02701561]
|
| 452 |
+
[8. 7.5534414 4.25308709 1.73277247 0.72069014 0.29932181
|
| 453 |
+
0.12428631 0.05403123]]
|
| 454 |
+
|
| 455 |
+
Specifying points where the solution is desired.
|
| 456 |
+
|
| 457 |
+
>>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8],
|
| 458 |
+
... t_eval=[0, 1, 2, 4, 10])
|
| 459 |
+
>>> print(sol.t)
|
| 460 |
+
[ 0 1 2 4 10]
|
| 461 |
+
>>> print(sol.y)
|
| 462 |
+
[[2. 1.21305369 0.73534021 0.27066736 0.01350938]
|
| 463 |
+
[4. 2.42610739 1.47068043 0.54133472 0.02701876]
|
| 464 |
+
[8. 4.85221478 2.94136085 1.08266944 0.05403753]]
|
| 465 |
+
|
| 466 |
+
Cannon fired upward with terminal event upon impact. The ``terminal`` and
|
| 467 |
+
``direction`` fields of an event are applied by monkey patching a function.
|
| 468 |
+
Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts
|
| 469 |
+
at position 0 with velocity +10. Note that the integration never reaches
|
| 470 |
+
t=100 because the event is terminal.
|
| 471 |
+
|
| 472 |
+
>>> def upward_cannon(t, y): return [y[1], -0.5]
|
| 473 |
+
>>> def hit_ground(t, y): return y[0]
|
| 474 |
+
>>> hit_ground.terminal = True
|
| 475 |
+
>>> hit_ground.direction = -1
|
| 476 |
+
>>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground)
|
| 477 |
+
>>> print(sol.t_events)
|
| 478 |
+
[array([40.])]
|
| 479 |
+
>>> print(sol.t)
|
| 480 |
+
[0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
|
| 481 |
+
1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
|
| 482 |
+
|
| 483 |
+
Use `dense_output` and `events` to find position, which is 100, at the apex
|
| 484 |
+
of the cannonball's trajectory. Apex is not defined as terminal, so both
|
| 485 |
+
apex and hit_ground are found. There is no information at t=20, so the sol
|
| 486 |
+
attribute is used to evaluate the solution. The sol attribute is returned
|
| 487 |
+
by setting ``dense_output=True``. Alternatively, the `y_events` attribute
|
| 488 |
+
can be used to access the solution at the time of the event.
|
| 489 |
+
|
| 490 |
+
>>> def apex(t, y): return y[1]
|
| 491 |
+
>>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10],
|
| 492 |
+
... events=(hit_ground, apex), dense_output=True)
|
| 493 |
+
>>> print(sol.t_events)
|
| 494 |
+
[array([40.]), array([20.])]
|
| 495 |
+
>>> print(sol.t)
|
| 496 |
+
[0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
|
| 497 |
+
1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
|
| 498 |
+
>>> print(sol.sol(sol.t_events[1][0]))
|
| 499 |
+
[100. 0.]
|
| 500 |
+
>>> print(sol.y_events)
|
| 501 |
+
[array([[-5.68434189e-14, -1.00000000e+01]]),
|
| 502 |
+
array([[1.00000000e+02, 1.77635684e-15]])]
|
| 503 |
+
|
| 504 |
+
As an example of a system with additional parameters, we'll implement
|
| 505 |
+
the Lotka-Volterra equations [12]_.
|
| 506 |
+
|
| 507 |
+
>>> def lotkavolterra(t, z, a, b, c, d):
|
| 508 |
+
... x, y = z
|
| 509 |
+
... return [a*x - b*x*y, -c*y + d*x*y]
|
| 510 |
+
...
|
| 511 |
+
|
| 512 |
+
We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args`
|
| 513 |
+
argument.
|
| 514 |
+
|
| 515 |
+
>>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
|
| 516 |
+
... dense_output=True)
|
| 517 |
+
|
| 518 |
+
Compute a dense solution and plot it.
|
| 519 |
+
|
| 520 |
+
>>> t = np.linspace(0, 15, 300)
|
| 521 |
+
>>> z = sol.sol(t)
|
| 522 |
+
>>> import matplotlib.pyplot as plt
|
| 523 |
+
>>> plt.plot(t, z.T)
|
| 524 |
+
>>> plt.xlabel('t')
|
| 525 |
+
>>> plt.legend(['x', 'y'], shadow=True)
|
| 526 |
+
>>> plt.title('Lotka-Volterra System')
|
| 527 |
+
>>> plt.show()
|
| 528 |
+
|
| 529 |
+
A couple examples of using solve_ivp to solve the differential
|
| 530 |
+
equation ``y' = Ay`` with complex matrix ``A``.
|
| 531 |
+
|
| 532 |
+
>>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j],
|
| 533 |
+
... [0.25 + 0.58j, -0.2 + 0.14j, 0],
|
| 534 |
+
... [0, 0.2 + 0.4j, -0.1 + 0.97j]])
|
| 535 |
+
|
| 536 |
+
Solving an IVP with ``A`` from above and ``y`` as 3x1 vector:
|
| 537 |
+
|
| 538 |
+
>>> def deriv_vec(t, y):
|
| 539 |
+
... return A @ y
|
| 540 |
+
>>> result = solve_ivp(deriv_vec, [0, 25],
|
| 541 |
+
... np.array([10 + 0j, 20 + 0j, 30 + 0j]),
|
| 542 |
+
... t_eval=np.linspace(0, 25, 101))
|
| 543 |
+
>>> print(result.y[:, 0])
|
| 544 |
+
[10.+0.j 20.+0.j 30.+0.j]
|
| 545 |
+
>>> print(result.y[:, -1])
|
| 546 |
+
[18.46291039+45.25653651j 10.01569306+36.23293216j
|
| 547 |
+
-4.98662741+80.07360388j]
|
| 548 |
+
|
| 549 |
+
Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix :
|
| 550 |
+
|
| 551 |
+
>>> def deriv_mat(t, y):
|
| 552 |
+
... return (A @ y.reshape(3, 3)).flatten()
|
| 553 |
+
>>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j],
|
| 554 |
+
... [5 + 0j, 6 + 0j, 7 + 0j],
|
| 555 |
+
... [9 + 0j, 34 + 0j, 78 + 0j]])
|
| 556 |
+
|
| 557 |
+
>>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(),
|
| 558 |
+
... t_eval=np.linspace(0, 25, 101))
|
| 559 |
+
>>> print(result.y[:, 0].reshape(3, 3))
|
| 560 |
+
[[ 2.+0.j 3.+0.j 4.+0.j]
|
| 561 |
+
[ 5.+0.j 6.+0.j 7.+0.j]
|
| 562 |
+
[ 9.+0.j 34.+0.j 78.+0.j]]
|
| 563 |
+
>>> print(result.y[:, -1].reshape(3, 3))
|
| 564 |
+
[[ 5.67451179 +12.07938445j 17.2888073 +31.03278837j
|
| 565 |
+
37.83405768 +63.25138759j]
|
| 566 |
+
[ 3.39949503 +11.82123994j 21.32530996 +44.88668871j
|
| 567 |
+
53.17531184+103.80400411j]
|
| 568 |
+
[ -2.26105874 +22.19277664j -15.1255713 +70.19616341j
|
| 569 |
+
-38.34616845+153.29039931j]]
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
"""
|
| 573 |
+
if method not in METHODS and not (
|
| 574 |
+
inspect.isclass(method) and issubclass(method, OdeSolver)):
|
| 575 |
+
raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.")
|
| 576 |
+
|
| 577 |
+
t0, tf = map(float, t_span)
|
| 578 |
+
|
| 579 |
+
if args is not None:
|
| 580 |
+
# Wrap the user's fun (and jac, if given) in lambdas to hide the
|
| 581 |
+
# additional parameters. Pass in the original fun as a keyword
|
| 582 |
+
# argument to keep it in the scope of the lambda.
|
| 583 |
+
try:
|
| 584 |
+
_ = [*(args)]
|
| 585 |
+
except TypeError as exp:
|
| 586 |
+
suggestion_tuple = (
|
| 587 |
+
"Supplied 'args' cannot be unpacked. Please supply `args`"
|
| 588 |
+
f" as a tuple (e.g. `args=({args},)`)"
|
| 589 |
+
)
|
| 590 |
+
raise TypeError(suggestion_tuple) from exp
|
| 591 |
+
|
| 592 |
+
def fun(t, x, fun=fun):
|
| 593 |
+
return fun(t, x, *args)
|
| 594 |
+
jac = options.get('jac')
|
| 595 |
+
if callable(jac):
|
| 596 |
+
options['jac'] = lambda t, x: jac(t, x, *args)
|
| 597 |
+
|
| 598 |
+
if t_eval is not None:
|
| 599 |
+
t_eval = np.asarray(t_eval)
|
| 600 |
+
if t_eval.ndim != 1:
|
| 601 |
+
raise ValueError("`t_eval` must be 1-dimensional.")
|
| 602 |
+
|
| 603 |
+
if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)):
|
| 604 |
+
raise ValueError("Values in `t_eval` are not within `t_span`.")
|
| 605 |
+
|
| 606 |
+
d = np.diff(t_eval)
|
| 607 |
+
if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0):
|
| 608 |
+
raise ValueError("Values in `t_eval` are not properly sorted.")
|
| 609 |
+
|
| 610 |
+
if tf > t0:
|
| 611 |
+
t_eval_i = 0
|
| 612 |
+
else:
|
| 613 |
+
# Make order of t_eval decreasing to use np.searchsorted.
|
| 614 |
+
t_eval = t_eval[::-1]
|
| 615 |
+
# This will be an upper bound for slices.
|
| 616 |
+
t_eval_i = t_eval.shape[0]
|
| 617 |
+
|
| 618 |
+
if method in METHODS:
|
| 619 |
+
method = METHODS[method]
|
| 620 |
+
|
| 621 |
+
solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
|
| 622 |
+
|
| 623 |
+
if t_eval is None:
|
| 624 |
+
ts = [t0]
|
| 625 |
+
ys = [y0]
|
| 626 |
+
elif t_eval is not None and dense_output:
|
| 627 |
+
ts = []
|
| 628 |
+
ti = [t0]
|
| 629 |
+
ys = []
|
| 630 |
+
else:
|
| 631 |
+
ts = []
|
| 632 |
+
ys = []
|
| 633 |
+
|
| 634 |
+
interpolants = []
|
| 635 |
+
|
| 636 |
+
if events is not None:
|
| 637 |
+
events, max_events, event_dir = prepare_events(events)
|
| 638 |
+
event_count = np.zeros(len(events))
|
| 639 |
+
if args is not None:
|
| 640 |
+
# Wrap user functions in lambdas to hide the additional parameters.
|
| 641 |
+
# The original event function is passed as a keyword argument to the
|
| 642 |
+
# lambda to keep the original function in scope (i.e., avoid the
|
| 643 |
+
# late binding closure "gotcha").
|
| 644 |
+
events = [lambda t, x, event=event: event(t, x, *args)
|
| 645 |
+
for event in events]
|
| 646 |
+
g = [event(t0, y0) for event in events]
|
| 647 |
+
t_events = [[] for _ in range(len(events))]
|
| 648 |
+
y_events = [[] for _ in range(len(events))]
|
| 649 |
+
else:
|
| 650 |
+
t_events = None
|
| 651 |
+
y_events = None
|
| 652 |
+
|
| 653 |
+
status = None
|
| 654 |
+
while status is None:
|
| 655 |
+
message = solver.step()
|
| 656 |
+
|
| 657 |
+
if solver.status == 'finished':
|
| 658 |
+
status = 0
|
| 659 |
+
elif solver.status == 'failed':
|
| 660 |
+
status = -1
|
| 661 |
+
break
|
| 662 |
+
|
| 663 |
+
t_old = solver.t_old
|
| 664 |
+
t = solver.t
|
| 665 |
+
y = solver.y
|
| 666 |
+
|
| 667 |
+
if dense_output:
|
| 668 |
+
sol = solver.dense_output()
|
| 669 |
+
interpolants.append(sol)
|
| 670 |
+
else:
|
| 671 |
+
sol = None
|
| 672 |
+
|
| 673 |
+
if events is not None:
|
| 674 |
+
g_new = [event(t, y) for event in events]
|
| 675 |
+
active_events = find_active_events(g, g_new, event_dir)
|
| 676 |
+
if active_events.size > 0:
|
| 677 |
+
if sol is None:
|
| 678 |
+
sol = solver.dense_output()
|
| 679 |
+
|
| 680 |
+
event_count[active_events] += 1
|
| 681 |
+
root_indices, roots, terminate = handle_events(
|
| 682 |
+
sol, events, active_events, event_count, max_events,
|
| 683 |
+
t_old, t)
|
| 684 |
+
|
| 685 |
+
for e, te in zip(root_indices, roots):
|
| 686 |
+
t_events[e].append(te)
|
| 687 |
+
y_events[e].append(sol(te))
|
| 688 |
+
|
| 689 |
+
if terminate:
|
| 690 |
+
status = 1
|
| 691 |
+
t = roots[-1]
|
| 692 |
+
y = sol(t)
|
| 693 |
+
|
| 694 |
+
g = g_new
|
| 695 |
+
|
| 696 |
+
if t_eval is None:
|
| 697 |
+
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)
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 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)
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ipy.optimize._numdiff import group_columns
|
| 6 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
| 7 |
+
norm, num_jac, EPS, warn_extraneous,
|
| 8 |
+
validate_first_step)
|
| 9 |
+
from .base import OdeSolver, DenseOutput
|
| 10 |
+
|
| 11 |
+
S6 = 6 ** 0.5
|
| 12 |
+
|
| 13 |
+
# Butcher tableau. A is not used directly, see below.
|
| 14 |
+
C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
|
| 15 |
+
E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
|
| 16 |
+
|
| 17 |
+
# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
|
| 18 |
+
# and a complex conjugate pair. They are written below.
|
| 19 |
+
MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
|
| 20 |
+
MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
|
| 21 |
+
- 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
|
| 22 |
+
|
| 23 |
+
# These are transformation matrices.
|
| 24 |
+
T = np.array([
|
| 25 |
+
[0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
|
| 26 |
+
[0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
|
| 27 |
+
[1, 1, 0]])
|
| 28 |
+
TI = np.array([
|
| 29 |
+
[4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
|
| 30 |
+
[-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
|
| 31 |
+
[0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
|
| 32 |
+
# These linear combinations are used in the algorithm.
|
| 33 |
+
TI_REAL = TI[0]
|
| 34 |
+
TI_COMPLEX = TI[1] + 1j * TI[2]
|
| 35 |
+
|
| 36 |
+
# Interpolator coefficients.
|
| 37 |
+
P = np.array([
|
| 38 |
+
[13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
|
| 39 |
+
[13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
|
| 40 |
+
[1/3, -8/3, 10/3]])
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
NEWTON_MAXITER = 6 # Maximum number of Newton iterations.
|
| 44 |
+
MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
|
| 45 |
+
MAX_FACTOR = 10 # Maximum allowed increase in a step size.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
|
| 49 |
+
LU_real, LU_complex, solve_lu):
|
| 50 |
+
"""Solve the collocation system.
|
| 51 |
+
|
| 52 |
+
Parameters
|
| 53 |
+
----------
|
| 54 |
+
fun : callable
|
| 55 |
+
Right-hand side of the system.
|
| 56 |
+
t : float
|
| 57 |
+
Current time.
|
| 58 |
+
y : ndarray, shape (n,)
|
| 59 |
+
Current state.
|
| 60 |
+
h : float
|
| 61 |
+
Step to try.
|
| 62 |
+
Z0 : ndarray, shape (3, n)
|
| 63 |
+
Initial guess for the solution. It determines new values of `y` at
|
| 64 |
+
``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
|
| 65 |
+
scale : ndarray, shape (n)
|
| 66 |
+
Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
|
| 67 |
+
tol : float
|
| 68 |
+
Tolerance to which solve the system. This value is compared with
|
| 69 |
+
the normalized by `scale` error.
|
| 70 |
+
LU_real, LU_complex
|
| 71 |
+
LU decompositions of the system Jacobians.
|
| 72 |
+
solve_lu : callable
|
| 73 |
+
Callable which solves a linear system given a LU decomposition. The
|
| 74 |
+
signature is ``solve_lu(LU, b)``.
|
| 75 |
+
|
| 76 |
+
Returns
|
| 77 |
+
-------
|
| 78 |
+
converged : bool
|
| 79 |
+
Whether iterations converged.
|
| 80 |
+
n_iter : int
|
| 81 |
+
Number of completed iterations.
|
| 82 |
+
Z : ndarray, shape (3, n)
|
| 83 |
+
Found solution.
|
| 84 |
+
rate : float
|
| 85 |
+
The rate of convergence.
|
| 86 |
+
"""
|
| 87 |
+
n = y.shape[0]
|
| 88 |
+
M_real = MU_REAL / h
|
| 89 |
+
M_complex = MU_COMPLEX / h
|
| 90 |
+
|
| 91 |
+
W = TI.dot(Z0)
|
| 92 |
+
Z = Z0
|
| 93 |
+
|
| 94 |
+
F = np.empty((3, n))
|
| 95 |
+
ch = h * C
|
| 96 |
+
|
| 97 |
+
dW_norm_old = None
|
| 98 |
+
dW = np.empty_like(W)
|
| 99 |
+
converged = False
|
| 100 |
+
rate = None
|
| 101 |
+
for k in range(NEWTON_MAXITER):
|
| 102 |
+
for i in range(3):
|
| 103 |
+
F[i] = fun(t + ch[i], y + Z[i])
|
| 104 |
+
|
| 105 |
+
if not np.all(np.isfinite(F)):
|
| 106 |
+
break
|
| 107 |
+
|
| 108 |
+
f_real = F.T.dot(TI_REAL) - M_real * W[0]
|
| 109 |
+
f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
|
| 110 |
+
|
| 111 |
+
dW_real = solve_lu(LU_real, f_real)
|
| 112 |
+
dW_complex = solve_lu(LU_complex, f_complex)
|
| 113 |
+
|
| 114 |
+
dW[0] = dW_real
|
| 115 |
+
dW[1] = dW_complex.real
|
| 116 |
+
dW[2] = dW_complex.imag
|
| 117 |
+
|
| 118 |
+
dW_norm = norm(dW / scale)
|
| 119 |
+
if dW_norm_old is not None:
|
| 120 |
+
rate = dW_norm / dW_norm_old
|
| 121 |
+
|
| 122 |
+
if (rate is not None and (rate >= 1 or
|
| 123 |
+
rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
|
| 124 |
+
break
|
| 125 |
+
|
| 126 |
+
W += dW
|
| 127 |
+
Z = T.dot(W)
|
| 128 |
+
|
| 129 |
+
if (dW_norm == 0 or
|
| 130 |
+
rate is not None and rate / (1 - rate) * dW_norm < tol):
|
| 131 |
+
converged = True
|
| 132 |
+
break
|
| 133 |
+
|
| 134 |
+
dW_norm_old = dW_norm
|
| 135 |
+
|
| 136 |
+
return converged, k + 1, Z, rate
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
|
| 140 |
+
"""Predict by which factor to increase/decrease the step size.
|
| 141 |
+
|
| 142 |
+
The algorithm is described in [1]_.
|
| 143 |
+
|
| 144 |
+
Parameters
|
| 145 |
+
----------
|
| 146 |
+
h_abs, h_abs_old : float
|
| 147 |
+
Current and previous values of the step size, `h_abs_old` can be None
|
| 148 |
+
(see Notes).
|
| 149 |
+
error_norm, error_norm_old : float
|
| 150 |
+
Current and previous values of the error norm, `error_norm_old` can
|
| 151 |
+
be None (see Notes).
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
factor : float
|
| 156 |
+
Predicted factor.
|
| 157 |
+
|
| 158 |
+
Notes
|
| 159 |
+
-----
|
| 160 |
+
If `h_abs_old` and `error_norm_old` are both not None then a two-step
|
| 161 |
+
algorithm is used, otherwise a one-step algorithm is used.
|
| 162 |
+
|
| 163 |
+
References
|
| 164 |
+
----------
|
| 165 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
| 166 |
+
Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
| 167 |
+
"""
|
| 168 |
+
if error_norm_old is None or h_abs_old is None or error_norm == 0:
|
| 169 |
+
multiplier = 1
|
| 170 |
+
else:
|
| 171 |
+
multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
|
| 172 |
+
|
| 173 |
+
with np.errstate(divide='ignore'):
|
| 174 |
+
factor = min(1, multiplier) * error_norm ** -0.25
|
| 175 |
+
|
| 176 |
+
return factor
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Radau(OdeSolver):
|
| 180 |
+
"""Implicit Runge-Kutta method of Radau IIA family of order 5.
|
| 181 |
+
|
| 182 |
+
The implementation follows [1]_. The error is controlled with a
|
| 183 |
+
third-order accurate embedded formula. A cubic polynomial which satisfies
|
| 184 |
+
the collocation conditions is used for the dense output.
|
| 185 |
+
|
| 186 |
+
Parameters
|
| 187 |
+
----------
|
| 188 |
+
fun : callable
|
| 189 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 190 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 191 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 192 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 193 |
+
information.
|
| 194 |
+
t0 : float
|
| 195 |
+
Initial time.
|
| 196 |
+
y0 : array_like, shape (n,)
|
| 197 |
+
Initial state.
|
| 198 |
+
t_bound : float
|
| 199 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 200 |
+
determines the direction of the integration.
|
| 201 |
+
first_step : float or None, optional
|
| 202 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 203 |
+
should choose.
|
| 204 |
+
max_step : float, optional
|
| 205 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 206 |
+
bounded and determined solely by the solver.
|
| 207 |
+
rtol, atol : float and array_like, optional
|
| 208 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 209 |
+
estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
|
| 210 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 211 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 212 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 213 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 214 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 215 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 216 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 217 |
+
than `atol`. If components of y have different scales, it might be
|
| 218 |
+
beneficial to set different `atol` values for different components by
|
| 219 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 220 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 221 |
+
jac : {None, array_like, sparse_matrix, callable}, optional
|
| 222 |
+
Jacobian matrix of the right-hand side of the system with respect to
|
| 223 |
+
y, required by this method. The Jacobian matrix has shape (n, n) and
|
| 224 |
+
its element (i, j) is equal to ``d f_i / d y_j``.
|
| 225 |
+
There are three ways to define the Jacobian:
|
| 226 |
+
|
| 227 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
| 228 |
+
be constant.
|
| 229 |
+
* If callable, the Jacobian is assumed to depend on both
|
| 230 |
+
t and y; it will be called as ``jac(t, y)`` as necessary.
|
| 231 |
+
For the 'Radau' and 'BDF' methods, the return value might be a
|
| 232 |
+
sparse matrix.
|
| 233 |
+
* If None (default), the Jacobian will be approximated by
|
| 234 |
+
finite differences.
|
| 235 |
+
|
| 236 |
+
It is generally recommended to provide the Jacobian rather than
|
| 237 |
+
relying on a finite-difference approximation.
|
| 238 |
+
jac_sparsity : {None, array_like, sparse matrix}, optional
|
| 239 |
+
Defines a sparsity structure of the Jacobian matrix for a
|
| 240 |
+
finite-difference approximation. Its shape must be (n, n). This argument
|
| 241 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
|
| 242 |
+
elements in *each* row, providing the sparsity structure will greatly
|
| 243 |
+
speed up the computations [2]_. A zero entry means that a corresponding
|
| 244 |
+
element in the Jacobian is always zero. If None (default), the Jacobian
|
| 245 |
+
is assumed to be dense.
|
| 246 |
+
vectorized : bool, optional
|
| 247 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
| 248 |
+
|
| 249 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 250 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 251 |
+
|
| 252 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 253 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 254 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 255 |
+
the returned array is the time derivative of the state corresponding
|
| 256 |
+
with a column of ``y``).
|
| 257 |
+
|
| 258 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 259 |
+
approximation of the Jacobian by this method, but may result in slower
|
| 260 |
+
execution overall in some circumstances (e.g. small ``len(y0)``).
|
| 261 |
+
|
| 262 |
+
Attributes
|
| 263 |
+
----------
|
| 264 |
+
n : int
|
| 265 |
+
Number of equations.
|
| 266 |
+
status : string
|
| 267 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 268 |
+
t_bound : float
|
| 269 |
+
Boundary time.
|
| 270 |
+
direction : float
|
| 271 |
+
Integration direction: +1 or -1.
|
| 272 |
+
t : float
|
| 273 |
+
Current time.
|
| 274 |
+
y : ndarray
|
| 275 |
+
Current state.
|
| 276 |
+
t_old : float
|
| 277 |
+
Previous time. None if no steps were made yet.
|
| 278 |
+
step_size : float
|
| 279 |
+
Size of the last successful step. None if no steps were made yet.
|
| 280 |
+
nfev : int
|
| 281 |
+
Number of evaluations of the right-hand side.
|
| 282 |
+
njev : int
|
| 283 |
+
Number of evaluations of the Jacobian.
|
| 284 |
+
nlu : int
|
| 285 |
+
Number of LU decompositions.
|
| 286 |
+
|
| 287 |
+
References
|
| 288 |
+
----------
|
| 289 |
+
.. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
|
| 290 |
+
Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
| 291 |
+
.. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
| 292 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
| 293 |
+
and its Applications, 13, pp. 117-120, 1974.
|
| 294 |
+
"""
|
| 295 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
| 296 |
+
rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
|
| 297 |
+
vectorized=False, first_step=None, **extraneous):
|
| 298 |
+
warn_extraneous(extraneous)
|
| 299 |
+
super().__init__(fun, t0, y0, t_bound, vectorized)
|
| 300 |
+
self.y_old = None
|
| 301 |
+
self.max_step = validate_max_step(max_step)
|
| 302 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
| 303 |
+
self.f = self.fun(self.t, self.y)
|
| 304 |
+
# Select initial step assuming the same order which is used to control
|
| 305 |
+
# the error.
|
| 306 |
+
if first_step is None:
|
| 307 |
+
self.h_abs = select_initial_step(
|
| 308 |
+
self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
|
| 309 |
+
3, self.rtol, self.atol)
|
| 310 |
+
else:
|
| 311 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
| 312 |
+
self.h_abs_old = None
|
| 313 |
+
self.error_norm_old = None
|
| 314 |
+
|
| 315 |
+
self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
|
| 316 |
+
self.sol = None
|
| 317 |
+
|
| 318 |
+
self.jac_factor = None
|
| 319 |
+
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
|
| 320 |
+
if issparse(self.J):
|
| 321 |
+
def lu(A):
|
| 322 |
+
self.nlu += 1
|
| 323 |
+
return splu(A)
|
| 324 |
+
|
| 325 |
+
def solve_lu(LU, b):
|
| 326 |
+
return LU.solve(b)
|
| 327 |
+
|
| 328 |
+
I = eye(self.n, format='csc')
|
| 329 |
+
else:
|
| 330 |
+
def lu(A):
|
| 331 |
+
self.nlu += 1
|
| 332 |
+
return lu_factor(A, overwrite_a=True)
|
| 333 |
+
|
| 334 |
+
def solve_lu(LU, b):
|
| 335 |
+
return lu_solve(LU, b, overwrite_b=True)
|
| 336 |
+
|
| 337 |
+
I = np.identity(self.n)
|
| 338 |
+
|
| 339 |
+
self.lu = lu
|
| 340 |
+
self.solve_lu = solve_lu
|
| 341 |
+
self.I = I
|
| 342 |
+
|
| 343 |
+
self.current_jac = True
|
| 344 |
+
self.LU_real = None
|
| 345 |
+
self.LU_complex = None
|
| 346 |
+
self.Z = None
|
| 347 |
+
|
| 348 |
+
def _validate_jac(self, jac, sparsity):
|
| 349 |
+
t0 = self.t
|
| 350 |
+
y0 = self.y
|
| 351 |
+
|
| 352 |
+
if jac is None:
|
| 353 |
+
if sparsity is not None:
|
| 354 |
+
if issparse(sparsity):
|
| 355 |
+
sparsity = csc_matrix(sparsity)
|
| 356 |
+
groups = group_columns(sparsity)
|
| 357 |
+
sparsity = (sparsity, groups)
|
| 358 |
+
|
| 359 |
+
def jac_wrapped(t, y, f):
|
| 360 |
+
self.njev += 1
|
| 361 |
+
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
|
| 362 |
+
self.atol, self.jac_factor,
|
| 363 |
+
sparsity)
|
| 364 |
+
return J
|
| 365 |
+
J = jac_wrapped(t0, y0, self.f)
|
| 366 |
+
elif callable(jac):
|
| 367 |
+
J = jac(t0, y0)
|
| 368 |
+
self.njev = 1
|
| 369 |
+
if issparse(J):
|
| 370 |
+
J = csc_matrix(J)
|
| 371 |
+
|
| 372 |
+
def jac_wrapped(t, y, _=None):
|
| 373 |
+
self.njev += 1
|
| 374 |
+
return csc_matrix(jac(t, y), dtype=float)
|
| 375 |
+
|
| 376 |
+
else:
|
| 377 |
+
J = np.asarray(J, dtype=float)
|
| 378 |
+
|
| 379 |
+
def jac_wrapped(t, y, _=None):
|
| 380 |
+
self.njev += 1
|
| 381 |
+
return np.asarray(jac(t, y), dtype=float)
|
| 382 |
+
|
| 383 |
+
if J.shape != (self.n, self.n):
|
| 384 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 385 |
+
f" but actually has {J.shape}.")
|
| 386 |
+
else:
|
| 387 |
+
if issparse(jac):
|
| 388 |
+
J = csc_matrix(jac)
|
| 389 |
+
else:
|
| 390 |
+
J = np.asarray(jac, dtype=float)
|
| 391 |
+
|
| 392 |
+
if J.shape != (self.n, self.n):
|
| 393 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 394 |
+
f" but actually has {J.shape}.")
|
| 395 |
+
jac_wrapped = None
|
| 396 |
+
|
| 397 |
+
return jac_wrapped, J
|
| 398 |
+
|
| 399 |
+
def _step_impl(self):
|
| 400 |
+
t = self.t
|
| 401 |
+
y = self.y
|
| 402 |
+
f = self.f
|
| 403 |
+
|
| 404 |
+
max_step = self.max_step
|
| 405 |
+
atol = self.atol
|
| 406 |
+
rtol = self.rtol
|
| 407 |
+
|
| 408 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
| 409 |
+
if self.h_abs > max_step:
|
| 410 |
+
h_abs = max_step
|
| 411 |
+
h_abs_old = None
|
| 412 |
+
error_norm_old = None
|
| 413 |
+
elif self.h_abs < min_step:
|
| 414 |
+
h_abs = min_step
|
| 415 |
+
h_abs_old = None
|
| 416 |
+
error_norm_old = None
|
| 417 |
+
else:
|
| 418 |
+
h_abs = self.h_abs
|
| 419 |
+
h_abs_old = self.h_abs_old
|
| 420 |
+
error_norm_old = self.error_norm_old
|
| 421 |
+
|
| 422 |
+
J = self.J
|
| 423 |
+
LU_real = self.LU_real
|
| 424 |
+
LU_complex = self.LU_complex
|
| 425 |
+
|
| 426 |
+
current_jac = self.current_jac
|
| 427 |
+
jac = self.jac
|
| 428 |
+
|
| 429 |
+
rejected = False
|
| 430 |
+
step_accepted = False
|
| 431 |
+
message = None
|
| 432 |
+
while not step_accepted:
|
| 433 |
+
if h_abs < min_step:
|
| 434 |
+
return False, self.TOO_SMALL_STEP
|
| 435 |
+
|
| 436 |
+
h = h_abs * self.direction
|
| 437 |
+
t_new = t + h
|
| 438 |
+
|
| 439 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
| 440 |
+
t_new = self.t_bound
|
| 441 |
+
|
| 442 |
+
h = t_new - t
|
| 443 |
+
h_abs = np.abs(h)
|
| 444 |
+
|
| 445 |
+
if self.sol is None:
|
| 446 |
+
Z0 = np.zeros((3, y.shape[0]))
|
| 447 |
+
else:
|
| 448 |
+
Z0 = self.sol(t + h * C).T - y
|
| 449 |
+
|
| 450 |
+
scale = atol + np.abs(y) * rtol
|
| 451 |
+
|
| 452 |
+
converged = False
|
| 453 |
+
while not converged:
|
| 454 |
+
if LU_real is None or LU_complex is None:
|
| 455 |
+
LU_real = self.lu(MU_REAL / h * self.I - J)
|
| 456 |
+
LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
|
| 457 |
+
|
| 458 |
+
converged, n_iter, Z, rate = solve_collocation_system(
|
| 459 |
+
self.fun, t, y, h, Z0, scale, self.newton_tol,
|
| 460 |
+
LU_real, LU_complex, self.solve_lu)
|
| 461 |
+
|
| 462 |
+
if not converged:
|
| 463 |
+
if current_jac:
|
| 464 |
+
break
|
| 465 |
+
|
| 466 |
+
J = self.jac(t, y, f)
|
| 467 |
+
current_jac = True
|
| 468 |
+
LU_real = None
|
| 469 |
+
LU_complex = None
|
| 470 |
+
|
| 471 |
+
if not converged:
|
| 472 |
+
h_abs *= 0.5
|
| 473 |
+
LU_real = None
|
| 474 |
+
LU_complex = None
|
| 475 |
+
continue
|
| 476 |
+
|
| 477 |
+
y_new = y + Z[-1]
|
| 478 |
+
ZE = Z.T.dot(E) / h
|
| 479 |
+
error = self.solve_lu(LU_real, f + ZE)
|
| 480 |
+
scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
|
| 481 |
+
error_norm = norm(error / scale)
|
| 482 |
+
safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
|
| 483 |
+
+ n_iter)
|
| 484 |
+
|
| 485 |
+
if rejected and error_norm > 1:
|
| 486 |
+
error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
|
| 487 |
+
error_norm = norm(error / scale)
|
| 488 |
+
|
| 489 |
+
if error_norm > 1:
|
| 490 |
+
factor = predict_factor(h_abs, h_abs_old,
|
| 491 |
+
error_norm, error_norm_old)
|
| 492 |
+
h_abs *= max(MIN_FACTOR, safety * factor)
|
| 493 |
+
|
| 494 |
+
LU_real = None
|
| 495 |
+
LU_complex = None
|
| 496 |
+
rejected = True
|
| 497 |
+
else:
|
| 498 |
+
step_accepted = True
|
| 499 |
+
|
| 500 |
+
recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
|
| 501 |
+
|
| 502 |
+
factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
|
| 503 |
+
factor = min(MAX_FACTOR, safety * factor)
|
| 504 |
+
|
| 505 |
+
if not recompute_jac and factor < 1.2:
|
| 506 |
+
factor = 1
|
| 507 |
+
else:
|
| 508 |
+
LU_real = None
|
| 509 |
+
LU_complex = None
|
| 510 |
+
|
| 511 |
+
f_new = self.fun(t_new, y_new)
|
| 512 |
+
if recompute_jac:
|
| 513 |
+
J = jac(t_new, y_new, f_new)
|
| 514 |
+
current_jac = True
|
| 515 |
+
elif jac is not None:
|
| 516 |
+
current_jac = False
|
| 517 |
+
|
| 518 |
+
self.h_abs_old = self.h_abs
|
| 519 |
+
self.error_norm_old = error_norm
|
| 520 |
+
|
| 521 |
+
self.h_abs = h_abs * factor
|
| 522 |
+
|
| 523 |
+
self.y_old = y
|
| 524 |
+
|
| 525 |
+
self.t = t_new
|
| 526 |
+
self.y = y_new
|
| 527 |
+
self.f = f_new
|
| 528 |
+
|
| 529 |
+
self.Z = Z
|
| 530 |
+
|
| 531 |
+
self.LU_real = LU_real
|
| 532 |
+
self.LU_complex = LU_complex
|
| 533 |
+
self.current_jac = current_jac
|
| 534 |
+
self.J = J
|
| 535 |
+
|
| 536 |
+
self.t_old = t
|
| 537 |
+
self.sol = self._compute_dense_output()
|
| 538 |
+
|
| 539 |
+
return step_accepted, message
|
| 540 |
+
|
| 541 |
+
def _compute_dense_output(self):
|
| 542 |
+
Q = np.dot(self.Z.T, P)
|
| 543 |
+
return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
|
| 544 |
+
|
| 545 |
+
def _dense_output_impl(self):
|
| 546 |
+
return self.sol
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class RadauDenseOutput(DenseOutput):
|
| 550 |
+
def __init__(self, t_old, t, y_old, Q):
|
| 551 |
+
super().__init__(t_old, t)
|
| 552 |
+
self.h = t - t_old
|
| 553 |
+
self.Q = Q
|
| 554 |
+
self.order = Q.shape[1] - 1
|
| 555 |
+
self.y_old = y_old
|
| 556 |
+
|
| 557 |
+
def _call_impl(self, t):
|
| 558 |
+
x = (t - self.t_old) / self.h
|
| 559 |
+
if t.ndim == 0:
|
| 560 |
+
p = np.tile(x, self.order + 1)
|
| 561 |
+
p = np.cumprod(p)
|
| 562 |
+
else:
|
| 563 |
+
p = np.tile(x, (self.order + 1, 1))
|
| 564 |
+
p = np.cumprod(p, axis=0)
|
| 565 |
+
# Here we don't multiply by h, not a mistake.
|
| 566 |
+
y = np.dot(self.Q, p)
|
| 567 |
+
if y.ndim == 2:
|
| 568 |
+
y += self.y_old[:, None]
|
| 569 |
+
else:
|
| 570 |
+
y += self.y_old
|
| 571 |
+
|
| 572 |
+
return y
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/rk.py
ADDED
|
@@ -0,0 +1,601 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from .base import OdeSolver, DenseOutput
|
| 3 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
| 4 |
+
norm, warn_extraneous, validate_first_step)
|
| 5 |
+
from . import dop853_coefficients
|
| 6 |
+
|
| 7 |
+
# Multiply steps computed from asymptotic behaviour of errors by this.
|
| 8 |
+
SAFETY = 0.9
|
| 9 |
+
|
| 10 |
+
MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
|
| 11 |
+
MAX_FACTOR = 10 # Maximum allowed increase in a step size.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def rk_step(fun, t, y, f, h, A, B, C, K):
|
| 15 |
+
"""Perform a single Runge-Kutta step.
|
| 16 |
+
|
| 17 |
+
This function computes a prediction of an explicit Runge-Kutta method and
|
| 18 |
+
also estimates the error of a less accurate method.
|
| 19 |
+
|
| 20 |
+
Notation for Butcher tableau is as in [1]_.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
fun : callable
|
| 25 |
+
Right-hand side of the system.
|
| 26 |
+
t : float
|
| 27 |
+
Current time.
|
| 28 |
+
y : ndarray, shape (n,)
|
| 29 |
+
Current state.
|
| 30 |
+
f : ndarray, shape (n,)
|
| 31 |
+
Current value of the derivative, i.e., ``fun(x, y)``.
|
| 32 |
+
h : float
|
| 33 |
+
Step to use.
|
| 34 |
+
A : ndarray, shape (n_stages, n_stages)
|
| 35 |
+
Coefficients for combining previous RK stages to compute the next
|
| 36 |
+
stage. For explicit methods the coefficients at and above the main
|
| 37 |
+
diagonal are zeros.
|
| 38 |
+
B : ndarray, shape (n_stages,)
|
| 39 |
+
Coefficients for combining RK stages for computing the final
|
| 40 |
+
prediction.
|
| 41 |
+
C : ndarray, shape (n_stages,)
|
| 42 |
+
Coefficients for incrementing time for consecutive RK stages.
|
| 43 |
+
The value for the first stage is always zero.
|
| 44 |
+
K : ndarray, shape (n_stages + 1, n)
|
| 45 |
+
Storage array for putting RK stages here. Stages are stored in rows.
|
| 46 |
+
The last row is a linear combination of the previous rows with
|
| 47 |
+
coefficients
|
| 48 |
+
|
| 49 |
+
Returns
|
| 50 |
+
-------
|
| 51 |
+
y_new : ndarray, shape (n,)
|
| 52 |
+
Solution at t + h computed with a higher accuracy.
|
| 53 |
+
f_new : ndarray, shape (n,)
|
| 54 |
+
Derivative ``fun(t + h, y_new)``.
|
| 55 |
+
|
| 56 |
+
References
|
| 57 |
+
----------
|
| 58 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
| 59 |
+
Equations I: Nonstiff Problems", Sec. II.4.
|
| 60 |
+
"""
|
| 61 |
+
K[0] = f
|
| 62 |
+
for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):
|
| 63 |
+
dy = np.dot(K[:s].T, a[:s]) * h
|
| 64 |
+
K[s] = fun(t + c * h, y + dy)
|
| 65 |
+
|
| 66 |
+
y_new = y + h * np.dot(K[:-1].T, B)
|
| 67 |
+
f_new = fun(t + h, y_new)
|
| 68 |
+
|
| 69 |
+
K[-1] = f_new
|
| 70 |
+
|
| 71 |
+
return y_new, f_new
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class RungeKutta(OdeSolver):
|
| 75 |
+
"""Base class for explicit Runge-Kutta methods."""
|
| 76 |
+
C: np.ndarray = NotImplemented
|
| 77 |
+
A: np.ndarray = NotImplemented
|
| 78 |
+
B: np.ndarray = NotImplemented
|
| 79 |
+
E: np.ndarray = NotImplemented
|
| 80 |
+
P: np.ndarray = NotImplemented
|
| 81 |
+
order: int = NotImplemented
|
| 82 |
+
error_estimator_order: int = NotImplemented
|
| 83 |
+
n_stages: int = NotImplemented
|
| 84 |
+
|
| 85 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
| 86 |
+
rtol=1e-3, atol=1e-6, vectorized=False,
|
| 87 |
+
first_step=None, **extraneous):
|
| 88 |
+
warn_extraneous(extraneous)
|
| 89 |
+
super().__init__(fun, t0, y0, t_bound, vectorized,
|
| 90 |
+
support_complex=True)
|
| 91 |
+
self.y_old = None
|
| 92 |
+
self.max_step = validate_max_step(max_step)
|
| 93 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
| 94 |
+
self.f = self.fun(self.t, self.y)
|
| 95 |
+
if first_step is None:
|
| 96 |
+
self.h_abs = select_initial_step(
|
| 97 |
+
self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
|
| 98 |
+
self.error_estimator_order, self.rtol, self.atol)
|
| 99 |
+
else:
|
| 100 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
| 101 |
+
self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)
|
| 102 |
+
self.error_exponent = -1 / (self.error_estimator_order + 1)
|
| 103 |
+
self.h_previous = None
|
| 104 |
+
|
| 105 |
+
def _estimate_error(self, K, h):
|
| 106 |
+
return np.dot(K.T, self.E) * h
|
| 107 |
+
|
| 108 |
+
def _estimate_error_norm(self, K, h, scale):
|
| 109 |
+
return norm(self._estimate_error(K, h) / scale)
|
| 110 |
+
|
| 111 |
+
def _step_impl(self):
|
| 112 |
+
t = self.t
|
| 113 |
+
y = self.y
|
| 114 |
+
|
| 115 |
+
max_step = self.max_step
|
| 116 |
+
rtol = self.rtol
|
| 117 |
+
atol = self.atol
|
| 118 |
+
|
| 119 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
| 120 |
+
|
| 121 |
+
if self.h_abs > max_step:
|
| 122 |
+
h_abs = max_step
|
| 123 |
+
elif self.h_abs < min_step:
|
| 124 |
+
h_abs = min_step
|
| 125 |
+
else:
|
| 126 |
+
h_abs = self.h_abs
|
| 127 |
+
|
| 128 |
+
step_accepted = False
|
| 129 |
+
step_rejected = False
|
| 130 |
+
|
| 131 |
+
while not step_accepted:
|
| 132 |
+
if h_abs < min_step:
|
| 133 |
+
return False, self.TOO_SMALL_STEP
|
| 134 |
+
|
| 135 |
+
h = h_abs * self.direction
|
| 136 |
+
t_new = t + h
|
| 137 |
+
|
| 138 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
| 139 |
+
t_new = self.t_bound
|
| 140 |
+
|
| 141 |
+
h = t_new - t
|
| 142 |
+
h_abs = np.abs(h)
|
| 143 |
+
|
| 144 |
+
y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,
|
| 145 |
+
self.B, self.C, self.K)
|
| 146 |
+
scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
|
| 147 |
+
error_norm = self._estimate_error_norm(self.K, h, scale)
|
| 148 |
+
|
| 149 |
+
if error_norm < 1:
|
| 150 |
+
if error_norm == 0:
|
| 151 |
+
factor = MAX_FACTOR
|
| 152 |
+
else:
|
| 153 |
+
factor = min(MAX_FACTOR,
|
| 154 |
+
SAFETY * error_norm ** self.error_exponent)
|
| 155 |
+
|
| 156 |
+
if step_rejected:
|
| 157 |
+
factor = min(1, factor)
|
| 158 |
+
|
| 159 |
+
h_abs *= factor
|
| 160 |
+
|
| 161 |
+
step_accepted = True
|
| 162 |
+
else:
|
| 163 |
+
h_abs *= max(MIN_FACTOR,
|
| 164 |
+
SAFETY * error_norm ** self.error_exponent)
|
| 165 |
+
step_rejected = True
|
| 166 |
+
|
| 167 |
+
self.h_previous = h
|
| 168 |
+
self.y_old = y
|
| 169 |
+
|
| 170 |
+
self.t = t_new
|
| 171 |
+
self.y = y_new
|
| 172 |
+
|
| 173 |
+
self.h_abs = h_abs
|
| 174 |
+
self.f = f_new
|
| 175 |
+
|
| 176 |
+
return True, None
|
| 177 |
+
|
| 178 |
+
def _dense_output_impl(self):
|
| 179 |
+
Q = self.K.T.dot(self.P)
|
| 180 |
+
return RkDenseOutput(self.t_old, self.t, self.y_old, Q)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class RK23(RungeKutta):
|
| 184 |
+
"""Explicit Runge-Kutta method of order 3(2).
|
| 185 |
+
|
| 186 |
+
This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
|
| 187 |
+
assuming accuracy of the second-order method, but steps are taken using the
|
| 188 |
+
third-order accurate formula (local extrapolation is done). A cubic Hermite
|
| 189 |
+
polynomial is used for the dense output.
|
| 190 |
+
|
| 191 |
+
Can be applied in the complex domain.
|
| 192 |
+
|
| 193 |
+
Parameters
|
| 194 |
+
----------
|
| 195 |
+
fun : callable
|
| 196 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 197 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 198 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 199 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 200 |
+
information.
|
| 201 |
+
t0 : float
|
| 202 |
+
Initial time.
|
| 203 |
+
y0 : array_like, shape (n,)
|
| 204 |
+
Initial state.
|
| 205 |
+
t_bound : float
|
| 206 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 207 |
+
determines the direction of the integration.
|
| 208 |
+
first_step : float or None, optional
|
| 209 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 210 |
+
should choose.
|
| 211 |
+
max_step : float, optional
|
| 212 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 213 |
+
bounded and determined solely by the solver.
|
| 214 |
+
rtol, atol : float and array_like, optional
|
| 215 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 216 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 217 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 218 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 219 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 220 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 221 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 222 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 223 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 224 |
+
than `atol`. If components of y have different scales, it might be
|
| 225 |
+
beneficial to set different `atol` values for different components by
|
| 226 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 227 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 228 |
+
vectorized : bool, optional
|
| 229 |
+
Whether `fun` may be called in a vectorized fashion. False (default)
|
| 230 |
+
is recommended for this solver.
|
| 231 |
+
|
| 232 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 233 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 234 |
+
|
| 235 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 236 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 237 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 238 |
+
the returned array is the time derivative of the state corresponding
|
| 239 |
+
with a column of ``y``).
|
| 240 |
+
|
| 241 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 242 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
| 243 |
+
will result in slower execution for this solver.
|
| 244 |
+
|
| 245 |
+
Attributes
|
| 246 |
+
----------
|
| 247 |
+
n : int
|
| 248 |
+
Number of equations.
|
| 249 |
+
status : string
|
| 250 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 251 |
+
t_bound : float
|
| 252 |
+
Boundary time.
|
| 253 |
+
direction : float
|
| 254 |
+
Integration direction: +1 or -1.
|
| 255 |
+
t : float
|
| 256 |
+
Current time.
|
| 257 |
+
y : ndarray
|
| 258 |
+
Current state.
|
| 259 |
+
t_old : float
|
| 260 |
+
Previous time. None if no steps were made yet.
|
| 261 |
+
step_size : float
|
| 262 |
+
Size of the last successful step. None if no steps were made yet.
|
| 263 |
+
nfev : int
|
| 264 |
+
Number evaluations of the system's right-hand side.
|
| 265 |
+
njev : int
|
| 266 |
+
Number of evaluations of the Jacobian.
|
| 267 |
+
Is always 0 for this solver as it does not use the Jacobian.
|
| 268 |
+
nlu : int
|
| 269 |
+
Number of LU decompositions. Is always 0 for this solver.
|
| 270 |
+
|
| 271 |
+
References
|
| 272 |
+
----------
|
| 273 |
+
.. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
|
| 274 |
+
Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
|
| 275 |
+
"""
|
| 276 |
+
order = 3
|
| 277 |
+
error_estimator_order = 2
|
| 278 |
+
n_stages = 3
|
| 279 |
+
C = np.array([0, 1/2, 3/4])
|
| 280 |
+
A = np.array([
|
| 281 |
+
[0, 0, 0],
|
| 282 |
+
[1/2, 0, 0],
|
| 283 |
+
[0, 3/4, 0]
|
| 284 |
+
])
|
| 285 |
+
B = np.array([2/9, 1/3, 4/9])
|
| 286 |
+
E = np.array([5/72, -1/12, -1/9, 1/8])
|
| 287 |
+
P = np.array([[1, -4 / 3, 5 / 9],
|
| 288 |
+
[0, 1, -2/3],
|
| 289 |
+
[0, 4/3, -8/9],
|
| 290 |
+
[0, -1, 1]])
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class RK45(RungeKutta):
|
| 294 |
+
"""Explicit Runge-Kutta method of order 5(4).
|
| 295 |
+
|
| 296 |
+
This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
|
| 297 |
+
assuming accuracy of the fourth-order method accuracy, but steps are taken
|
| 298 |
+
using the fifth-order accurate formula (local extrapolation is done).
|
| 299 |
+
A quartic interpolation polynomial is used for the dense output [2]_.
|
| 300 |
+
|
| 301 |
+
Can be applied in the complex domain.
|
| 302 |
+
|
| 303 |
+
Parameters
|
| 304 |
+
----------
|
| 305 |
+
fun : callable
|
| 306 |
+
Right-hand side of the system. The calling signature is ``fun(t, y)``.
|
| 307 |
+
Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
|
| 308 |
+
It can either have shape (n,); then ``fun`` must return array_like with
|
| 309 |
+
shape (n,). Alternatively it can have shape (n, k); then ``fun``
|
| 310 |
+
must return an array_like with shape (n, k), i.e., each column
|
| 311 |
+
corresponds to a single column in ``y``. The choice between the two
|
| 312 |
+
options is determined by `vectorized` argument (see below).
|
| 313 |
+
t0 : float
|
| 314 |
+
Initial time.
|
| 315 |
+
y0 : array_like, shape (n,)
|
| 316 |
+
Initial state.
|
| 317 |
+
t_bound : float
|
| 318 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 319 |
+
determines the direction of the integration.
|
| 320 |
+
first_step : float or None, optional
|
| 321 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 322 |
+
should choose.
|
| 323 |
+
max_step : float, optional
|
| 324 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 325 |
+
bounded and determined solely by the solver.
|
| 326 |
+
rtol, atol : float and array_like, optional
|
| 327 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 328 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 329 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 330 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 331 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 332 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 333 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 334 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 335 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 336 |
+
than `atol`. If components of y have different scales, it might be
|
| 337 |
+
beneficial to set different `atol` values for different components by
|
| 338 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 339 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 340 |
+
vectorized : bool, optional
|
| 341 |
+
Whether `fun` is implemented in a vectorized fashion. Default is False.
|
| 342 |
+
|
| 343 |
+
Attributes
|
| 344 |
+
----------
|
| 345 |
+
n : int
|
| 346 |
+
Number of equations.
|
| 347 |
+
status : string
|
| 348 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 349 |
+
t_bound : float
|
| 350 |
+
Boundary time.
|
| 351 |
+
direction : float
|
| 352 |
+
Integration direction: +1 or -1.
|
| 353 |
+
t : float
|
| 354 |
+
Current time.
|
| 355 |
+
y : ndarray
|
| 356 |
+
Current state.
|
| 357 |
+
t_old : float
|
| 358 |
+
Previous time. None if no steps were made yet.
|
| 359 |
+
step_size : float
|
| 360 |
+
Size of the last successful step. None if no steps were made yet.
|
| 361 |
+
nfev : int
|
| 362 |
+
Number evaluations of the system's right-hand side.
|
| 363 |
+
njev : int
|
| 364 |
+
Number of evaluations of the Jacobian.
|
| 365 |
+
Is always 0 for this solver as it does not use the Jacobian.
|
| 366 |
+
nlu : int
|
| 367 |
+
Number of LU decompositions. Is always 0 for this solver.
|
| 368 |
+
|
| 369 |
+
References
|
| 370 |
+
----------
|
| 371 |
+
.. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
|
| 372 |
+
formulae", Journal of Computational and Applied Mathematics, Vol. 6,
|
| 373 |
+
No. 1, pp. 19-26, 1980.
|
| 374 |
+
.. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
|
| 375 |
+
of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
|
| 376 |
+
"""
|
| 377 |
+
order = 5
|
| 378 |
+
error_estimator_order = 4
|
| 379 |
+
n_stages = 6
|
| 380 |
+
C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])
|
| 381 |
+
A = np.array([
|
| 382 |
+
[0, 0, 0, 0, 0],
|
| 383 |
+
[1/5, 0, 0, 0, 0],
|
| 384 |
+
[3/40, 9/40, 0, 0, 0],
|
| 385 |
+
[44/45, -56/15, 32/9, 0, 0],
|
| 386 |
+
[19372/6561, -25360/2187, 64448/6561, -212/729, 0],
|
| 387 |
+
[9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]
|
| 388 |
+
])
|
| 389 |
+
B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])
|
| 390 |
+
E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,
|
| 391 |
+
1/40])
|
| 392 |
+
# Corresponds to the optimum value of c_6 from [2]_.
|
| 393 |
+
P = np.array([
|
| 394 |
+
[1, -8048581381/2820520608, 8663915743/2820520608,
|
| 395 |
+
-12715105075/11282082432],
|
| 396 |
+
[0, 0, 0, 0],
|
| 397 |
+
[0, 131558114200/32700410799, -68118460800/10900136933,
|
| 398 |
+
87487479700/32700410799],
|
| 399 |
+
[0, -1754552775/470086768, 14199869525/1410260304,
|
| 400 |
+
-10690763975/1880347072],
|
| 401 |
+
[0, 127303824393/49829197408, -318862633887/49829197408,
|
| 402 |
+
701980252875 / 199316789632],
|
| 403 |
+
[0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],
|
| 404 |
+
[0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
class DOP853(RungeKutta):
|
| 408 |
+
"""Explicit Runge-Kutta method of order 8.
|
| 409 |
+
|
| 410 |
+
This is a Python implementation of "DOP853" algorithm originally written
|
| 411 |
+
in Fortran [1]_, [2]_. Note that this is not a literal translation, but
|
| 412 |
+
the algorithmic core and coefficients are the same.
|
| 413 |
+
|
| 414 |
+
Can be applied in the complex domain.
|
| 415 |
+
|
| 416 |
+
Parameters
|
| 417 |
+
----------
|
| 418 |
+
fun : callable
|
| 419 |
+
Right-hand side of the system. The calling signature is ``fun(t, y)``.
|
| 420 |
+
Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:
|
| 421 |
+
It can either have shape (n,); then ``fun`` must return array_like with
|
| 422 |
+
shape (n,). Alternatively it can have shape (n, k); then ``fun``
|
| 423 |
+
must return an array_like with shape (n, k), i.e. each column
|
| 424 |
+
corresponds to a single column in ``y``. The choice between the two
|
| 425 |
+
options is determined by `vectorized` argument (see below).
|
| 426 |
+
t0 : float
|
| 427 |
+
Initial time.
|
| 428 |
+
y0 : array_like, shape (n,)
|
| 429 |
+
Initial state.
|
| 430 |
+
t_bound : float
|
| 431 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 432 |
+
determines the direction of the integration.
|
| 433 |
+
first_step : float or None, optional
|
| 434 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 435 |
+
should choose.
|
| 436 |
+
max_step : float, optional
|
| 437 |
+
Maximum allowed step size. Default is np.inf, i.e. the step size is not
|
| 438 |
+
bounded and determined solely by the solver.
|
| 439 |
+
rtol, atol : float and array_like, optional
|
| 440 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 441 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 442 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 443 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 444 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 445 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 446 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 447 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 448 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 449 |
+
than `atol`. If components of y have different scales, it might be
|
| 450 |
+
beneficial to set different `atol` values for different components by
|
| 451 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 452 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 453 |
+
vectorized : bool, optional
|
| 454 |
+
Whether `fun` is implemented in a vectorized fashion. Default is False.
|
| 455 |
+
|
| 456 |
+
Attributes
|
| 457 |
+
----------
|
| 458 |
+
n : int
|
| 459 |
+
Number of equations.
|
| 460 |
+
status : string
|
| 461 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 462 |
+
t_bound : float
|
| 463 |
+
Boundary time.
|
| 464 |
+
direction : float
|
| 465 |
+
Integration direction: +1 or -1.
|
| 466 |
+
t : float
|
| 467 |
+
Current time.
|
| 468 |
+
y : ndarray
|
| 469 |
+
Current state.
|
| 470 |
+
t_old : float
|
| 471 |
+
Previous time. None if no steps were made yet.
|
| 472 |
+
step_size : float
|
| 473 |
+
Size of the last successful step. None if no steps were made yet.
|
| 474 |
+
nfev : int
|
| 475 |
+
Number evaluations of the system's right-hand side.
|
| 476 |
+
njev : int
|
| 477 |
+
Number of evaluations of the Jacobian. Is always 0 for this solver
|
| 478 |
+
as it does not use the Jacobian.
|
| 479 |
+
nlu : int
|
| 480 |
+
Number of LU decompositions. Is always 0 for this solver.
|
| 481 |
+
|
| 482 |
+
References
|
| 483 |
+
----------
|
| 484 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
| 485 |
+
Equations I: Nonstiff Problems", Sec. II.
|
| 486 |
+
.. [2] `Page with original Fortran code of DOP853
|
| 487 |
+
<http://www.unige.ch/~hairer/software.html>`_.
|
| 488 |
+
"""
|
| 489 |
+
n_stages = dop853_coefficients.N_STAGES
|
| 490 |
+
order = 8
|
| 491 |
+
error_estimator_order = 7
|
| 492 |
+
A = dop853_coefficients.A[:n_stages, :n_stages]
|
| 493 |
+
B = dop853_coefficients.B
|
| 494 |
+
C = dop853_coefficients.C[:n_stages]
|
| 495 |
+
E3 = dop853_coefficients.E3
|
| 496 |
+
E5 = dop853_coefficients.E5
|
| 497 |
+
D = dop853_coefficients.D
|
| 498 |
+
|
| 499 |
+
A_EXTRA = dop853_coefficients.A[n_stages + 1:]
|
| 500 |
+
C_EXTRA = dop853_coefficients.C[n_stages + 1:]
|
| 501 |
+
|
| 502 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
| 503 |
+
rtol=1e-3, atol=1e-6, vectorized=False,
|
| 504 |
+
first_step=None, **extraneous):
|
| 505 |
+
super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol,
|
| 506 |
+
vectorized, first_step, **extraneous)
|
| 507 |
+
self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,
|
| 508 |
+
self.n), dtype=self.y.dtype)
|
| 509 |
+
self.K = self.K_extended[:self.n_stages + 1]
|
| 510 |
+
|
| 511 |
+
def _estimate_error(self, K, h): # Left for testing purposes.
|
| 512 |
+
err5 = np.dot(K.T, self.E5)
|
| 513 |
+
err3 = np.dot(K.T, self.E3)
|
| 514 |
+
denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))
|
| 515 |
+
correction_factor = np.ones_like(err5)
|
| 516 |
+
mask = denom > 0
|
| 517 |
+
correction_factor[mask] = np.abs(err5[mask]) / denom[mask]
|
| 518 |
+
return h * err5 * correction_factor
|
| 519 |
+
|
| 520 |
+
def _estimate_error_norm(self, K, h, scale):
|
| 521 |
+
err5 = np.dot(K.T, self.E5) / scale
|
| 522 |
+
err3 = np.dot(K.T, self.E3) / scale
|
| 523 |
+
err5_norm_2 = np.linalg.norm(err5)**2
|
| 524 |
+
err3_norm_2 = np.linalg.norm(err3)**2
|
| 525 |
+
if err5_norm_2 == 0 and err3_norm_2 == 0:
|
| 526 |
+
return 0.0
|
| 527 |
+
denom = err5_norm_2 + 0.01 * err3_norm_2
|
| 528 |
+
return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
|
| 529 |
+
|
| 530 |
+
def _dense_output_impl(self):
|
| 531 |
+
K = self.K_extended
|
| 532 |
+
h = self.h_previous
|
| 533 |
+
for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),
|
| 534 |
+
start=self.n_stages + 1):
|
| 535 |
+
dy = np.dot(K[:s].T, a[:s]) * h
|
| 536 |
+
K[s] = self.fun(self.t_old + c * h, self.y_old + dy)
|
| 537 |
+
|
| 538 |
+
F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),
|
| 539 |
+
dtype=self.y_old.dtype)
|
| 540 |
+
|
| 541 |
+
f_old = K[0]
|
| 542 |
+
delta_y = self.y - self.y_old
|
| 543 |
+
|
| 544 |
+
F[0] = delta_y
|
| 545 |
+
F[1] = h * f_old - delta_y
|
| 546 |
+
F[2] = 2 * delta_y - h * (self.f + f_old)
|
| 547 |
+
F[3:] = h * np.dot(self.D, K)
|
| 548 |
+
|
| 549 |
+
return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
class RkDenseOutput(DenseOutput):
|
| 553 |
+
def __init__(self, t_old, t, y_old, Q):
|
| 554 |
+
super().__init__(t_old, t)
|
| 555 |
+
self.h = t - t_old
|
| 556 |
+
self.Q = Q
|
| 557 |
+
self.order = Q.shape[1] - 1
|
| 558 |
+
self.y_old = y_old
|
| 559 |
+
|
| 560 |
+
def _call_impl(self, t):
|
| 561 |
+
x = (t - self.t_old) / self.h
|
| 562 |
+
if t.ndim == 0:
|
| 563 |
+
p = np.tile(x, self.order + 1)
|
| 564 |
+
p = np.cumprod(p)
|
| 565 |
+
else:
|
| 566 |
+
p = np.tile(x, (self.order + 1, 1))
|
| 567 |
+
p = np.cumprod(p, axis=0)
|
| 568 |
+
y = self.h * np.dot(self.Q, p)
|
| 569 |
+
if y.ndim == 2:
|
| 570 |
+
y += self.y_old[:, None]
|
| 571 |
+
else:
|
| 572 |
+
y += self.y_old
|
| 573 |
+
|
| 574 |
+
return y
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
class Dop853DenseOutput(DenseOutput):
|
| 578 |
+
def __init__(self, t_old, t, y_old, F):
|
| 579 |
+
super().__init__(t_old, t)
|
| 580 |
+
self.h = t - t_old
|
| 581 |
+
self.F = F
|
| 582 |
+
self.y_old = y_old
|
| 583 |
+
|
| 584 |
+
def _call_impl(self, t):
|
| 585 |
+
x = (t - self.t_old) / self.h
|
| 586 |
+
|
| 587 |
+
if t.ndim == 0:
|
| 588 |
+
y = np.zeros_like(self.y_old)
|
| 589 |
+
else:
|
| 590 |
+
x = x[:, None]
|
| 591 |
+
y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)
|
| 592 |
+
|
| 593 |
+
for i, f in enumerate(reversed(self.F)):
|
| 594 |
+
y += f
|
| 595 |
+
if i % 2 == 0:
|
| 596 |
+
y *= x
|
| 597 |
+
else:
|
| 598 |
+
y *= 1 - x
|
| 599 |
+
y += self.y_old
|
| 600 |
+
|
| 601 |
+
return y.T
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py
ADDED
|
File without changes
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (185 Bytes). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_ivp.cpython-310.pyc
ADDED
|
Binary file (33.3 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__pycache__/test_rk.cpython-310.pyc
ADDED
|
Binary file (1.91 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
ADDED
|
@@ -0,0 +1,1268 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
import pytest
|
| 5 |
+
from pytest import raises as assert_raises
|
| 6 |
+
import numpy as np
|
| 7 |
+
from scipy.optimize._numdiff import group_columns
|
| 8 |
+
from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
|
| 9 |
+
from scipy.integrate import OdeSolution
|
| 10 |
+
from scipy.integrate._ivp.common import num_jac, select_initial_step
|
| 11 |
+
from scipy.integrate._ivp.base import ConstantDenseOutput
|
| 12 |
+
from scipy.sparse import coo_matrix, csc_matrix
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def fun_zero(t, y):
|
| 16 |
+
return np.zeros_like(y)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def fun_linear(t, y):
|
| 20 |
+
return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def jac_linear():
|
| 24 |
+
return np.array([[-1, -5], [1, 1]])
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def sol_linear(t):
|
| 28 |
+
return np.vstack((-5 * np.sin(2 * t),
|
| 29 |
+
2 * np.cos(2 * t) + np.sin(2 * t)))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def fun_rational(t, y):
|
| 33 |
+
return np.array([y[1] / t,
|
| 34 |
+
y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def fun_rational_vectorized(t, y):
|
| 38 |
+
return np.vstack((y[1] / t,
|
| 39 |
+
y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def jac_rational(t, y):
|
| 43 |
+
return np.array([
|
| 44 |
+
[0, 1 / t],
|
| 45 |
+
[-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
|
| 46 |
+
(y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
|
| 47 |
+
])
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def jac_rational_sparse(t, y):
|
| 51 |
+
return csc_matrix([
|
| 52 |
+
[0, 1 / t],
|
| 53 |
+
[-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
|
| 54 |
+
(y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
|
| 55 |
+
])
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def sol_rational(t):
|
| 59 |
+
return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def fun_medazko(t, y):
|
| 63 |
+
n = y.shape[0] // 2
|
| 64 |
+
k = 100
|
| 65 |
+
c = 4
|
| 66 |
+
|
| 67 |
+
phi = 2 if t <= 5 else 0
|
| 68 |
+
y = np.hstack((phi, 0, y, y[-2]))
|
| 69 |
+
|
| 70 |
+
d = 1 / n
|
| 71 |
+
j = np.arange(n) + 1
|
| 72 |
+
alpha = 2 * (j * d - 1) ** 3 / c ** 2
|
| 73 |
+
beta = (j * d - 1) ** 4 / c ** 2
|
| 74 |
+
|
| 75 |
+
j_2_p1 = 2 * j + 2
|
| 76 |
+
j_2_m3 = 2 * j - 2
|
| 77 |
+
j_2_m1 = 2 * j
|
| 78 |
+
j_2 = 2 * j + 1
|
| 79 |
+
|
| 80 |
+
f = np.empty(2 * n)
|
| 81 |
+
f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
|
| 82 |
+
beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
|
| 83 |
+
k * y[j_2_m1] * y[j_2])
|
| 84 |
+
f[1::2] = -k * y[j_2] * y[j_2_m1]
|
| 85 |
+
|
| 86 |
+
return f
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def medazko_sparsity(n):
|
| 90 |
+
cols = []
|
| 91 |
+
rows = []
|
| 92 |
+
|
| 93 |
+
i = np.arange(n) * 2
|
| 94 |
+
|
| 95 |
+
cols.append(i[1:])
|
| 96 |
+
rows.append(i[1:] - 2)
|
| 97 |
+
|
| 98 |
+
cols.append(i)
|
| 99 |
+
rows.append(i)
|
| 100 |
+
|
| 101 |
+
cols.append(i)
|
| 102 |
+
rows.append(i + 1)
|
| 103 |
+
|
| 104 |
+
cols.append(i[:-1])
|
| 105 |
+
rows.append(i[:-1] + 2)
|
| 106 |
+
|
| 107 |
+
i = np.arange(n) * 2 + 1
|
| 108 |
+
|
| 109 |
+
cols.append(i)
|
| 110 |
+
rows.append(i)
|
| 111 |
+
|
| 112 |
+
cols.append(i)
|
| 113 |
+
rows.append(i - 1)
|
| 114 |
+
|
| 115 |
+
cols = np.hstack(cols)
|
| 116 |
+
rows = np.hstack(rows)
|
| 117 |
+
|
| 118 |
+
return coo_matrix((np.ones_like(cols), (cols, rows)))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def fun_complex(t, y):
|
| 122 |
+
return -y
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def jac_complex(t, y):
|
| 126 |
+
return -np.eye(y.shape[0])
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def jac_complex_sparse(t, y):
|
| 130 |
+
return csc_matrix(jac_complex(t, y))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def sol_complex(t):
|
| 134 |
+
y = (0.5 + 1j) * np.exp(-t)
|
| 135 |
+
return y.reshape((1, -1))
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def fun_event_dense_output_LSODA(t, y):
|
| 139 |
+
return y * (t - 2)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def jac_event_dense_output_LSODA(t, y):
|
| 143 |
+
return t - 2
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def sol_event_dense_output_LSODA(t):
|
| 147 |
+
return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def compute_error(y, y_true, rtol, atol):
|
| 151 |
+
e = (y - y_true) / (atol + rtol * np.abs(y_true))
|
| 152 |
+
return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@pytest.mark.thread_unsafe
|
| 156 |
+
def test_integration():
|
| 157 |
+
rtol = 1e-3
|
| 158 |
+
atol = 1e-6
|
| 159 |
+
y0 = [1/3, 2/9]
|
| 160 |
+
|
| 161 |
+
for vectorized, method, t_span, jac in product(
|
| 162 |
+
[False, True],
|
| 163 |
+
['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
|
| 164 |
+
[[5, 9], [5, 1]],
|
| 165 |
+
[None, jac_rational, jac_rational_sparse]):
|
| 166 |
+
|
| 167 |
+
if vectorized:
|
| 168 |
+
fun = fun_rational_vectorized
|
| 169 |
+
else:
|
| 170 |
+
fun = fun_rational
|
| 171 |
+
|
| 172 |
+
with suppress_warnings() as sup:
|
| 173 |
+
sup.filter(UserWarning,
|
| 174 |
+
"The following arguments have no effect for a chosen "
|
| 175 |
+
"solver: `jac`")
|
| 176 |
+
res = solve_ivp(fun, t_span, y0, rtol=rtol,
|
| 177 |
+
atol=atol, method=method, dense_output=True,
|
| 178 |
+
jac=jac, vectorized=vectorized)
|
| 179 |
+
assert_equal(res.t[0], t_span[0])
|
| 180 |
+
assert_(res.t_events is None)
|
| 181 |
+
assert_(res.y_events is None)
|
| 182 |
+
assert_(res.success)
|
| 183 |
+
assert_equal(res.status, 0)
|
| 184 |
+
|
| 185 |
+
if method == 'DOP853':
|
| 186 |
+
# DOP853 spends more functions evaluation because it doesn't
|
| 187 |
+
# have enough time to develop big enough step size.
|
| 188 |
+
assert_(res.nfev < 50)
|
| 189 |
+
else:
|
| 190 |
+
assert_(res.nfev < 40)
|
| 191 |
+
|
| 192 |
+
if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
|
| 193 |
+
assert_equal(res.njev, 0)
|
| 194 |
+
assert_equal(res.nlu, 0)
|
| 195 |
+
else:
|
| 196 |
+
assert_(0 < res.njev < 3)
|
| 197 |
+
assert_(0 < res.nlu < 10)
|
| 198 |
+
|
| 199 |
+
y_true = sol_rational(res.t)
|
| 200 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 201 |
+
assert_(np.all(e < 5))
|
| 202 |
+
|
| 203 |
+
tc = np.linspace(*t_span)
|
| 204 |
+
yc_true = sol_rational(tc)
|
| 205 |
+
yc = res.sol(tc)
|
| 206 |
+
|
| 207 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 208 |
+
assert_(np.all(e < 5))
|
| 209 |
+
|
| 210 |
+
tc = (t_span[0] + t_span[-1]) / 2
|
| 211 |
+
yc_true = sol_rational(tc)
|
| 212 |
+
yc = res.sol(tc)
|
| 213 |
+
|
| 214 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 215 |
+
assert_(np.all(e < 5))
|
| 216 |
+
|
| 217 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
@pytest.mark.thread_unsafe
|
| 221 |
+
def test_integration_complex():
|
| 222 |
+
rtol = 1e-3
|
| 223 |
+
atol = 1e-6
|
| 224 |
+
y0 = [0.5 + 1j]
|
| 225 |
+
t_span = [0, 1]
|
| 226 |
+
tc = np.linspace(t_span[0], t_span[1])
|
| 227 |
+
for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
|
| 228 |
+
[None, jac_complex, jac_complex_sparse]):
|
| 229 |
+
with suppress_warnings() as sup:
|
| 230 |
+
sup.filter(UserWarning,
|
| 231 |
+
"The following arguments have no effect for a chosen "
|
| 232 |
+
"solver: `jac`")
|
| 233 |
+
res = solve_ivp(fun_complex, t_span, y0, method=method,
|
| 234 |
+
dense_output=True, rtol=rtol, atol=atol, jac=jac)
|
| 235 |
+
|
| 236 |
+
assert_equal(res.t[0], t_span[0])
|
| 237 |
+
assert_(res.t_events is None)
|
| 238 |
+
assert_(res.y_events is None)
|
| 239 |
+
assert_(res.success)
|
| 240 |
+
assert_equal(res.status, 0)
|
| 241 |
+
|
| 242 |
+
if method == 'DOP853':
|
| 243 |
+
assert res.nfev < 35
|
| 244 |
+
else:
|
| 245 |
+
assert res.nfev < 25
|
| 246 |
+
|
| 247 |
+
if method == 'BDF':
|
| 248 |
+
assert_equal(res.njev, 1)
|
| 249 |
+
assert res.nlu < 6
|
| 250 |
+
else:
|
| 251 |
+
assert res.njev == 0
|
| 252 |
+
assert res.nlu == 0
|
| 253 |
+
|
| 254 |
+
y_true = sol_complex(res.t)
|
| 255 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 256 |
+
assert np.all(e < 5)
|
| 257 |
+
|
| 258 |
+
yc_true = sol_complex(tc)
|
| 259 |
+
yc = res.sol(tc)
|
| 260 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 261 |
+
|
| 262 |
+
assert np.all(e < 5)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@pytest.mark.fail_slow(5)
|
| 266 |
+
def test_integration_sparse_difference():
|
| 267 |
+
n = 200
|
| 268 |
+
t_span = [0, 20]
|
| 269 |
+
y0 = np.zeros(2 * n)
|
| 270 |
+
y0[1::2] = 1
|
| 271 |
+
sparsity = medazko_sparsity(n)
|
| 272 |
+
|
| 273 |
+
for method in ['BDF', 'Radau']:
|
| 274 |
+
res = solve_ivp(fun_medazko, t_span, y0, method=method,
|
| 275 |
+
jac_sparsity=sparsity)
|
| 276 |
+
|
| 277 |
+
assert_equal(res.t[0], t_span[0])
|
| 278 |
+
assert_(res.t_events is None)
|
| 279 |
+
assert_(res.y_events is None)
|
| 280 |
+
assert_(res.success)
|
| 281 |
+
assert_equal(res.status, 0)
|
| 282 |
+
|
| 283 |
+
assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
|
| 284 |
+
assert_allclose(res.y[79, -1], 0, atol=1e-3)
|
| 285 |
+
assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
|
| 286 |
+
assert_allclose(res.y[149, -1], 0, atol=1e-3)
|
| 287 |
+
assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
|
| 288 |
+
assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
|
| 289 |
+
assert_allclose(res.y[238, -1], 0, atol=1e-3)
|
| 290 |
+
assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def test_integration_const_jac():
|
| 294 |
+
rtol = 1e-3
|
| 295 |
+
atol = 1e-6
|
| 296 |
+
y0 = [0, 2]
|
| 297 |
+
t_span = [0, 2]
|
| 298 |
+
J = jac_linear()
|
| 299 |
+
J_sparse = csc_matrix(J)
|
| 300 |
+
|
| 301 |
+
for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
|
| 302 |
+
res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
|
| 303 |
+
method=method, dense_output=True, jac=jac)
|
| 304 |
+
assert_equal(res.t[0], t_span[0])
|
| 305 |
+
assert_(res.t_events is None)
|
| 306 |
+
assert_(res.y_events is None)
|
| 307 |
+
assert_(res.success)
|
| 308 |
+
assert_equal(res.status, 0)
|
| 309 |
+
|
| 310 |
+
assert_(res.nfev < 100)
|
| 311 |
+
assert_equal(res.njev, 0)
|
| 312 |
+
assert_(0 < res.nlu < 15)
|
| 313 |
+
|
| 314 |
+
y_true = sol_linear(res.t)
|
| 315 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 316 |
+
assert_(np.all(e < 10))
|
| 317 |
+
|
| 318 |
+
tc = np.linspace(*t_span)
|
| 319 |
+
yc_true = sol_linear(tc)
|
| 320 |
+
yc = res.sol(tc)
|
| 321 |
+
|
| 322 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 323 |
+
assert_(np.all(e < 15))
|
| 324 |
+
|
| 325 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@pytest.mark.slow
|
| 329 |
+
@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
|
| 330 |
+
def test_integration_stiff(method, num_parallel_threads):
|
| 331 |
+
rtol = 1e-6
|
| 332 |
+
atol = 1e-6
|
| 333 |
+
y0 = [1e4, 0, 0]
|
| 334 |
+
tspan = [0, 1e8]
|
| 335 |
+
|
| 336 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 337 |
+
pytest.skip(reason='LSODA does not allow for concurrent calls')
|
| 338 |
+
|
| 339 |
+
def fun_robertson(t, state):
|
| 340 |
+
x, y, z = state
|
| 341 |
+
return [
|
| 342 |
+
-0.04 * x + 1e4 * y * z,
|
| 343 |
+
0.04 * x - 1e4 * y * z - 3e7 * y * y,
|
| 344 |
+
3e7 * y * y,
|
| 345 |
+
]
|
| 346 |
+
|
| 347 |
+
res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
|
| 348 |
+
atol=atol, method=method)
|
| 349 |
+
|
| 350 |
+
# If the stiff mode is not activated correctly, these numbers will be much bigger
|
| 351 |
+
assert res.nfev < 5000
|
| 352 |
+
assert res.njev < 200
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def test_events(num_parallel_threads):
|
| 356 |
+
def event_rational_1(t, y):
|
| 357 |
+
return y[0] - y[1] ** 0.7
|
| 358 |
+
|
| 359 |
+
def event_rational_2(t, y):
|
| 360 |
+
return y[1] ** 0.6 - y[0]
|
| 361 |
+
|
| 362 |
+
def event_rational_3(t, y):
|
| 363 |
+
return t - 7.4
|
| 364 |
+
|
| 365 |
+
event_rational_3.terminal = True
|
| 366 |
+
|
| 367 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 368 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 369 |
+
continue
|
| 370 |
+
|
| 371 |
+
res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
|
| 372 |
+
events=(event_rational_1, event_rational_2))
|
| 373 |
+
assert_equal(res.status, 0)
|
| 374 |
+
assert_equal(res.t_events[0].size, 1)
|
| 375 |
+
assert_equal(res.t_events[1].size, 1)
|
| 376 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 377 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 378 |
+
|
| 379 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 380 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 381 |
+
assert np.isclose(
|
| 382 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 383 |
+
assert np.isclose(
|
| 384 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 385 |
+
|
| 386 |
+
event_rational_1.direction = 1
|
| 387 |
+
event_rational_2.direction = 1
|
| 388 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 389 |
+
events=(event_rational_1, event_rational_2))
|
| 390 |
+
assert_equal(res.status, 0)
|
| 391 |
+
assert_equal(res.t_events[0].size, 1)
|
| 392 |
+
assert_equal(res.t_events[1].size, 0)
|
| 393 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 394 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 395 |
+
assert_equal(res.y_events[1].shape, (0,))
|
| 396 |
+
assert np.isclose(
|
| 397 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 398 |
+
|
| 399 |
+
event_rational_1.direction = -1
|
| 400 |
+
event_rational_2.direction = -1
|
| 401 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 402 |
+
events=(event_rational_1, event_rational_2))
|
| 403 |
+
assert_equal(res.status, 0)
|
| 404 |
+
assert_equal(res.t_events[0].size, 0)
|
| 405 |
+
assert_equal(res.t_events[1].size, 1)
|
| 406 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 407 |
+
assert_equal(res.y_events[0].shape, (0,))
|
| 408 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 409 |
+
assert np.isclose(
|
| 410 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 411 |
+
|
| 412 |
+
event_rational_1.direction = 0
|
| 413 |
+
event_rational_2.direction = 0
|
| 414 |
+
|
| 415 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 416 |
+
events=(event_rational_1, event_rational_2,
|
| 417 |
+
event_rational_3), dense_output=True)
|
| 418 |
+
assert_equal(res.status, 1)
|
| 419 |
+
assert_equal(res.t_events[0].size, 1)
|
| 420 |
+
assert_equal(res.t_events[1].size, 0)
|
| 421 |
+
assert_equal(res.t_events[2].size, 1)
|
| 422 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 423 |
+
assert_(7.3 < res.t_events[2][0] < 7.5)
|
| 424 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 425 |
+
assert_equal(res.y_events[1].shape, (0,))
|
| 426 |
+
assert_equal(res.y_events[2].shape, (1, 2))
|
| 427 |
+
assert np.isclose(
|
| 428 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 429 |
+
assert np.isclose(
|
| 430 |
+
event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
|
| 431 |
+
|
| 432 |
+
res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
|
| 433 |
+
events=event_rational_1, dense_output=True)
|
| 434 |
+
assert_equal(res.status, 0)
|
| 435 |
+
assert_equal(res.t_events[0].size, 1)
|
| 436 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 437 |
+
|
| 438 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 439 |
+
assert np.isclose(
|
| 440 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 441 |
+
|
| 442 |
+
# Also test that termination by event doesn't break interpolants.
|
| 443 |
+
tc = np.linspace(res.t[0], res.t[-1])
|
| 444 |
+
yc_true = sol_rational(tc)
|
| 445 |
+
yc = res.sol(tc)
|
| 446 |
+
e = compute_error(yc, yc_true, 1e-3, 1e-6)
|
| 447 |
+
assert_(np.all(e < 5))
|
| 448 |
+
|
| 449 |
+
# Test that the y_event matches solution
|
| 450 |
+
assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
|
| 451 |
+
rtol=1e-3, atol=1e-6)
|
| 452 |
+
|
| 453 |
+
# Test in backward direction.
|
| 454 |
+
event_rational_1.direction = 0
|
| 455 |
+
event_rational_2.direction = 0
|
| 456 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 457 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 458 |
+
continue
|
| 459 |
+
|
| 460 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 461 |
+
events=(event_rational_1, event_rational_2))
|
| 462 |
+
assert_equal(res.status, 0)
|
| 463 |
+
assert_equal(res.t_events[0].size, 1)
|
| 464 |
+
assert_equal(res.t_events[1].size, 1)
|
| 465 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 466 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 467 |
+
|
| 468 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 469 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 470 |
+
assert np.isclose(
|
| 471 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 472 |
+
assert np.isclose(
|
| 473 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 474 |
+
|
| 475 |
+
event_rational_1.direction = -1
|
| 476 |
+
event_rational_2.direction = -1
|
| 477 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 478 |
+
events=(event_rational_1, event_rational_2))
|
| 479 |
+
assert_equal(res.status, 0)
|
| 480 |
+
assert_equal(res.t_events[0].size, 1)
|
| 481 |
+
assert_equal(res.t_events[1].size, 0)
|
| 482 |
+
assert_(5.3 < res.t_events[0][0] < 5.7)
|
| 483 |
+
|
| 484 |
+
assert_equal(res.y_events[0].shape, (1, 2))
|
| 485 |
+
assert_equal(res.y_events[1].shape, (0,))
|
| 486 |
+
assert np.isclose(
|
| 487 |
+
event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
|
| 488 |
+
|
| 489 |
+
event_rational_1.direction = 1
|
| 490 |
+
event_rational_2.direction = 1
|
| 491 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 492 |
+
events=(event_rational_1, event_rational_2))
|
| 493 |
+
assert_equal(res.status, 0)
|
| 494 |
+
assert_equal(res.t_events[0].size, 0)
|
| 495 |
+
assert_equal(res.t_events[1].size, 1)
|
| 496 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 497 |
+
|
| 498 |
+
assert_equal(res.y_events[0].shape, (0,))
|
| 499 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 500 |
+
assert np.isclose(
|
| 501 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 502 |
+
|
| 503 |
+
event_rational_1.direction = 0
|
| 504 |
+
event_rational_2.direction = 0
|
| 505 |
+
|
| 506 |
+
res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
|
| 507 |
+
events=(event_rational_1, event_rational_2,
|
| 508 |
+
event_rational_3), dense_output=True)
|
| 509 |
+
assert_equal(res.status, 1)
|
| 510 |
+
assert_equal(res.t_events[0].size, 0)
|
| 511 |
+
assert_equal(res.t_events[1].size, 1)
|
| 512 |
+
assert_equal(res.t_events[2].size, 1)
|
| 513 |
+
assert_(7.3 < res.t_events[1][0] < 7.7)
|
| 514 |
+
assert_(7.3 < res.t_events[2][0] < 7.5)
|
| 515 |
+
|
| 516 |
+
assert_equal(res.y_events[0].shape, (0,))
|
| 517 |
+
assert_equal(res.y_events[1].shape, (1, 2))
|
| 518 |
+
assert_equal(res.y_events[2].shape, (1, 2))
|
| 519 |
+
assert np.isclose(
|
| 520 |
+
event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
|
| 521 |
+
assert np.isclose(
|
| 522 |
+
event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
|
| 523 |
+
|
| 524 |
+
# Also test that termination by event doesn't break interpolants.
|
| 525 |
+
tc = np.linspace(res.t[-1], res.t[0])
|
| 526 |
+
yc_true = sol_rational(tc)
|
| 527 |
+
yc = res.sol(tc)
|
| 528 |
+
e = compute_error(yc, yc_true, 1e-3, 1e-6)
|
| 529 |
+
assert_(np.all(e < 5))
|
| 530 |
+
|
| 531 |
+
assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
|
| 532 |
+
rtol=1e-3, atol=1e-6)
|
| 533 |
+
assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
|
| 534 |
+
rtol=1e-3, atol=1e-6)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _get_harmonic_oscillator():
|
| 538 |
+
def f(t, y):
|
| 539 |
+
return [y[1], -y[0]]
|
| 540 |
+
|
| 541 |
+
def event(t, y):
|
| 542 |
+
return y[0]
|
| 543 |
+
|
| 544 |
+
return f, event
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
@pytest.mark.parametrize('n_events', [3, 4])
|
| 548 |
+
def test_event_terminal_integer(n_events):
|
| 549 |
+
f, event = _get_harmonic_oscillator()
|
| 550 |
+
event.terminal = n_events
|
| 551 |
+
res = solve_ivp(f, (0, 100), [1, 0], events=event)
|
| 552 |
+
assert len(res.t_events[0]) == n_events
|
| 553 |
+
assert len(res.y_events[0]) == n_events
|
| 554 |
+
assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def test_event_terminal_iv():
|
| 558 |
+
f, event = _get_harmonic_oscillator()
|
| 559 |
+
args = (f, (0, 100), [1, 0])
|
| 560 |
+
|
| 561 |
+
event.terminal = None
|
| 562 |
+
res = solve_ivp(*args, events=event)
|
| 563 |
+
event.terminal = 0
|
| 564 |
+
ref = solve_ivp(*args, events=event)
|
| 565 |
+
assert_allclose(res.t_events, ref.t_events)
|
| 566 |
+
|
| 567 |
+
message = "The `terminal` attribute..."
|
| 568 |
+
event.terminal = -1
|
| 569 |
+
with pytest.raises(ValueError, match=message):
|
| 570 |
+
solve_ivp(*args, events=event)
|
| 571 |
+
event.terminal = 3.5
|
| 572 |
+
with pytest.raises(ValueError, match=message):
|
| 573 |
+
solve_ivp(*args, events=event)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def test_max_step(num_parallel_threads):
|
| 577 |
+
rtol = 1e-3
|
| 578 |
+
atol = 1e-6
|
| 579 |
+
y0 = [1/3, 2/9]
|
| 580 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 581 |
+
if method is LSODA and num_parallel_threads > 1:
|
| 582 |
+
continue
|
| 583 |
+
for t_span in ([5, 9], [5, 1]):
|
| 584 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
|
| 585 |
+
max_step=0.5, atol=atol, method=method,
|
| 586 |
+
dense_output=True)
|
| 587 |
+
assert_equal(res.t[0], t_span[0])
|
| 588 |
+
assert_equal(res.t[-1], t_span[-1])
|
| 589 |
+
assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
|
| 590 |
+
assert_(res.t_events is None)
|
| 591 |
+
assert_(res.success)
|
| 592 |
+
assert_equal(res.status, 0)
|
| 593 |
+
|
| 594 |
+
y_true = sol_rational(res.t)
|
| 595 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 596 |
+
assert_(np.all(e < 5))
|
| 597 |
+
|
| 598 |
+
tc = np.linspace(*t_span)
|
| 599 |
+
yc_true = sol_rational(tc)
|
| 600 |
+
yc = res.sol(tc)
|
| 601 |
+
|
| 602 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 603 |
+
assert_(np.all(e < 5))
|
| 604 |
+
|
| 605 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 606 |
+
|
| 607 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
| 608 |
+
t_span[1], max_step=-1)
|
| 609 |
+
|
| 610 |
+
if method is not LSODA:
|
| 611 |
+
solver = method(fun_rational, t_span[0], y0, t_span[1],
|
| 612 |
+
rtol=rtol, atol=atol, max_step=1e-20)
|
| 613 |
+
message = solver.step()
|
| 614 |
+
message = solver.step() # First step succeeds but second step fails.
|
| 615 |
+
assert_equal(solver.status, 'failed')
|
| 616 |
+
assert_("step size is less" in message)
|
| 617 |
+
assert_raises(RuntimeError, solver.step)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def test_first_step(num_parallel_threads):
|
| 621 |
+
rtol = 1e-3
|
| 622 |
+
atol = 1e-6
|
| 623 |
+
y0 = [1/3, 2/9]
|
| 624 |
+
first_step = 0.1
|
| 625 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 626 |
+
if method is LSODA and num_parallel_threads > 1:
|
| 627 |
+
continue
|
| 628 |
+
for t_span in ([5, 9], [5, 1]):
|
| 629 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
|
| 630 |
+
max_step=0.5, atol=atol, method=method,
|
| 631 |
+
dense_output=True, first_step=first_step)
|
| 632 |
+
|
| 633 |
+
assert_equal(res.t[0], t_span[0])
|
| 634 |
+
assert_equal(res.t[-1], t_span[-1])
|
| 635 |
+
assert_allclose(first_step, np.abs(res.t[1] - 5))
|
| 636 |
+
assert_(res.t_events is None)
|
| 637 |
+
assert_(res.success)
|
| 638 |
+
assert_equal(res.status, 0)
|
| 639 |
+
|
| 640 |
+
y_true = sol_rational(res.t)
|
| 641 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 642 |
+
assert_(np.all(e < 5))
|
| 643 |
+
|
| 644 |
+
tc = np.linspace(*t_span)
|
| 645 |
+
yc_true = sol_rational(tc)
|
| 646 |
+
yc = res.sol(tc)
|
| 647 |
+
|
| 648 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 649 |
+
assert_(np.all(e < 5))
|
| 650 |
+
|
| 651 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 652 |
+
|
| 653 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
| 654 |
+
t_span[1], first_step=-1)
|
| 655 |
+
assert_raises(ValueError, method, fun_rational, t_span[0], y0,
|
| 656 |
+
t_span[1], first_step=5)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def test_t_eval():
|
| 660 |
+
rtol = 1e-3
|
| 661 |
+
atol = 1e-6
|
| 662 |
+
y0 = [1/3, 2/9]
|
| 663 |
+
for t_span in ([5, 9], [5, 1]):
|
| 664 |
+
t_eval = np.linspace(t_span[0], t_span[1], 10)
|
| 665 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 666 |
+
t_eval=t_eval)
|
| 667 |
+
assert_equal(res.t, t_eval)
|
| 668 |
+
assert_(res.t_events is None)
|
| 669 |
+
assert_(res.success)
|
| 670 |
+
assert_equal(res.status, 0)
|
| 671 |
+
|
| 672 |
+
y_true = sol_rational(res.t)
|
| 673 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 674 |
+
assert_(np.all(e < 5))
|
| 675 |
+
|
| 676 |
+
t_eval = [5, 5.01, 7, 8, 8.01, 9]
|
| 677 |
+
res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
|
| 678 |
+
t_eval=t_eval)
|
| 679 |
+
assert_equal(res.t, t_eval)
|
| 680 |
+
assert_(res.t_events is None)
|
| 681 |
+
assert_(res.success)
|
| 682 |
+
assert_equal(res.status, 0)
|
| 683 |
+
|
| 684 |
+
y_true = sol_rational(res.t)
|
| 685 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 686 |
+
assert_(np.all(e < 5))
|
| 687 |
+
|
| 688 |
+
t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
|
| 689 |
+
res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
|
| 690 |
+
t_eval=t_eval)
|
| 691 |
+
assert_equal(res.t, t_eval)
|
| 692 |
+
assert_(res.t_events is None)
|
| 693 |
+
assert_(res.success)
|
| 694 |
+
assert_equal(res.status, 0)
|
| 695 |
+
|
| 696 |
+
t_eval = [5.01, 7, 8, 8.01]
|
| 697 |
+
res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
|
| 698 |
+
t_eval=t_eval)
|
| 699 |
+
assert_equal(res.t, t_eval)
|
| 700 |
+
assert_(res.t_events is None)
|
| 701 |
+
assert_(res.success)
|
| 702 |
+
assert_equal(res.status, 0)
|
| 703 |
+
|
| 704 |
+
y_true = sol_rational(res.t)
|
| 705 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 706 |
+
assert_(np.all(e < 5))
|
| 707 |
+
|
| 708 |
+
t_eval = [4.99, 3, 1.5, 1.1, 1.01]
|
| 709 |
+
res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
|
| 710 |
+
t_eval=t_eval)
|
| 711 |
+
assert_equal(res.t, t_eval)
|
| 712 |
+
assert_(res.t_events is None)
|
| 713 |
+
assert_(res.success)
|
| 714 |
+
assert_equal(res.status, 0)
|
| 715 |
+
|
| 716 |
+
t_eval = [4, 6]
|
| 717 |
+
assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
|
| 718 |
+
rtol=rtol, atol=atol, t_eval=t_eval)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def test_t_eval_dense_output():
|
| 722 |
+
rtol = 1e-3
|
| 723 |
+
atol = 1e-6
|
| 724 |
+
y0 = [1/3, 2/9]
|
| 725 |
+
t_span = [5, 9]
|
| 726 |
+
t_eval = np.linspace(t_span[0], t_span[1], 10)
|
| 727 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 728 |
+
t_eval=t_eval)
|
| 729 |
+
res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 730 |
+
t_eval=t_eval, dense_output=True)
|
| 731 |
+
assert_equal(res.t, t_eval)
|
| 732 |
+
assert_(res.t_events is None)
|
| 733 |
+
assert_(res.success)
|
| 734 |
+
assert_equal(res.status, 0)
|
| 735 |
+
|
| 736 |
+
assert_equal(res.t, res_d.t)
|
| 737 |
+
assert_equal(res.y, res_d.y)
|
| 738 |
+
assert_(res_d.t_events is None)
|
| 739 |
+
assert_(res_d.success)
|
| 740 |
+
assert_equal(res_d.status, 0)
|
| 741 |
+
|
| 742 |
+
# if t and y are equal only test values for one case
|
| 743 |
+
y_true = sol_rational(res.t)
|
| 744 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 745 |
+
assert_(np.all(e < 5))
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
@pytest.mark.thread_unsafe
|
| 749 |
+
def test_t_eval_early_event():
|
| 750 |
+
def early_event(t, y):
|
| 751 |
+
return t - 7
|
| 752 |
+
|
| 753 |
+
early_event.terminal = True
|
| 754 |
+
|
| 755 |
+
rtol = 1e-3
|
| 756 |
+
atol = 1e-6
|
| 757 |
+
y0 = [1/3, 2/9]
|
| 758 |
+
t_span = [5, 9]
|
| 759 |
+
t_eval = np.linspace(7.5, 9, 16)
|
| 760 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 761 |
+
with suppress_warnings() as sup:
|
| 762 |
+
sup.filter(UserWarning,
|
| 763 |
+
"The following arguments have no effect for a chosen "
|
| 764 |
+
"solver: `jac`")
|
| 765 |
+
res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
|
| 766 |
+
method=method, t_eval=t_eval, events=early_event,
|
| 767 |
+
jac=jac_rational)
|
| 768 |
+
assert res.success
|
| 769 |
+
assert res.message == 'A termination event occurred.'
|
| 770 |
+
assert res.status == 1
|
| 771 |
+
assert not res.t and not res.y
|
| 772 |
+
assert len(res.t_events) == 1
|
| 773 |
+
assert res.t_events[0].size == 1
|
| 774 |
+
assert res.t_events[0][0] == 7
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def test_event_dense_output_LSODA(num_parallel_threads):
|
| 778 |
+
if num_parallel_threads > 1:
|
| 779 |
+
pytest.skip('LSODA does not allow for concurrent execution')
|
| 780 |
+
|
| 781 |
+
def event_lsoda(t, y):
|
| 782 |
+
return y[0] - 2.02e-5
|
| 783 |
+
|
| 784 |
+
rtol = 1e-3
|
| 785 |
+
atol = 1e-6
|
| 786 |
+
y0 = [0.05]
|
| 787 |
+
t_span = [-2, 2]
|
| 788 |
+
first_step = 1e-3
|
| 789 |
+
res = solve_ivp(
|
| 790 |
+
fun_event_dense_output_LSODA,
|
| 791 |
+
t_span,
|
| 792 |
+
y0,
|
| 793 |
+
method="LSODA",
|
| 794 |
+
dense_output=True,
|
| 795 |
+
events=event_lsoda,
|
| 796 |
+
first_step=first_step,
|
| 797 |
+
max_step=1,
|
| 798 |
+
rtol=rtol,
|
| 799 |
+
atol=atol,
|
| 800 |
+
jac=jac_event_dense_output_LSODA,
|
| 801 |
+
)
|
| 802 |
+
|
| 803 |
+
assert_equal(res.t[0], t_span[0])
|
| 804 |
+
assert_equal(res.t[-1], t_span[-1])
|
| 805 |
+
assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
|
| 806 |
+
assert res.success
|
| 807 |
+
assert_equal(res.status, 0)
|
| 808 |
+
|
| 809 |
+
y_true = sol_event_dense_output_LSODA(res.t)
|
| 810 |
+
e = compute_error(res.y, y_true, rtol, atol)
|
| 811 |
+
assert_array_less(e, 5)
|
| 812 |
+
|
| 813 |
+
tc = np.linspace(*t_span)
|
| 814 |
+
yc_true = sol_event_dense_output_LSODA(tc)
|
| 815 |
+
yc = res.sol(tc)
|
| 816 |
+
e = compute_error(yc, yc_true, rtol, atol)
|
| 817 |
+
assert_array_less(e, 5)
|
| 818 |
+
|
| 819 |
+
assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
def test_no_integration():
|
| 823 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 824 |
+
sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
|
| 825 |
+
method=method, dense_output=True)
|
| 826 |
+
assert_equal(sol.sol(4), [2, 3])
|
| 827 |
+
assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
|
| 828 |
+
|
| 829 |
+
|
| 830 |
+
def test_no_integration_class():
|
| 831 |
+
for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 832 |
+
solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
|
| 833 |
+
solver.step()
|
| 834 |
+
assert_equal(solver.status, 'finished')
|
| 835 |
+
sol = solver.dense_output()
|
| 836 |
+
assert_equal(sol(0.0), [10.0, 0.0])
|
| 837 |
+
assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
|
| 838 |
+
|
| 839 |
+
solver = method(lambda t, y: -y, 0.0, [], np.inf)
|
| 840 |
+
solver.step()
|
| 841 |
+
assert_equal(solver.status, 'finished')
|
| 842 |
+
sol = solver.dense_output()
|
| 843 |
+
assert_equal(sol(100.0), [])
|
| 844 |
+
assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
def test_empty():
|
| 848 |
+
def fun(t, y):
|
| 849 |
+
return np.zeros((0,))
|
| 850 |
+
|
| 851 |
+
y0 = np.zeros((0,))
|
| 852 |
+
|
| 853 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 854 |
+
sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
|
| 855 |
+
method=method, dense_output=True)
|
| 856 |
+
assert_equal(sol.sol(10), np.zeros((0,)))
|
| 857 |
+
assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
|
| 858 |
+
|
| 859 |
+
for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
|
| 860 |
+
sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
|
| 861 |
+
method=method, dense_output=True)
|
| 862 |
+
assert_equal(sol.sol(10), np.zeros((0,)))
|
| 863 |
+
assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
def test_ConstantDenseOutput():
|
| 867 |
+
sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
|
| 868 |
+
assert_allclose(sol(1.5), [1, 2])
|
| 869 |
+
assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
|
| 870 |
+
|
| 871 |
+
sol = ConstantDenseOutput(0, 1, np.array([]))
|
| 872 |
+
assert_allclose(sol(1.5), np.empty(0))
|
| 873 |
+
assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
def test_classes():
|
| 877 |
+
y0 = [1 / 3, 2 / 9]
|
| 878 |
+
for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
|
| 879 |
+
solver = cls(fun_rational, 5, y0, np.inf)
|
| 880 |
+
assert_equal(solver.n, 2)
|
| 881 |
+
assert_equal(solver.status, 'running')
|
| 882 |
+
assert_equal(solver.t_bound, np.inf)
|
| 883 |
+
assert_equal(solver.direction, 1)
|
| 884 |
+
assert_equal(solver.t, 5)
|
| 885 |
+
assert_equal(solver.y, y0)
|
| 886 |
+
assert_(solver.step_size is None)
|
| 887 |
+
if cls is not LSODA:
|
| 888 |
+
assert_(solver.nfev > 0)
|
| 889 |
+
assert_(solver.njev >= 0)
|
| 890 |
+
assert_equal(solver.nlu, 0)
|
| 891 |
+
else:
|
| 892 |
+
assert_equal(solver.nfev, 0)
|
| 893 |
+
assert_equal(solver.njev, 0)
|
| 894 |
+
assert_equal(solver.nlu, 0)
|
| 895 |
+
|
| 896 |
+
assert_raises(RuntimeError, solver.dense_output)
|
| 897 |
+
|
| 898 |
+
message = solver.step()
|
| 899 |
+
assert_equal(solver.status, 'running')
|
| 900 |
+
assert_equal(message, None)
|
| 901 |
+
assert_equal(solver.n, 2)
|
| 902 |
+
assert_equal(solver.t_bound, np.inf)
|
| 903 |
+
assert_equal(solver.direction, 1)
|
| 904 |
+
assert_(solver.t > 5)
|
| 905 |
+
assert_(not np.all(np.equal(solver.y, y0)))
|
| 906 |
+
assert_(solver.step_size > 0)
|
| 907 |
+
assert_(solver.nfev > 0)
|
| 908 |
+
assert_(solver.njev >= 0)
|
| 909 |
+
assert_(solver.nlu >= 0)
|
| 910 |
+
sol = solver.dense_output()
|
| 911 |
+
assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
|
| 912 |
+
|
| 913 |
+
|
| 914 |
+
def test_OdeSolution():
|
| 915 |
+
ts = np.array([0, 2, 5], dtype=float)
|
| 916 |
+
s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
|
| 917 |
+
s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
|
| 918 |
+
|
| 919 |
+
sol = OdeSolution(ts, [s1, s2])
|
| 920 |
+
|
| 921 |
+
assert_equal(sol(-1), [-1])
|
| 922 |
+
assert_equal(sol(1), [-1])
|
| 923 |
+
assert_equal(sol(2), [-1])
|
| 924 |
+
assert_equal(sol(3), [1])
|
| 925 |
+
assert_equal(sol(5), [1])
|
| 926 |
+
assert_equal(sol(6), [1])
|
| 927 |
+
|
| 928 |
+
assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
|
| 929 |
+
np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
|
| 930 |
+
|
| 931 |
+
ts = np.array([10, 4, -3])
|
| 932 |
+
s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
|
| 933 |
+
s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
|
| 934 |
+
|
| 935 |
+
sol = OdeSolution(ts, [s1, s2])
|
| 936 |
+
assert_equal(sol(11), [-1])
|
| 937 |
+
assert_equal(sol(10), [-1])
|
| 938 |
+
assert_equal(sol(5), [-1])
|
| 939 |
+
assert_equal(sol(4), [-1])
|
| 940 |
+
assert_equal(sol(0), [1])
|
| 941 |
+
assert_equal(sol(-3), [1])
|
| 942 |
+
assert_equal(sol(-4), [1])
|
| 943 |
+
|
| 944 |
+
assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
|
| 945 |
+
np.array([[-1, 1, -1, 1, -1, 1, -1]]))
|
| 946 |
+
|
| 947 |
+
ts = np.array([1, 1])
|
| 948 |
+
s = ConstantDenseOutput(1, 1, np.array([10]))
|
| 949 |
+
sol = OdeSolution(ts, [s])
|
| 950 |
+
assert_equal(sol(0), [10])
|
| 951 |
+
assert_equal(sol(1), [10])
|
| 952 |
+
assert_equal(sol(2), [10])
|
| 953 |
+
|
| 954 |
+
assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def test_num_jac():
|
| 958 |
+
def fun(t, y):
|
| 959 |
+
return np.vstack([
|
| 960 |
+
-0.04 * y[0] + 1e4 * y[1] * y[2],
|
| 961 |
+
0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
|
| 962 |
+
3e7 * y[1] ** 2
|
| 963 |
+
])
|
| 964 |
+
|
| 965 |
+
def jac(t, y):
|
| 966 |
+
return np.array([
|
| 967 |
+
[-0.04, 1e4 * y[2], 1e4 * y[1]],
|
| 968 |
+
[0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
|
| 969 |
+
[0, 6e7 * y[1], 0]
|
| 970 |
+
])
|
| 971 |
+
|
| 972 |
+
t = 1
|
| 973 |
+
y = np.array([1, 0, 0])
|
| 974 |
+
J_true = jac(t, y)
|
| 975 |
+
threshold = 1e-5
|
| 976 |
+
f = fun(t, y).ravel()
|
| 977 |
+
|
| 978 |
+
J_num, factor = num_jac(fun, t, y, f, threshold, None)
|
| 979 |
+
assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
|
| 980 |
+
|
| 981 |
+
J_num, factor = num_jac(fun, t, y, f, threshold, factor)
|
| 982 |
+
assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
|
| 983 |
+
|
| 984 |
+
|
| 985 |
+
def test_num_jac_sparse():
|
| 986 |
+
def fun(t, y):
|
| 987 |
+
e = y[1:]**3 - y[:-1]**2
|
| 988 |
+
z = np.zeros(y.shape[1])
|
| 989 |
+
return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
|
| 990 |
+
|
| 991 |
+
def structure(n):
|
| 992 |
+
A = np.zeros((n, n), dtype=int)
|
| 993 |
+
A[0, 0] = 1
|
| 994 |
+
A[0, 1] = 1
|
| 995 |
+
for i in range(1, n - 1):
|
| 996 |
+
A[i, i - 1: i + 2] = 1
|
| 997 |
+
A[-1, -1] = 1
|
| 998 |
+
A[-1, -2] = 1
|
| 999 |
+
|
| 1000 |
+
return A
|
| 1001 |
+
|
| 1002 |
+
np.random.seed(0)
|
| 1003 |
+
n = 20
|
| 1004 |
+
y = np.random.randn(n)
|
| 1005 |
+
A = structure(n)
|
| 1006 |
+
groups = group_columns(A)
|
| 1007 |
+
|
| 1008 |
+
f = fun(0, y[:, None]).ravel()
|
| 1009 |
+
|
| 1010 |
+
# Compare dense and sparse results, assuming that dense implementation
|
| 1011 |
+
# is correct (as it is straightforward).
|
| 1012 |
+
J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
|
| 1013 |
+
sparsity=(A, groups))
|
| 1014 |
+
J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
|
| 1015 |
+
assert_allclose(J_num_dense, J_num_sparse.toarray(),
|
| 1016 |
+
rtol=1e-12, atol=1e-14)
|
| 1017 |
+
assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
|
| 1018 |
+
|
| 1019 |
+
# Take small factors to trigger their recomputing inside.
|
| 1020 |
+
factor = np.random.uniform(0, 1e-12, size=n)
|
| 1021 |
+
J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
|
| 1022 |
+
sparsity=(A, groups))
|
| 1023 |
+
J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
|
| 1024 |
+
|
| 1025 |
+
assert_allclose(J_num_dense, J_num_sparse.toarray(),
|
| 1026 |
+
rtol=1e-12, atol=1e-14)
|
| 1027 |
+
assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
def test_args():
|
| 1031 |
+
|
| 1032 |
+
# sys3 is actually two decoupled systems. (x, y) form a
|
| 1033 |
+
# linear oscillator, while z is a nonlinear first order
|
| 1034 |
+
# system with equilibria at z=0 and z=1. If k > 0, z=1
|
| 1035 |
+
# is stable and z=0 is unstable.
|
| 1036 |
+
|
| 1037 |
+
def sys3(t, w, omega, k, zfinal):
|
| 1038 |
+
x, y, z = w
|
| 1039 |
+
return [-omega*y, omega*x, k*z*(1 - z)]
|
| 1040 |
+
|
| 1041 |
+
def sys3_jac(t, w, omega, k, zfinal):
|
| 1042 |
+
x, y, z = w
|
| 1043 |
+
J = np.array([[0, -omega, 0],
|
| 1044 |
+
[omega, 0, 0],
|
| 1045 |
+
[0, 0, k*(1 - 2*z)]])
|
| 1046 |
+
return J
|
| 1047 |
+
|
| 1048 |
+
def sys3_x0decreasing(t, w, omega, k, zfinal):
|
| 1049 |
+
x, y, z = w
|
| 1050 |
+
return x
|
| 1051 |
+
|
| 1052 |
+
def sys3_y0increasing(t, w, omega, k, zfinal):
|
| 1053 |
+
x, y, z = w
|
| 1054 |
+
return y
|
| 1055 |
+
|
| 1056 |
+
def sys3_zfinal(t, w, omega, k, zfinal):
|
| 1057 |
+
x, y, z = w
|
| 1058 |
+
return z - zfinal
|
| 1059 |
+
|
| 1060 |
+
# Set the event flags for the event functions.
|
| 1061 |
+
sys3_x0decreasing.direction = -1
|
| 1062 |
+
sys3_y0increasing.direction = 1
|
| 1063 |
+
sys3_zfinal.terminal = True
|
| 1064 |
+
|
| 1065 |
+
omega = 2
|
| 1066 |
+
k = 4
|
| 1067 |
+
|
| 1068 |
+
tfinal = 5
|
| 1069 |
+
zfinal = 0.99
|
| 1070 |
+
# Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
|
| 1071 |
+
# The condition z(tfinal) = zfinal is the terminal event.
|
| 1072 |
+
z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
|
| 1073 |
+
|
| 1074 |
+
w0 = [0, -1, z0]
|
| 1075 |
+
|
| 1076 |
+
# Provide the jac argument and use the Radau method to ensure that the use
|
| 1077 |
+
# of the Jacobian function is exercised.
|
| 1078 |
+
# If event handling is working, the solution will stop at tfinal, not tend.
|
| 1079 |
+
tend = 2*tfinal
|
| 1080 |
+
sol = solve_ivp(sys3, [0, tend], w0,
|
| 1081 |
+
events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
|
| 1082 |
+
dense_output=True, args=(omega, k, zfinal),
|
| 1083 |
+
method='Radau', jac=sys3_jac,
|
| 1084 |
+
rtol=1e-10, atol=1e-13)
|
| 1085 |
+
|
| 1086 |
+
# Check that we got the expected events at the expected times.
|
| 1087 |
+
x0events_t = sol.t_events[0]
|
| 1088 |
+
y0events_t = sol.t_events[1]
|
| 1089 |
+
zfinalevents_t = sol.t_events[2]
|
| 1090 |
+
assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
|
| 1091 |
+
assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
|
| 1092 |
+
assert_allclose(zfinalevents_t, [tfinal])
|
| 1093 |
+
|
| 1094 |
+
# Check that the solution agrees with the known exact solution.
|
| 1095 |
+
t = np.linspace(0, zfinalevents_t[0], 250)
|
| 1096 |
+
w = sol.sol(t)
|
| 1097 |
+
assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
|
| 1098 |
+
assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
|
| 1099 |
+
assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
|
| 1100 |
+
rtol=1e-9, atol=1e-12)
|
| 1101 |
+
|
| 1102 |
+
# Check that the state variables have the expected values at the events.
|
| 1103 |
+
x0events = sol.sol(x0events_t)
|
| 1104 |
+
y0events = sol.sol(y0events_t)
|
| 1105 |
+
zfinalevents = sol.sol(zfinalevents_t)
|
| 1106 |
+
assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
|
| 1107 |
+
assert_allclose(x0events[1], np.ones_like(x0events[1]))
|
| 1108 |
+
assert_allclose(y0events[0], np.ones_like(y0events[0]))
|
| 1109 |
+
assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
|
| 1110 |
+
assert_allclose(zfinalevents[2], [zfinal])
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
@pytest.mark.thread_unsafe
|
| 1114 |
+
def test_array_rtol():
|
| 1115 |
+
# solve_ivp had a bug with array_like `rtol`; see gh-15482
|
| 1116 |
+
# check that it's fixed
|
| 1117 |
+
def f(t, y):
|
| 1118 |
+
return y[0], y[1]
|
| 1119 |
+
|
| 1120 |
+
# no warning (or error) when `rtol` is array_like
|
| 1121 |
+
sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
|
| 1122 |
+
err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
|
| 1123 |
+
|
| 1124 |
+
# warning when an element of `rtol` is too small
|
| 1125 |
+
with pytest.warns(UserWarning, match="At least one element..."):
|
| 1126 |
+
sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
|
| 1127 |
+
err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
|
| 1128 |
+
|
| 1129 |
+
# tighter rtol improves the error
|
| 1130 |
+
assert err2 < err1
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
|
| 1134 |
+
def test_integration_zero_rhs(method, num_parallel_threads):
|
| 1135 |
+
if method == 'LSODA' and num_parallel_threads > 1:
|
| 1136 |
+
pytest.skip(reason='LSODA does not allow for concurrent execution')
|
| 1137 |
+
|
| 1138 |
+
result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
|
| 1139 |
+
assert_(result.success)
|
| 1140 |
+
assert_equal(result.status, 0)
|
| 1141 |
+
assert_allclose(result.y, 1.0, rtol=1e-15)
|
| 1142 |
+
|
| 1143 |
+
|
| 1144 |
+
def test_args_single_value():
|
| 1145 |
+
def fun_with_arg(t, y, a):
|
| 1146 |
+
return a*y
|
| 1147 |
+
|
| 1148 |
+
message = "Supplied 'args' cannot be unpacked."
|
| 1149 |
+
with pytest.raises(TypeError, match=message):
|
| 1150 |
+
solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
|
| 1151 |
+
|
| 1152 |
+
sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
|
| 1153 |
+
assert_allclose(sol.y[0, -1], np.exp(-0.1))
|
| 1154 |
+
|
| 1155 |
+
|
| 1156 |
+
@pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
|
| 1157 |
+
def test_initial_state_finiteness(f0_fill):
|
| 1158 |
+
# regression test for gh-17846
|
| 1159 |
+
msg = "All components of the initial state `y0` must be finite."
|
| 1160 |
+
with pytest.raises(ValueError, match=msg):
|
| 1161 |
+
solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
|
| 1162 |
+
|
| 1163 |
+
|
| 1164 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1165 |
+
def test_zero_interval(method):
|
| 1166 |
+
# Case where upper and lower limits of integration are the same
|
| 1167 |
+
# Result of integration should match initial state.
|
| 1168 |
+
# f[y(t)] = 2y(t)
|
| 1169 |
+
def f(t, y):
|
| 1170 |
+
return 2 * y
|
| 1171 |
+
res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method)
|
| 1172 |
+
assert res.success
|
| 1173 |
+
assert_allclose(res.y[0, -1], 1.0)
|
| 1174 |
+
|
| 1175 |
+
|
| 1176 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1177 |
+
def test_tbound_respected_small_interval(method):
|
| 1178 |
+
"""Regression test for gh-17341"""
|
| 1179 |
+
SMALL = 1e-4
|
| 1180 |
+
|
| 1181 |
+
# f[y(t)] = 2y(t) on t in [0,SMALL]
|
| 1182 |
+
# undefined otherwise
|
| 1183 |
+
def f(t, y):
|
| 1184 |
+
if t > SMALL:
|
| 1185 |
+
raise ValueError("Function was evaluated outside interval")
|
| 1186 |
+
return 2 * y
|
| 1187 |
+
res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method)
|
| 1188 |
+
assert res.success
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1192 |
+
def test_tbound_respected_larger_interval(method):
|
| 1193 |
+
"""Regression test for gh-8848"""
|
| 1194 |
+
def V(r):
|
| 1195 |
+
return -11/r + 10 * r / (0.05 + r**2)
|
| 1196 |
+
|
| 1197 |
+
def func(t, p):
|
| 1198 |
+
if t < -17 or t > 2:
|
| 1199 |
+
raise ValueError("Function was evaluated outside interval")
|
| 1200 |
+
P = p[0]
|
| 1201 |
+
Q = p[1]
|
| 1202 |
+
r = np.exp(t)
|
| 1203 |
+
dPdr = r * Q
|
| 1204 |
+
dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q)
|
| 1205 |
+
return np.array([dPdr, dQdr])
|
| 1206 |
+
|
| 1207 |
+
result = solve_ivp(func,
|
| 1208 |
+
(-17, 2),
|
| 1209 |
+
y0=np.array([1, -11]),
|
| 1210 |
+
max_step=0.03,
|
| 1211 |
+
vectorized=False,
|
| 1212 |
+
t_eval=None,
|
| 1213 |
+
atol=1e-8,
|
| 1214 |
+
rtol=1e-5)
|
| 1215 |
+
assert result.success
|
| 1216 |
+
|
| 1217 |
+
|
| 1218 |
+
@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
|
| 1219 |
+
def test_tbound_respected_oscillator(method):
|
| 1220 |
+
"Regression test for gh-9198"
|
| 1221 |
+
def reactions_func(t, y):
|
| 1222 |
+
if (t > 205):
|
| 1223 |
+
raise ValueError("Called outside interval")
|
| 1224 |
+
yprime = np.array([1.73307544e-02,
|
| 1225 |
+
6.49376470e-06,
|
| 1226 |
+
0.00000000e+00,
|
| 1227 |
+
0.00000000e+00])
|
| 1228 |
+
return yprime
|
| 1229 |
+
|
| 1230 |
+
def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000):
|
| 1231 |
+
init_state = np.array([134.08298555, 138.82348612, 100., 0.])
|
| 1232 |
+
t0 = 100.0
|
| 1233 |
+
t1 = 200.0
|
| 1234 |
+
return solve_ivp(reactions_func,
|
| 1235 |
+
(t0, t1),
|
| 1236 |
+
init_state.copy(),
|
| 1237 |
+
dense_output=True,
|
| 1238 |
+
max_step=t1 - t0)
|
| 1239 |
+
result = run_sim2(1000, 100, 100)
|
| 1240 |
+
assert result.success
|
| 1241 |
+
|
| 1242 |
+
|
| 1243 |
+
def test_inital_maxstep():
|
| 1244 |
+
"""Verify that select_inital_step respects max_step"""
|
| 1245 |
+
rtol = 1e-3
|
| 1246 |
+
atol = 1e-6
|
| 1247 |
+
y0 = np.array([1/3, 2/9])
|
| 1248 |
+
for (t0, t_bound) in ((5, 9), (5, 1)):
|
| 1249 |
+
for method_order in [RK23.error_estimator_order,
|
| 1250 |
+
RK45.error_estimator_order,
|
| 1251 |
+
DOP853.error_estimator_order,
|
| 1252 |
+
3, #RADAU
|
| 1253 |
+
1 #BDF
|
| 1254 |
+
]:
|
| 1255 |
+
step_no_max = select_initial_step(fun_rational, t0, y0, t_bound,
|
| 1256 |
+
np.inf,
|
| 1257 |
+
fun_rational(t0,y0),
|
| 1258 |
+
np.sign(t_bound - t0),
|
| 1259 |
+
method_order,
|
| 1260 |
+
rtol, atol)
|
| 1261 |
+
max_step = step_no_max/2
|
| 1262 |
+
step_with_max = select_initial_step(fun_rational, t0, y0, t_bound,
|
| 1263 |
+
max_step,
|
| 1264 |
+
fun_rational(t0, y0),
|
| 1265 |
+
np.sign(t_bound - t0),
|
| 1266 |
+
method_order,
|
| 1267 |
+
rtol, atol)
|
| 1268 |
+
assert_equal(max_step, step_with_max)
|
evalkit_eagle/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)
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_lebedev.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b386368734a8b4c0c067a7e7a560a3f520121abd1a7f3b0d5307f7ce3ba8714
|
| 3 |
+
size 516865
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_ode.py
ADDED
|
@@ -0,0 +1,1388 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Authors: Pearu Peterson, Pauli Virtanen, John Travers
|
| 2 |
+
"""
|
| 3 |
+
First-order ODE integrators.
|
| 4 |
+
|
| 5 |
+
User-friendly interface to various numerical integrators for solving a
|
| 6 |
+
system of first order ODEs with prescribed initial conditions::
|
| 7 |
+
|
| 8 |
+
d y(t)[i]
|
| 9 |
+
--------- = f(t,y(t))[i],
|
| 10 |
+
d t
|
| 11 |
+
|
| 12 |
+
y(t=0)[i] = y0[i],
|
| 13 |
+
|
| 14 |
+
where::
|
| 15 |
+
|
| 16 |
+
i = 0, ..., len(y0) - 1
|
| 17 |
+
|
| 18 |
+
class ode
|
| 19 |
+
---------
|
| 20 |
+
|
| 21 |
+
A generic interface class to numeric integrators. It has the following
|
| 22 |
+
methods::
|
| 23 |
+
|
| 24 |
+
integrator = ode(f, jac=None)
|
| 25 |
+
integrator = integrator.set_integrator(name, **params)
|
| 26 |
+
integrator = integrator.set_initial_value(y0, t0=0.0)
|
| 27 |
+
integrator = integrator.set_f_params(*args)
|
| 28 |
+
integrator = integrator.set_jac_params(*args)
|
| 29 |
+
y1 = integrator.integrate(t1, step=False, relax=False)
|
| 30 |
+
flag = integrator.successful()
|
| 31 |
+
|
| 32 |
+
class complex_ode
|
| 33 |
+
-----------------
|
| 34 |
+
|
| 35 |
+
This class has the same generic interface as ode, except it can handle complex
|
| 36 |
+
f, y and Jacobians by transparently translating them into the equivalent
|
| 37 |
+
real-valued system. It supports the real-valued solvers (i.e., not zvode) and is
|
| 38 |
+
an alternative to ode with the zvode solver, sometimes performing better.
|
| 39 |
+
"""
|
| 40 |
+
# XXX: Integrators must have:
|
| 41 |
+
# ===========================
|
| 42 |
+
# cvode - C version of vode and vodpk with many improvements.
|
| 43 |
+
# Get it from http://www.netlib.org/ode/cvode.tar.gz.
|
| 44 |
+
# To wrap cvode to Python, one must write the extension module by
|
| 45 |
+
# hand. Its interface is too much 'advanced C' that using f2py
|
| 46 |
+
# would be too complicated (or impossible).
|
| 47 |
+
#
|
| 48 |
+
# How to define a new integrator:
|
| 49 |
+
# ===============================
|
| 50 |
+
#
|
| 51 |
+
# class myodeint(IntegratorBase):
|
| 52 |
+
#
|
| 53 |
+
# runner = <odeint function> or None
|
| 54 |
+
#
|
| 55 |
+
# def __init__(self,...): # required
|
| 56 |
+
# <initialize>
|
| 57 |
+
#
|
| 58 |
+
# def reset(self,n,has_jac): # optional
|
| 59 |
+
# # n - the size of the problem (number of equations)
|
| 60 |
+
# # has_jac - whether user has supplied its own routine for Jacobian
|
| 61 |
+
# <allocate memory,initialize further>
|
| 62 |
+
#
|
| 63 |
+
# def run(self,f,jac,y0,t0,t1,f_params,jac_params): # required
|
| 64 |
+
# # this method is called to integrate from t=t0 to t=t1
|
| 65 |
+
# # with initial condition y0. f and jac are user-supplied functions
|
| 66 |
+
# # that define the problem. f_params,jac_params are additional
|
| 67 |
+
# # arguments
|
| 68 |
+
# # to these functions.
|
| 69 |
+
# <calculate y1>
|
| 70 |
+
# if <calculation was unsuccessful>:
|
| 71 |
+
# self.success = 0
|
| 72 |
+
# return t1,y1
|
| 73 |
+
#
|
| 74 |
+
# # In addition, one can define step() and run_relax() methods (they
|
| 75 |
+
# # take the same arguments as run()) if the integrator can support
|
| 76 |
+
# # these features (see IntegratorBase doc strings).
|
| 77 |
+
#
|
| 78 |
+
# if myodeint.runner:
|
| 79 |
+
# IntegratorBase.integrator_classes.append(myodeint)
|
| 80 |
+
|
| 81 |
+
__all__ = ['ode', 'complex_ode']
|
| 82 |
+
|
| 83 |
+
import re
|
| 84 |
+
import threading
|
| 85 |
+
import warnings
|
| 86 |
+
|
| 87 |
+
from numpy import asarray, array, zeros, isscalar, real, imag, vstack
|
| 88 |
+
|
| 89 |
+
from . import _vode
|
| 90 |
+
from . import _dop
|
| 91 |
+
from . import _lsoda
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
_dop_int_dtype = _dop.types.intvar.dtype
|
| 95 |
+
_vode_int_dtype = _vode.types.intvar.dtype
|
| 96 |
+
_lsoda_int_dtype = _lsoda.types.intvar.dtype
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
# lsoda, vode and zvode are not thread-safe. VODE_LOCK protects both vode and
|
| 100 |
+
# zvode; they share the `def run` implementation
|
| 101 |
+
LSODA_LOCK = threading.Lock()
|
| 102 |
+
VODE_LOCK = threading.Lock()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ------------------------------------------------------------------------------
|
| 106 |
+
# User interface
|
| 107 |
+
# ------------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class ode:
|
| 111 |
+
"""
|
| 112 |
+
A generic interface class to numeric integrators.
|
| 113 |
+
|
| 114 |
+
Solve an equation system :math:`y'(t) = f(t,y)` with (optional) ``jac = df/dy``.
|
| 115 |
+
|
| 116 |
+
*Note*: The first two arguments of ``f(t, y, ...)`` are in the
|
| 117 |
+
opposite order of the arguments in the system definition function used
|
| 118 |
+
by `scipy.integrate.odeint`.
|
| 119 |
+
|
| 120 |
+
Parameters
|
| 121 |
+
----------
|
| 122 |
+
f : callable ``f(t, y, *f_args)``
|
| 123 |
+
Right-hand side of the differential equation. t is a scalar,
|
| 124 |
+
``y.shape == (n,)``.
|
| 125 |
+
``f_args`` is set by calling ``set_f_params(*args)``.
|
| 126 |
+
`f` should return a scalar, array or list (not a tuple).
|
| 127 |
+
jac : callable ``jac(t, y, *jac_args)``, optional
|
| 128 |
+
Jacobian of the right-hand side, ``jac[i,j] = d f[i] / d y[j]``.
|
| 129 |
+
``jac_args`` is set by calling ``set_jac_params(*args)``.
|
| 130 |
+
|
| 131 |
+
Attributes
|
| 132 |
+
----------
|
| 133 |
+
t : float
|
| 134 |
+
Current time.
|
| 135 |
+
y : ndarray
|
| 136 |
+
Current variable values.
|
| 137 |
+
|
| 138 |
+
See also
|
| 139 |
+
--------
|
| 140 |
+
odeint : an integrator with a simpler interface based on lsoda from ODEPACK
|
| 141 |
+
quad : for finding the area under a curve
|
| 142 |
+
|
| 143 |
+
Notes
|
| 144 |
+
-----
|
| 145 |
+
Available integrators are listed below. They can be selected using
|
| 146 |
+
the `set_integrator` method.
|
| 147 |
+
|
| 148 |
+
"vode"
|
| 149 |
+
|
| 150 |
+
Real-valued Variable-coefficient Ordinary Differential Equation
|
| 151 |
+
solver, with fixed-leading-coefficient implementation. It provides
|
| 152 |
+
implicit Adams method (for non-stiff problems) and a method based on
|
| 153 |
+
backward differentiation formulas (BDF) (for stiff problems).
|
| 154 |
+
|
| 155 |
+
Source: http://www.netlib.org/ode/vode.f
|
| 156 |
+
|
| 157 |
+
.. warning::
|
| 158 |
+
|
| 159 |
+
This integrator is not re-entrant. You cannot have two `ode`
|
| 160 |
+
instances using the "vode" integrator at the same time.
|
| 161 |
+
|
| 162 |
+
This integrator accepts the following parameters in `set_integrator`
|
| 163 |
+
method of the `ode` class:
|
| 164 |
+
|
| 165 |
+
- atol : float or sequence
|
| 166 |
+
absolute tolerance for solution
|
| 167 |
+
- rtol : float or sequence
|
| 168 |
+
relative tolerance for solution
|
| 169 |
+
- lband : None or int
|
| 170 |
+
- uband : None or int
|
| 171 |
+
Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
|
| 172 |
+
Setting these requires your jac routine to return the jacobian
|
| 173 |
+
in packed format, jac_packed[i-j+uband, j] = jac[i,j]. The
|
| 174 |
+
dimension of the matrix must be (lband+uband+1, len(y)).
|
| 175 |
+
- method: 'adams' or 'bdf'
|
| 176 |
+
Which solver to use, Adams (non-stiff) or BDF (stiff)
|
| 177 |
+
- with_jacobian : bool
|
| 178 |
+
This option is only considered when the user has not supplied a
|
| 179 |
+
Jacobian function and has not indicated (by setting either band)
|
| 180 |
+
that the Jacobian is banded. In this case, `with_jacobian` specifies
|
| 181 |
+
whether the iteration method of the ODE solver's correction step is
|
| 182 |
+
chord iteration with an internally generated full Jacobian or
|
| 183 |
+
functional iteration with no Jacobian.
|
| 184 |
+
- nsteps : int
|
| 185 |
+
Maximum number of (internally defined) steps allowed during one
|
| 186 |
+
call to the solver.
|
| 187 |
+
- first_step : float
|
| 188 |
+
- min_step : float
|
| 189 |
+
- max_step : float
|
| 190 |
+
Limits for the step sizes used by the integrator.
|
| 191 |
+
- order : int
|
| 192 |
+
Maximum order used by the integrator,
|
| 193 |
+
order <= 12 for Adams, <= 5 for BDF.
|
| 194 |
+
|
| 195 |
+
"zvode"
|
| 196 |
+
|
| 197 |
+
Complex-valued Variable-coefficient Ordinary Differential Equation
|
| 198 |
+
solver, with fixed-leading-coefficient implementation. It provides
|
| 199 |
+
implicit Adams method (for non-stiff problems) and a method based on
|
| 200 |
+
backward differentiation formulas (BDF) (for stiff problems).
|
| 201 |
+
|
| 202 |
+
Source: http://www.netlib.org/ode/zvode.f
|
| 203 |
+
|
| 204 |
+
.. warning::
|
| 205 |
+
|
| 206 |
+
This integrator is not re-entrant. You cannot have two `ode`
|
| 207 |
+
instances using the "zvode" integrator at the same time.
|
| 208 |
+
|
| 209 |
+
This integrator accepts the same parameters in `set_integrator`
|
| 210 |
+
as the "vode" solver.
|
| 211 |
+
|
| 212 |
+
.. note::
|
| 213 |
+
|
| 214 |
+
When using ZVODE for a stiff system, it should only be used for
|
| 215 |
+
the case in which the function f is analytic, that is, when each f(i)
|
| 216 |
+
is an analytic function of each y(j). Analyticity means that the
|
| 217 |
+
partial derivative df(i)/dy(j) is a unique complex number, and this
|
| 218 |
+
fact is critical in the way ZVODE solves the dense or banded linear
|
| 219 |
+
systems that arise in the stiff case. For a complex stiff ODE system
|
| 220 |
+
in which f is not analytic, ZVODE is likely to have convergence
|
| 221 |
+
failures, and for this problem one should instead use DVODE on the
|
| 222 |
+
equivalent real system (in the real and imaginary parts of y).
|
| 223 |
+
|
| 224 |
+
"lsoda"
|
| 225 |
+
|
| 226 |
+
Real-valued Variable-coefficient Ordinary Differential Equation
|
| 227 |
+
solver, with fixed-leading-coefficient implementation. It provides
|
| 228 |
+
automatic method switching between implicit Adams method (for non-stiff
|
| 229 |
+
problems) and a method based on backward differentiation formulas (BDF)
|
| 230 |
+
(for stiff problems).
|
| 231 |
+
|
| 232 |
+
Source: http://www.netlib.org/odepack
|
| 233 |
+
|
| 234 |
+
.. warning::
|
| 235 |
+
|
| 236 |
+
This integrator is not re-entrant. You cannot have two `ode`
|
| 237 |
+
instances using the "lsoda" integrator at the same time.
|
| 238 |
+
|
| 239 |
+
This integrator accepts the following parameters in `set_integrator`
|
| 240 |
+
method of the `ode` class:
|
| 241 |
+
|
| 242 |
+
- atol : float or sequence
|
| 243 |
+
absolute tolerance for solution
|
| 244 |
+
- rtol : float or sequence
|
| 245 |
+
relative tolerance for solution
|
| 246 |
+
- lband : None or int
|
| 247 |
+
- uband : None or int
|
| 248 |
+
Jacobian band width, jac[i,j] != 0 for i-lband <= j <= i+uband.
|
| 249 |
+
Setting these requires your jac routine to return the jacobian
|
| 250 |
+
in packed format, jac_packed[i-j+uband, j] = jac[i,j].
|
| 251 |
+
- with_jacobian : bool
|
| 252 |
+
*Not used.*
|
| 253 |
+
- nsteps : int
|
| 254 |
+
Maximum number of (internally defined) steps allowed during one
|
| 255 |
+
call to the solver.
|
| 256 |
+
- first_step : float
|
| 257 |
+
- min_step : float
|
| 258 |
+
- max_step : float
|
| 259 |
+
Limits for the step sizes used by the integrator.
|
| 260 |
+
- max_order_ns : int
|
| 261 |
+
Maximum order used in the nonstiff case (default 12).
|
| 262 |
+
- max_order_s : int
|
| 263 |
+
Maximum order used in the stiff case (default 5).
|
| 264 |
+
- max_hnil : int
|
| 265 |
+
Maximum number of messages reporting too small step size (t + h = t)
|
| 266 |
+
(default 0)
|
| 267 |
+
- ixpr : int
|
| 268 |
+
Whether to generate extra printing at method switches (default False).
|
| 269 |
+
|
| 270 |
+
"dopri5"
|
| 271 |
+
|
| 272 |
+
This is an explicit runge-kutta method of order (4)5 due to Dormand &
|
| 273 |
+
Prince (with stepsize control and dense output).
|
| 274 |
+
|
| 275 |
+
Authors:
|
| 276 |
+
|
| 277 |
+
E. Hairer and G. Wanner
|
| 278 |
+
Universite de Geneve, Dept. de Mathematiques
|
| 279 |
+
CH-1211 Geneve 24, Switzerland
|
| 280 |
+
e-mail: ernst.hairer@math.unige.ch, gerhard.wanner@math.unige.ch
|
| 281 |
+
|
| 282 |
+
This code is described in [HNW93]_.
|
| 283 |
+
|
| 284 |
+
This integrator accepts the following parameters in set_integrator()
|
| 285 |
+
method of the ode class:
|
| 286 |
+
|
| 287 |
+
- atol : float or sequence
|
| 288 |
+
absolute tolerance for solution
|
| 289 |
+
- rtol : float or sequence
|
| 290 |
+
relative tolerance for solution
|
| 291 |
+
- nsteps : int
|
| 292 |
+
Maximum number of (internally defined) steps allowed during one
|
| 293 |
+
call to the solver.
|
| 294 |
+
- first_step : float
|
| 295 |
+
- max_step : float
|
| 296 |
+
- safety : float
|
| 297 |
+
Safety factor on new step selection (default 0.9)
|
| 298 |
+
- ifactor : float
|
| 299 |
+
- dfactor : float
|
| 300 |
+
Maximum factor to increase/decrease step size by in one step
|
| 301 |
+
- beta : float
|
| 302 |
+
Beta parameter for stabilised step size control.
|
| 303 |
+
- verbosity : int
|
| 304 |
+
Switch for printing messages (< 0 for no messages).
|
| 305 |
+
|
| 306 |
+
"dop853"
|
| 307 |
+
|
| 308 |
+
This is an explicit runge-kutta method of order 8(5,3) due to Dormand
|
| 309 |
+
& Prince (with stepsize control and dense output).
|
| 310 |
+
|
| 311 |
+
Options and references the same as "dopri5".
|
| 312 |
+
|
| 313 |
+
Examples
|
| 314 |
+
--------
|
| 315 |
+
|
| 316 |
+
A problem to integrate and the corresponding jacobian:
|
| 317 |
+
|
| 318 |
+
>>> from scipy.integrate import ode
|
| 319 |
+
>>>
|
| 320 |
+
>>> y0, t0 = [1.0j, 2.0], 0
|
| 321 |
+
>>>
|
| 322 |
+
>>> def f(t, y, arg1):
|
| 323 |
+
... return [1j*arg1*y[0] + y[1], -arg1*y[1]**2]
|
| 324 |
+
>>> def jac(t, y, arg1):
|
| 325 |
+
... return [[1j*arg1, 1], [0, -arg1*2*y[1]]]
|
| 326 |
+
|
| 327 |
+
The integration:
|
| 328 |
+
|
| 329 |
+
>>> r = ode(f, jac).set_integrator('zvode', method='bdf')
|
| 330 |
+
>>> r.set_initial_value(y0, t0).set_f_params(2.0).set_jac_params(2.0)
|
| 331 |
+
>>> t1 = 10
|
| 332 |
+
>>> dt = 1
|
| 333 |
+
>>> while r.successful() and r.t < t1:
|
| 334 |
+
... print(r.t+dt, r.integrate(r.t+dt))
|
| 335 |
+
1 [-0.71038232+0.23749653j 0.40000271+0.j ]
|
| 336 |
+
2.0 [0.19098503-0.52359246j 0.22222356+0.j ]
|
| 337 |
+
3.0 [0.47153208+0.52701229j 0.15384681+0.j ]
|
| 338 |
+
4.0 [-0.61905937+0.30726255j 0.11764744+0.j ]
|
| 339 |
+
5.0 [0.02340997-0.61418799j 0.09523835+0.j ]
|
| 340 |
+
6.0 [0.58643071+0.339819j 0.08000018+0.j ]
|
| 341 |
+
7.0 [-0.52070105+0.44525141j 0.06896565+0.j ]
|
| 342 |
+
8.0 [-0.15986733-0.61234476j 0.06060616+0.j ]
|
| 343 |
+
9.0 [0.64850462+0.15048982j 0.05405414+0.j ]
|
| 344 |
+
10.0 [-0.38404699+0.56382299j 0.04878055+0.j ]
|
| 345 |
+
|
| 346 |
+
References
|
| 347 |
+
----------
|
| 348 |
+
.. [HNW93] E. Hairer, S.P. Norsett and G. Wanner, Solving Ordinary
|
| 349 |
+
Differential Equations i. Nonstiff Problems. 2nd edition.
|
| 350 |
+
Springer Series in Computational Mathematics,
|
| 351 |
+
Springer-Verlag (1993)
|
| 352 |
+
|
| 353 |
+
"""
|
| 354 |
+
|
| 355 |
+
def __init__(self, f, jac=None):
|
| 356 |
+
self.stiff = 0
|
| 357 |
+
self.f = f
|
| 358 |
+
self.jac = jac
|
| 359 |
+
self.f_params = ()
|
| 360 |
+
self.jac_params = ()
|
| 361 |
+
self._y = []
|
| 362 |
+
|
| 363 |
+
@property
|
| 364 |
+
def y(self):
|
| 365 |
+
return self._y
|
| 366 |
+
|
| 367 |
+
def set_initial_value(self, y, t=0.0):
|
| 368 |
+
"""Set initial conditions y(t) = y."""
|
| 369 |
+
if isscalar(y):
|
| 370 |
+
y = [y]
|
| 371 |
+
n_prev = len(self._y)
|
| 372 |
+
if not n_prev:
|
| 373 |
+
self.set_integrator('') # find first available integrator
|
| 374 |
+
self._y = asarray(y, self._integrator.scalar)
|
| 375 |
+
self.t = t
|
| 376 |
+
self._integrator.reset(len(self._y), self.jac is not None)
|
| 377 |
+
return self
|
| 378 |
+
|
| 379 |
+
def set_integrator(self, name, **integrator_params):
|
| 380 |
+
"""
|
| 381 |
+
Set integrator by name.
|
| 382 |
+
|
| 383 |
+
Parameters
|
| 384 |
+
----------
|
| 385 |
+
name : str
|
| 386 |
+
Name of the integrator.
|
| 387 |
+
**integrator_params
|
| 388 |
+
Additional parameters for the integrator.
|
| 389 |
+
"""
|
| 390 |
+
integrator = find_integrator(name)
|
| 391 |
+
if integrator is None:
|
| 392 |
+
# FIXME: this really should be raise an exception. Will that break
|
| 393 |
+
# any code?
|
| 394 |
+
message = f'No integrator name match with {name!r} or is not available.'
|
| 395 |
+
warnings.warn(message, stacklevel=2)
|
| 396 |
+
else:
|
| 397 |
+
self._integrator = integrator(**integrator_params)
|
| 398 |
+
if not len(self._y):
|
| 399 |
+
self.t = 0.0
|
| 400 |
+
self._y = array([0.0], self._integrator.scalar)
|
| 401 |
+
self._integrator.reset(len(self._y), self.jac is not None)
|
| 402 |
+
return self
|
| 403 |
+
|
| 404 |
+
def integrate(self, t, step=False, relax=False):
|
| 405 |
+
"""Find y=y(t), set y as an initial condition, and return y.
|
| 406 |
+
|
| 407 |
+
Parameters
|
| 408 |
+
----------
|
| 409 |
+
t : float
|
| 410 |
+
The endpoint of the integration step.
|
| 411 |
+
step : bool
|
| 412 |
+
If True, and if the integrator supports the step method,
|
| 413 |
+
then perform a single integration step and return.
|
| 414 |
+
This parameter is provided in order to expose internals of
|
| 415 |
+
the implementation, and should not be changed from its default
|
| 416 |
+
value in most cases.
|
| 417 |
+
relax : bool
|
| 418 |
+
If True and if the integrator supports the run_relax method,
|
| 419 |
+
then integrate until t_1 >= t and return. ``relax`` is not
|
| 420 |
+
referenced if ``step=True``.
|
| 421 |
+
This parameter is provided in order to expose internals of
|
| 422 |
+
the implementation, and should not be changed from its default
|
| 423 |
+
value in most cases.
|
| 424 |
+
|
| 425 |
+
Returns
|
| 426 |
+
-------
|
| 427 |
+
y : float
|
| 428 |
+
The integrated value at t
|
| 429 |
+
"""
|
| 430 |
+
if step and self._integrator.supports_step:
|
| 431 |
+
mth = self._integrator.step
|
| 432 |
+
elif relax and self._integrator.supports_run_relax:
|
| 433 |
+
mth = self._integrator.run_relax
|
| 434 |
+
else:
|
| 435 |
+
mth = self._integrator.run
|
| 436 |
+
|
| 437 |
+
try:
|
| 438 |
+
self._y, self.t = mth(self.f, self.jac or (lambda: None),
|
| 439 |
+
self._y, self.t, t,
|
| 440 |
+
self.f_params, self.jac_params)
|
| 441 |
+
except SystemError as e:
|
| 442 |
+
# f2py issue with tuple returns, see ticket 1187.
|
| 443 |
+
raise ValueError(
|
| 444 |
+
'Function to integrate must not return a tuple.'
|
| 445 |
+
) from e
|
| 446 |
+
|
| 447 |
+
return self._y
|
| 448 |
+
|
| 449 |
+
def successful(self):
|
| 450 |
+
"""Check if integration was successful."""
|
| 451 |
+
try:
|
| 452 |
+
self._integrator
|
| 453 |
+
except AttributeError:
|
| 454 |
+
self.set_integrator('')
|
| 455 |
+
return self._integrator.success == 1
|
| 456 |
+
|
| 457 |
+
def get_return_code(self):
|
| 458 |
+
"""Extracts the return code for the integration to enable better control
|
| 459 |
+
if the integration fails.
|
| 460 |
+
|
| 461 |
+
In general, a return code > 0 implies success, while a return code < 0
|
| 462 |
+
implies failure.
|
| 463 |
+
|
| 464 |
+
Notes
|
| 465 |
+
-----
|
| 466 |
+
This section describes possible return codes and their meaning, for available
|
| 467 |
+
integrators that can be selected by `set_integrator` method.
|
| 468 |
+
|
| 469 |
+
"vode"
|
| 470 |
+
|
| 471 |
+
=========== =======
|
| 472 |
+
Return Code Message
|
| 473 |
+
=========== =======
|
| 474 |
+
2 Integration successful.
|
| 475 |
+
-1 Excess work done on this call. (Perhaps wrong MF.)
|
| 476 |
+
-2 Excess accuracy requested. (Tolerances too small.)
|
| 477 |
+
-3 Illegal input detected. (See printed message.)
|
| 478 |
+
-4 Repeated error test failures. (Check all input.)
|
| 479 |
+
-5 Repeated convergence failures. (Perhaps bad Jacobian
|
| 480 |
+
supplied or wrong choice of MF or tolerances.)
|
| 481 |
+
-6 Error weight became zero during problem. (Solution
|
| 482 |
+
component i vanished, and ATOL or ATOL(i) = 0.)
|
| 483 |
+
=========== =======
|
| 484 |
+
|
| 485 |
+
"zvode"
|
| 486 |
+
|
| 487 |
+
=========== =======
|
| 488 |
+
Return Code Message
|
| 489 |
+
=========== =======
|
| 490 |
+
2 Integration successful.
|
| 491 |
+
-1 Excess work done on this call. (Perhaps wrong MF.)
|
| 492 |
+
-2 Excess accuracy requested. (Tolerances too small.)
|
| 493 |
+
-3 Illegal input detected. (See printed message.)
|
| 494 |
+
-4 Repeated error test failures. (Check all input.)
|
| 495 |
+
-5 Repeated convergence failures. (Perhaps bad Jacobian
|
| 496 |
+
supplied or wrong choice of MF or tolerances.)
|
| 497 |
+
-6 Error weight became zero during problem. (Solution
|
| 498 |
+
component i vanished, and ATOL or ATOL(i) = 0.)
|
| 499 |
+
=========== =======
|
| 500 |
+
|
| 501 |
+
"dopri5"
|
| 502 |
+
|
| 503 |
+
=========== =======
|
| 504 |
+
Return Code Message
|
| 505 |
+
=========== =======
|
| 506 |
+
1 Integration successful.
|
| 507 |
+
2 Integration successful (interrupted by solout).
|
| 508 |
+
-1 Input is not consistent.
|
| 509 |
+
-2 Larger nsteps is needed.
|
| 510 |
+
-3 Step size becomes too small.
|
| 511 |
+
-4 Problem is probably stiff (interrupted).
|
| 512 |
+
=========== =======
|
| 513 |
+
|
| 514 |
+
"dop853"
|
| 515 |
+
|
| 516 |
+
=========== =======
|
| 517 |
+
Return Code Message
|
| 518 |
+
=========== =======
|
| 519 |
+
1 Integration successful.
|
| 520 |
+
2 Integration successful (interrupted by solout).
|
| 521 |
+
-1 Input is not consistent.
|
| 522 |
+
-2 Larger nsteps is needed.
|
| 523 |
+
-3 Step size becomes too small.
|
| 524 |
+
-4 Problem is probably stiff (interrupted).
|
| 525 |
+
=========== =======
|
| 526 |
+
|
| 527 |
+
"lsoda"
|
| 528 |
+
|
| 529 |
+
=========== =======
|
| 530 |
+
Return Code Message
|
| 531 |
+
=========== =======
|
| 532 |
+
2 Integration successful.
|
| 533 |
+
-1 Excess work done on this call (perhaps wrong Dfun type).
|
| 534 |
+
-2 Excess accuracy requested (tolerances too small).
|
| 535 |
+
-3 Illegal input detected (internal error).
|
| 536 |
+
-4 Repeated error test failures (internal error).
|
| 537 |
+
-5 Repeated convergence failures (perhaps bad Jacobian or tolerances).
|
| 538 |
+
-6 Error weight became zero during problem.
|
| 539 |
+
-7 Internal workspace insufficient to finish (internal error).
|
| 540 |
+
=========== =======
|
| 541 |
+
"""
|
| 542 |
+
try:
|
| 543 |
+
self._integrator
|
| 544 |
+
except AttributeError:
|
| 545 |
+
self.set_integrator('')
|
| 546 |
+
return self._integrator.istate
|
| 547 |
+
|
| 548 |
+
def set_f_params(self, *args):
|
| 549 |
+
"""Set extra parameters for user-supplied function f."""
|
| 550 |
+
self.f_params = args
|
| 551 |
+
return self
|
| 552 |
+
|
| 553 |
+
def set_jac_params(self, *args):
|
| 554 |
+
"""Set extra parameters for user-supplied function jac."""
|
| 555 |
+
self.jac_params = args
|
| 556 |
+
return self
|
| 557 |
+
|
| 558 |
+
def set_solout(self, solout):
|
| 559 |
+
"""
|
| 560 |
+
Set callable to be called at every successful integration step.
|
| 561 |
+
|
| 562 |
+
Parameters
|
| 563 |
+
----------
|
| 564 |
+
solout : callable
|
| 565 |
+
``solout(t, y)`` is called at each internal integrator step,
|
| 566 |
+
t is a scalar providing the current independent position
|
| 567 |
+
y is the current solution ``y.shape == (n,)``
|
| 568 |
+
solout should return -1 to stop integration
|
| 569 |
+
otherwise it should return None or 0
|
| 570 |
+
|
| 571 |
+
"""
|
| 572 |
+
if self._integrator.supports_solout:
|
| 573 |
+
self._integrator.set_solout(solout)
|
| 574 |
+
if self._y is not None:
|
| 575 |
+
self._integrator.reset(len(self._y), self.jac is not None)
|
| 576 |
+
else:
|
| 577 |
+
raise ValueError("selected integrator does not support solout,"
|
| 578 |
+
" choose another one")
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def _transform_banded_jac(bjac):
|
| 582 |
+
"""
|
| 583 |
+
Convert a real matrix of the form (for example)
|
| 584 |
+
|
| 585 |
+
[0 0 A B] [0 0 0 B]
|
| 586 |
+
[0 0 C D] [0 0 A D]
|
| 587 |
+
[E F G H] to [0 F C H]
|
| 588 |
+
[I J K L] [E J G L]
|
| 589 |
+
[I 0 K 0]
|
| 590 |
+
|
| 591 |
+
That is, every other column is shifted up one.
|
| 592 |
+
"""
|
| 593 |
+
# Shift every other column.
|
| 594 |
+
newjac = zeros((bjac.shape[0] + 1, bjac.shape[1]))
|
| 595 |
+
newjac[1:, ::2] = bjac[:, ::2]
|
| 596 |
+
newjac[:-1, 1::2] = bjac[:, 1::2]
|
| 597 |
+
return newjac
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class complex_ode(ode):
|
| 601 |
+
"""
|
| 602 |
+
A wrapper of ode for complex systems.
|
| 603 |
+
|
| 604 |
+
This functions similarly as `ode`, but re-maps a complex-valued
|
| 605 |
+
equation system to a real-valued one before using the integrators.
|
| 606 |
+
|
| 607 |
+
Parameters
|
| 608 |
+
----------
|
| 609 |
+
f : callable ``f(t, y, *f_args)``
|
| 610 |
+
Rhs of the equation. t is a scalar, ``y.shape == (n,)``.
|
| 611 |
+
``f_args`` is set by calling ``set_f_params(*args)``.
|
| 612 |
+
jac : callable ``jac(t, y, *jac_args)``
|
| 613 |
+
Jacobian of the rhs, ``jac[i,j] = d f[i] / d y[j]``.
|
| 614 |
+
``jac_args`` is set by calling ``set_f_params(*args)``.
|
| 615 |
+
|
| 616 |
+
Attributes
|
| 617 |
+
----------
|
| 618 |
+
t : float
|
| 619 |
+
Current time.
|
| 620 |
+
y : ndarray
|
| 621 |
+
Current variable values.
|
| 622 |
+
|
| 623 |
+
Examples
|
| 624 |
+
--------
|
| 625 |
+
For usage examples, see `ode`.
|
| 626 |
+
|
| 627 |
+
"""
|
| 628 |
+
|
| 629 |
+
def __init__(self, f, jac=None):
|
| 630 |
+
self.cf = f
|
| 631 |
+
self.cjac = jac
|
| 632 |
+
if jac is None:
|
| 633 |
+
ode.__init__(self, self._wrap, None)
|
| 634 |
+
else:
|
| 635 |
+
ode.__init__(self, self._wrap, self._wrap_jac)
|
| 636 |
+
|
| 637 |
+
def _wrap(self, t, y, *f_args):
|
| 638 |
+
f = self.cf(*((t, y[::2] + 1j * y[1::2]) + f_args))
|
| 639 |
+
# self.tmp is a real-valued array containing the interleaved
|
| 640 |
+
# real and imaginary parts of f.
|
| 641 |
+
self.tmp[::2] = real(f)
|
| 642 |
+
self.tmp[1::2] = imag(f)
|
| 643 |
+
return self.tmp
|
| 644 |
+
|
| 645 |
+
def _wrap_jac(self, t, y, *jac_args):
|
| 646 |
+
# jac is the complex Jacobian computed by the user-defined function.
|
| 647 |
+
jac = self.cjac(*((t, y[::2] + 1j * y[1::2]) + jac_args))
|
| 648 |
+
|
| 649 |
+
# jac_tmp is the real version of the complex Jacobian. Each complex
|
| 650 |
+
# entry in jac, say 2+3j, becomes a 2x2 block of the form
|
| 651 |
+
# [2 -3]
|
| 652 |
+
# [3 2]
|
| 653 |
+
jac_tmp = zeros((2 * jac.shape[0], 2 * jac.shape[1]))
|
| 654 |
+
jac_tmp[1::2, 1::2] = jac_tmp[::2, ::2] = real(jac)
|
| 655 |
+
jac_tmp[1::2, ::2] = imag(jac)
|
| 656 |
+
jac_tmp[::2, 1::2] = -jac_tmp[1::2, ::2]
|
| 657 |
+
|
| 658 |
+
ml = getattr(self._integrator, 'ml', None)
|
| 659 |
+
mu = getattr(self._integrator, 'mu', None)
|
| 660 |
+
if ml is not None or mu is not None:
|
| 661 |
+
# Jacobian is banded. The user's Jacobian function has computed
|
| 662 |
+
# the complex Jacobian in packed format. The corresponding
|
| 663 |
+
# real-valued version has every other column shifted up.
|
| 664 |
+
jac_tmp = _transform_banded_jac(jac_tmp)
|
| 665 |
+
|
| 666 |
+
return jac_tmp
|
| 667 |
+
|
| 668 |
+
@property
|
| 669 |
+
def y(self):
|
| 670 |
+
return self._y[::2] + 1j * self._y[1::2]
|
| 671 |
+
|
| 672 |
+
def set_integrator(self, name, **integrator_params):
|
| 673 |
+
"""
|
| 674 |
+
Set integrator by name.
|
| 675 |
+
|
| 676 |
+
Parameters
|
| 677 |
+
----------
|
| 678 |
+
name : str
|
| 679 |
+
Name of the integrator
|
| 680 |
+
**integrator_params
|
| 681 |
+
Additional parameters for the integrator.
|
| 682 |
+
"""
|
| 683 |
+
if name == 'zvode':
|
| 684 |
+
raise ValueError("zvode must be used with ode, not complex_ode")
|
| 685 |
+
|
| 686 |
+
lband = integrator_params.get('lband')
|
| 687 |
+
uband = integrator_params.get('uband')
|
| 688 |
+
if lband is not None or uband is not None:
|
| 689 |
+
# The Jacobian is banded. Override the user-supplied bandwidths
|
| 690 |
+
# (which are for the complex Jacobian) with the bandwidths of
|
| 691 |
+
# the corresponding real-valued Jacobian wrapper of the complex
|
| 692 |
+
# Jacobian.
|
| 693 |
+
integrator_params['lband'] = 2 * (lband or 0) + 1
|
| 694 |
+
integrator_params['uband'] = 2 * (uband or 0) + 1
|
| 695 |
+
|
| 696 |
+
return ode.set_integrator(self, name, **integrator_params)
|
| 697 |
+
|
| 698 |
+
def set_initial_value(self, y, t=0.0):
|
| 699 |
+
"""Set initial conditions y(t) = y."""
|
| 700 |
+
y = asarray(y)
|
| 701 |
+
self.tmp = zeros(y.size * 2, 'float')
|
| 702 |
+
self.tmp[::2] = real(y)
|
| 703 |
+
self.tmp[1::2] = imag(y)
|
| 704 |
+
return ode.set_initial_value(self, self.tmp, t)
|
| 705 |
+
|
| 706 |
+
def integrate(self, t, step=False, relax=False):
|
| 707 |
+
"""Find y=y(t), set y as an initial condition, and return y.
|
| 708 |
+
|
| 709 |
+
Parameters
|
| 710 |
+
----------
|
| 711 |
+
t : float
|
| 712 |
+
The endpoint of the integration step.
|
| 713 |
+
step : bool
|
| 714 |
+
If True, and if the integrator supports the step method,
|
| 715 |
+
then perform a single integration step and return.
|
| 716 |
+
This parameter is provided in order to expose internals of
|
| 717 |
+
the implementation, and should not be changed from its default
|
| 718 |
+
value in most cases.
|
| 719 |
+
relax : bool
|
| 720 |
+
If True and if the integrator supports the run_relax method,
|
| 721 |
+
then integrate until t_1 >= t and return. ``relax`` is not
|
| 722 |
+
referenced if ``step=True``.
|
| 723 |
+
This parameter is provided in order to expose internals of
|
| 724 |
+
the implementation, and should not be changed from its default
|
| 725 |
+
value in most cases.
|
| 726 |
+
|
| 727 |
+
Returns
|
| 728 |
+
-------
|
| 729 |
+
y : float
|
| 730 |
+
The integrated value at t
|
| 731 |
+
"""
|
| 732 |
+
y = ode.integrate(self, t, step, relax)
|
| 733 |
+
return y[::2] + 1j * y[1::2]
|
| 734 |
+
|
| 735 |
+
def set_solout(self, solout):
|
| 736 |
+
"""
|
| 737 |
+
Set callable to be called at every successful integration step.
|
| 738 |
+
|
| 739 |
+
Parameters
|
| 740 |
+
----------
|
| 741 |
+
solout : callable
|
| 742 |
+
``solout(t, y)`` is called at each internal integrator step,
|
| 743 |
+
t is a scalar providing the current independent position
|
| 744 |
+
y is the current solution ``y.shape == (n,)``
|
| 745 |
+
solout should return -1 to stop integration
|
| 746 |
+
otherwise it should return None or 0
|
| 747 |
+
|
| 748 |
+
"""
|
| 749 |
+
if self._integrator.supports_solout:
|
| 750 |
+
self._integrator.set_solout(solout, complex=True)
|
| 751 |
+
else:
|
| 752 |
+
raise TypeError("selected integrator does not support solouta, "
|
| 753 |
+
"choose another one")
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
# ------------------------------------------------------------------------------
|
| 757 |
+
# ODE integrators
|
| 758 |
+
# ------------------------------------------------------------------------------
|
| 759 |
+
|
| 760 |
+
def find_integrator(name):
|
| 761 |
+
for cl in IntegratorBase.integrator_classes:
|
| 762 |
+
if re.match(name, cl.__name__, re.I):
|
| 763 |
+
return cl
|
| 764 |
+
return None
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
class IntegratorConcurrencyError(RuntimeError):
|
| 768 |
+
"""
|
| 769 |
+
Failure due to concurrent usage of an integrator that can be used
|
| 770 |
+
only for a single problem at a time.
|
| 771 |
+
|
| 772 |
+
"""
|
| 773 |
+
|
| 774 |
+
def __init__(self, name):
|
| 775 |
+
msg = (f"Integrator `{name}` can be used to solve only a single problem "
|
| 776 |
+
"at a time. If you want to integrate multiple problems, "
|
| 777 |
+
"consider using a different integrator (see `ode.set_integrator`)")
|
| 778 |
+
RuntimeError.__init__(self, msg)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
class IntegratorBase:
|
| 782 |
+
runner = None # runner is None => integrator is not available
|
| 783 |
+
success = None # success==1 if integrator was called successfully
|
| 784 |
+
istate = None # istate > 0 means success, istate < 0 means failure
|
| 785 |
+
supports_run_relax = None
|
| 786 |
+
supports_step = None
|
| 787 |
+
supports_solout = False
|
| 788 |
+
integrator_classes = []
|
| 789 |
+
scalar = float
|
| 790 |
+
|
| 791 |
+
def acquire_new_handle(self):
|
| 792 |
+
# Some of the integrators have internal state (ancient
|
| 793 |
+
# Fortran...), and so only one instance can use them at a time.
|
| 794 |
+
# We keep track of this, and fail when concurrent usage is tried.
|
| 795 |
+
self.__class__.active_global_handle += 1
|
| 796 |
+
self.handle = self.__class__.active_global_handle
|
| 797 |
+
|
| 798 |
+
def check_handle(self):
|
| 799 |
+
if self.handle is not self.__class__.active_global_handle:
|
| 800 |
+
raise IntegratorConcurrencyError(self.__class__.__name__)
|
| 801 |
+
|
| 802 |
+
def reset(self, n, has_jac):
|
| 803 |
+
"""Prepare integrator for call: allocate memory, set flags, etc.
|
| 804 |
+
n - number of equations.
|
| 805 |
+
has_jac - if user has supplied function for evaluating Jacobian.
|
| 806 |
+
"""
|
| 807 |
+
|
| 808 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
| 809 |
+
"""Integrate from t=t0 to t=t1 using y0 as an initial condition.
|
| 810 |
+
Return 2-tuple (y1,t1) where y1 is the result and t=t1
|
| 811 |
+
defines the stoppage coordinate of the result.
|
| 812 |
+
"""
|
| 813 |
+
raise NotImplementedError('all integrators must define '
|
| 814 |
+
'run(f, jac, t0, t1, y0, f_params, jac_params)')
|
| 815 |
+
|
| 816 |
+
def step(self, f, jac, y0, t0, t1, f_params, jac_params):
|
| 817 |
+
"""Make one integration step and return (y1,t1)."""
|
| 818 |
+
raise NotImplementedError(f'{self.__class__.__name__} '
|
| 819 |
+
'does not support step() method')
|
| 820 |
+
|
| 821 |
+
def run_relax(self, f, jac, y0, t0, t1, f_params, jac_params):
|
| 822 |
+
"""Integrate from t=t0 to t>=t1 and return (y1,t)."""
|
| 823 |
+
raise NotImplementedError(f'{self.__class__.__name__} '
|
| 824 |
+
'does not support run_relax() method')
|
| 825 |
+
|
| 826 |
+
# XXX: __str__ method for getting visual state of the integrator
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def _vode_banded_jac_wrapper(jacfunc, ml, jac_params):
|
| 830 |
+
"""
|
| 831 |
+
Wrap a banded Jacobian function with a function that pads
|
| 832 |
+
the Jacobian with `ml` rows of zeros.
|
| 833 |
+
"""
|
| 834 |
+
|
| 835 |
+
def jac_wrapper(t, y):
|
| 836 |
+
jac = asarray(jacfunc(t, y, *jac_params))
|
| 837 |
+
padded_jac = vstack((jac, zeros((ml, jac.shape[1]))))
|
| 838 |
+
return padded_jac
|
| 839 |
+
|
| 840 |
+
return jac_wrapper
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
class vode(IntegratorBase):
|
| 844 |
+
runner = getattr(_vode, 'dvode', None)
|
| 845 |
+
|
| 846 |
+
messages = {-1: 'Excess work done on this call. (Perhaps wrong MF.)',
|
| 847 |
+
-2: 'Excess accuracy requested. (Tolerances too small.)',
|
| 848 |
+
-3: 'Illegal input detected. (See printed message.)',
|
| 849 |
+
-4: 'Repeated error test failures. (Check all input.)',
|
| 850 |
+
-5: 'Repeated convergence failures. (Perhaps bad'
|
| 851 |
+
' Jacobian supplied or wrong choice of MF or tolerances.)',
|
| 852 |
+
-6: 'Error weight became zero during problem. (Solution'
|
| 853 |
+
' component i vanished, and ATOL or ATOL(i) = 0.)'
|
| 854 |
+
}
|
| 855 |
+
supports_run_relax = 1
|
| 856 |
+
supports_step = 1
|
| 857 |
+
active_global_handle = 0
|
| 858 |
+
|
| 859 |
+
def __init__(self,
|
| 860 |
+
method='adams',
|
| 861 |
+
with_jacobian=False,
|
| 862 |
+
rtol=1e-6, atol=1e-12,
|
| 863 |
+
lband=None, uband=None,
|
| 864 |
+
order=12,
|
| 865 |
+
nsteps=500,
|
| 866 |
+
max_step=0.0, # corresponds to infinite
|
| 867 |
+
min_step=0.0,
|
| 868 |
+
first_step=0.0, # determined by solver
|
| 869 |
+
):
|
| 870 |
+
|
| 871 |
+
if re.match(method, r'adams', re.I):
|
| 872 |
+
self.meth = 1
|
| 873 |
+
elif re.match(method, r'bdf', re.I):
|
| 874 |
+
self.meth = 2
|
| 875 |
+
else:
|
| 876 |
+
raise ValueError(f'Unknown integration method {method}')
|
| 877 |
+
self.with_jacobian = with_jacobian
|
| 878 |
+
self.rtol = rtol
|
| 879 |
+
self.atol = atol
|
| 880 |
+
self.mu = uband
|
| 881 |
+
self.ml = lband
|
| 882 |
+
|
| 883 |
+
self.order = order
|
| 884 |
+
self.nsteps = nsteps
|
| 885 |
+
self.max_step = max_step
|
| 886 |
+
self.min_step = min_step
|
| 887 |
+
self.first_step = first_step
|
| 888 |
+
self.success = 1
|
| 889 |
+
|
| 890 |
+
self.initialized = False
|
| 891 |
+
|
| 892 |
+
def _determine_mf_and_set_bands(self, has_jac):
|
| 893 |
+
"""
|
| 894 |
+
Determine the `MF` parameter (Method Flag) for the Fortran subroutine `dvode`.
|
| 895 |
+
|
| 896 |
+
In the Fortran code, the legal values of `MF` are:
|
| 897 |
+
10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25,
|
| 898 |
+
-11, -12, -14, -15, -21, -22, -24, -25
|
| 899 |
+
but this Python wrapper does not use negative values.
|
| 900 |
+
|
| 901 |
+
Returns
|
| 902 |
+
|
| 903 |
+
mf = 10*self.meth + miter
|
| 904 |
+
|
| 905 |
+
self.meth is the linear multistep method:
|
| 906 |
+
self.meth == 1: method="adams"
|
| 907 |
+
self.meth == 2: method="bdf"
|
| 908 |
+
|
| 909 |
+
miter is the correction iteration method:
|
| 910 |
+
miter == 0: Functional iteration; no Jacobian involved.
|
| 911 |
+
miter == 1: Chord iteration with user-supplied full Jacobian.
|
| 912 |
+
miter == 2: Chord iteration with internally computed full Jacobian.
|
| 913 |
+
miter == 3: Chord iteration with internally computed diagonal Jacobian.
|
| 914 |
+
miter == 4: Chord iteration with user-supplied banded Jacobian.
|
| 915 |
+
miter == 5: Chord iteration with internally computed banded Jacobian.
|
| 916 |
+
|
| 917 |
+
Side effects: If either self.mu or self.ml is not None and the other is None,
|
| 918 |
+
then the one that is None is set to 0.
|
| 919 |
+
"""
|
| 920 |
+
|
| 921 |
+
jac_is_banded = self.mu is not None or self.ml is not None
|
| 922 |
+
if jac_is_banded:
|
| 923 |
+
if self.mu is None:
|
| 924 |
+
self.mu = 0
|
| 925 |
+
if self.ml is None:
|
| 926 |
+
self.ml = 0
|
| 927 |
+
|
| 928 |
+
# has_jac is True if the user provided a Jacobian function.
|
| 929 |
+
if has_jac:
|
| 930 |
+
if jac_is_banded:
|
| 931 |
+
miter = 4
|
| 932 |
+
else:
|
| 933 |
+
miter = 1
|
| 934 |
+
else:
|
| 935 |
+
if jac_is_banded:
|
| 936 |
+
if self.ml == self.mu == 0:
|
| 937 |
+
miter = 3 # Chord iteration with internal diagonal Jacobian.
|
| 938 |
+
else:
|
| 939 |
+
miter = 5 # Chord iteration with internal banded Jacobian.
|
| 940 |
+
else:
|
| 941 |
+
# self.with_jacobian is set by the user in
|
| 942 |
+
# the call to ode.set_integrator.
|
| 943 |
+
if self.with_jacobian:
|
| 944 |
+
miter = 2 # Chord iteration with internal full Jacobian.
|
| 945 |
+
else:
|
| 946 |
+
miter = 0 # Functional iteration; no Jacobian involved.
|
| 947 |
+
|
| 948 |
+
mf = 10 * self.meth + miter
|
| 949 |
+
return mf
|
| 950 |
+
|
| 951 |
+
def reset(self, n, has_jac):
|
| 952 |
+
mf = self._determine_mf_and_set_bands(has_jac)
|
| 953 |
+
|
| 954 |
+
if mf == 10:
|
| 955 |
+
lrw = 20 + 16 * n
|
| 956 |
+
elif mf in [11, 12]:
|
| 957 |
+
lrw = 22 + 16 * n + 2 * n * n
|
| 958 |
+
elif mf == 13:
|
| 959 |
+
lrw = 22 + 17 * n
|
| 960 |
+
elif mf in [14, 15]:
|
| 961 |
+
lrw = 22 + 18 * n + (3 * self.ml + 2 * self.mu) * n
|
| 962 |
+
elif mf == 20:
|
| 963 |
+
lrw = 20 + 9 * n
|
| 964 |
+
elif mf in [21, 22]:
|
| 965 |
+
lrw = 22 + 9 * n + 2 * n * n
|
| 966 |
+
elif mf == 23:
|
| 967 |
+
lrw = 22 + 10 * n
|
| 968 |
+
elif mf in [24, 25]:
|
| 969 |
+
lrw = 22 + 11 * n + (3 * self.ml + 2 * self.mu) * n
|
| 970 |
+
else:
|
| 971 |
+
raise ValueError(f'Unexpected mf={mf}')
|
| 972 |
+
|
| 973 |
+
if mf % 10 in [0, 3]:
|
| 974 |
+
liw = 30
|
| 975 |
+
else:
|
| 976 |
+
liw = 30 + n
|
| 977 |
+
|
| 978 |
+
rwork = zeros((lrw,), float)
|
| 979 |
+
rwork[4] = self.first_step
|
| 980 |
+
rwork[5] = self.max_step
|
| 981 |
+
rwork[6] = self.min_step
|
| 982 |
+
self.rwork = rwork
|
| 983 |
+
|
| 984 |
+
iwork = zeros((liw,), _vode_int_dtype)
|
| 985 |
+
if self.ml is not None:
|
| 986 |
+
iwork[0] = self.ml
|
| 987 |
+
if self.mu is not None:
|
| 988 |
+
iwork[1] = self.mu
|
| 989 |
+
iwork[4] = self.order
|
| 990 |
+
iwork[5] = self.nsteps
|
| 991 |
+
iwork[6] = 2 # mxhnil
|
| 992 |
+
self.iwork = iwork
|
| 993 |
+
|
| 994 |
+
self.call_args = [self.rtol, self.atol, 1, 1,
|
| 995 |
+
self.rwork, self.iwork, mf]
|
| 996 |
+
self.success = 1
|
| 997 |
+
self.initialized = False
|
| 998 |
+
|
| 999 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
| 1000 |
+
if self.initialized:
|
| 1001 |
+
self.check_handle()
|
| 1002 |
+
else:
|
| 1003 |
+
self.initialized = True
|
| 1004 |
+
self.acquire_new_handle()
|
| 1005 |
+
|
| 1006 |
+
if self.ml is not None and self.ml > 0:
|
| 1007 |
+
# Banded Jacobian. Wrap the user-provided function with one
|
| 1008 |
+
# that pads the Jacobian array with the extra `self.ml` rows
|
| 1009 |
+
# required by the f2py-generated wrapper.
|
| 1010 |
+
jac = _vode_banded_jac_wrapper(jac, self.ml, jac_params)
|
| 1011 |
+
|
| 1012 |
+
args = ((f, jac, y0, t0, t1) + tuple(self.call_args) +
|
| 1013 |
+
(f_params, jac_params))
|
| 1014 |
+
|
| 1015 |
+
with VODE_LOCK:
|
| 1016 |
+
y1, t, istate = self.runner(*args)
|
| 1017 |
+
|
| 1018 |
+
self.istate = istate
|
| 1019 |
+
if istate < 0:
|
| 1020 |
+
unexpected_istate_msg = f'Unexpected istate={istate:d}'
|
| 1021 |
+
warnings.warn(f'{self.__class__.__name__:s}: '
|
| 1022 |
+
f'{self.messages.get(istate, unexpected_istate_msg):s}',
|
| 1023 |
+
stacklevel=2)
|
| 1024 |
+
self.success = 0
|
| 1025 |
+
else:
|
| 1026 |
+
self.call_args[3] = 2 # upgrade istate from 1 to 2
|
| 1027 |
+
self.istate = 2
|
| 1028 |
+
return y1, t
|
| 1029 |
+
|
| 1030 |
+
def step(self, *args):
|
| 1031 |
+
itask = self.call_args[2]
|
| 1032 |
+
self.call_args[2] = 2
|
| 1033 |
+
r = self.run(*args)
|
| 1034 |
+
self.call_args[2] = itask
|
| 1035 |
+
return r
|
| 1036 |
+
|
| 1037 |
+
def run_relax(self, *args):
|
| 1038 |
+
itask = self.call_args[2]
|
| 1039 |
+
self.call_args[2] = 3
|
| 1040 |
+
r = self.run(*args)
|
| 1041 |
+
self.call_args[2] = itask
|
| 1042 |
+
return r
|
| 1043 |
+
|
| 1044 |
+
|
| 1045 |
+
if vode.runner is not None:
|
| 1046 |
+
IntegratorBase.integrator_classes.append(vode)
|
| 1047 |
+
|
| 1048 |
+
|
| 1049 |
+
class zvode(vode):
|
| 1050 |
+
runner = getattr(_vode, 'zvode', None)
|
| 1051 |
+
|
| 1052 |
+
supports_run_relax = 1
|
| 1053 |
+
supports_step = 1
|
| 1054 |
+
scalar = complex
|
| 1055 |
+
active_global_handle = 0
|
| 1056 |
+
|
| 1057 |
+
def reset(self, n, has_jac):
|
| 1058 |
+
mf = self._determine_mf_and_set_bands(has_jac)
|
| 1059 |
+
|
| 1060 |
+
if mf in (10,):
|
| 1061 |
+
lzw = 15 * n
|
| 1062 |
+
elif mf in (11, 12):
|
| 1063 |
+
lzw = 15 * n + 2 * n ** 2
|
| 1064 |
+
elif mf in (-11, -12):
|
| 1065 |
+
lzw = 15 * n + n ** 2
|
| 1066 |
+
elif mf in (13,):
|
| 1067 |
+
lzw = 16 * n
|
| 1068 |
+
elif mf in (14, 15):
|
| 1069 |
+
lzw = 17 * n + (3 * self.ml + 2 * self.mu) * n
|
| 1070 |
+
elif mf in (-14, -15):
|
| 1071 |
+
lzw = 16 * n + (2 * self.ml + self.mu) * n
|
| 1072 |
+
elif mf in (20,):
|
| 1073 |
+
lzw = 8 * n
|
| 1074 |
+
elif mf in (21, 22):
|
| 1075 |
+
lzw = 8 * n + 2 * n ** 2
|
| 1076 |
+
elif mf in (-21, -22):
|
| 1077 |
+
lzw = 8 * n + n ** 2
|
| 1078 |
+
elif mf in (23,):
|
| 1079 |
+
lzw = 9 * n
|
| 1080 |
+
elif mf in (24, 25):
|
| 1081 |
+
lzw = 10 * n + (3 * self.ml + 2 * self.mu) * n
|
| 1082 |
+
elif mf in (-24, -25):
|
| 1083 |
+
lzw = 9 * n + (2 * self.ml + self.mu) * n
|
| 1084 |
+
|
| 1085 |
+
lrw = 20 + n
|
| 1086 |
+
|
| 1087 |
+
if mf % 10 in (0, 3):
|
| 1088 |
+
liw = 30
|
| 1089 |
+
else:
|
| 1090 |
+
liw = 30 + n
|
| 1091 |
+
|
| 1092 |
+
zwork = zeros((lzw,), complex)
|
| 1093 |
+
self.zwork = zwork
|
| 1094 |
+
|
| 1095 |
+
rwork = zeros((lrw,), float)
|
| 1096 |
+
rwork[4] = self.first_step
|
| 1097 |
+
rwork[5] = self.max_step
|
| 1098 |
+
rwork[6] = self.min_step
|
| 1099 |
+
self.rwork = rwork
|
| 1100 |
+
|
| 1101 |
+
iwork = zeros((liw,), _vode_int_dtype)
|
| 1102 |
+
if self.ml is not None:
|
| 1103 |
+
iwork[0] = self.ml
|
| 1104 |
+
if self.mu is not None:
|
| 1105 |
+
iwork[1] = self.mu
|
| 1106 |
+
iwork[4] = self.order
|
| 1107 |
+
iwork[5] = self.nsteps
|
| 1108 |
+
iwork[6] = 2 # mxhnil
|
| 1109 |
+
self.iwork = iwork
|
| 1110 |
+
|
| 1111 |
+
self.call_args = [self.rtol, self.atol, 1, 1,
|
| 1112 |
+
self.zwork, self.rwork, self.iwork, mf]
|
| 1113 |
+
self.success = 1
|
| 1114 |
+
self.initialized = False
|
| 1115 |
+
|
| 1116 |
+
|
| 1117 |
+
if zvode.runner is not None:
|
| 1118 |
+
IntegratorBase.integrator_classes.append(zvode)
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
class dopri5(IntegratorBase):
|
| 1122 |
+
runner = getattr(_dop, 'dopri5', None)
|
| 1123 |
+
name = 'dopri5'
|
| 1124 |
+
supports_solout = True
|
| 1125 |
+
|
| 1126 |
+
messages = {1: 'computation successful',
|
| 1127 |
+
2: 'computation successful (interrupted by solout)',
|
| 1128 |
+
-1: 'input is not consistent',
|
| 1129 |
+
-2: 'larger nsteps is needed',
|
| 1130 |
+
-3: 'step size becomes too small',
|
| 1131 |
+
-4: 'problem is probably stiff (interrupted)',
|
| 1132 |
+
}
|
| 1133 |
+
|
| 1134 |
+
def __init__(self,
|
| 1135 |
+
rtol=1e-6, atol=1e-12,
|
| 1136 |
+
nsteps=500,
|
| 1137 |
+
max_step=0.0,
|
| 1138 |
+
first_step=0.0, # determined by solver
|
| 1139 |
+
safety=0.9,
|
| 1140 |
+
ifactor=10.0,
|
| 1141 |
+
dfactor=0.2,
|
| 1142 |
+
beta=0.0,
|
| 1143 |
+
method=None,
|
| 1144 |
+
verbosity=-1, # no messages if negative
|
| 1145 |
+
):
|
| 1146 |
+
self.rtol = rtol
|
| 1147 |
+
self.atol = atol
|
| 1148 |
+
self.nsteps = nsteps
|
| 1149 |
+
self.max_step = max_step
|
| 1150 |
+
self.first_step = first_step
|
| 1151 |
+
self.safety = safety
|
| 1152 |
+
self.ifactor = ifactor
|
| 1153 |
+
self.dfactor = dfactor
|
| 1154 |
+
self.beta = beta
|
| 1155 |
+
self.verbosity = verbosity
|
| 1156 |
+
self.success = 1
|
| 1157 |
+
self.set_solout(None)
|
| 1158 |
+
|
| 1159 |
+
def set_solout(self, solout, complex=False):
|
| 1160 |
+
self.solout = solout
|
| 1161 |
+
self.solout_cmplx = complex
|
| 1162 |
+
if solout is None:
|
| 1163 |
+
self.iout = 0
|
| 1164 |
+
else:
|
| 1165 |
+
self.iout = 1
|
| 1166 |
+
|
| 1167 |
+
def reset(self, n, has_jac):
|
| 1168 |
+
work = zeros((8 * n + 21,), float)
|
| 1169 |
+
work[1] = self.safety
|
| 1170 |
+
work[2] = self.dfactor
|
| 1171 |
+
work[3] = self.ifactor
|
| 1172 |
+
work[4] = self.beta
|
| 1173 |
+
work[5] = self.max_step
|
| 1174 |
+
work[6] = self.first_step
|
| 1175 |
+
self.work = work
|
| 1176 |
+
iwork = zeros((21,), _dop_int_dtype)
|
| 1177 |
+
iwork[0] = self.nsteps
|
| 1178 |
+
iwork[2] = self.verbosity
|
| 1179 |
+
self.iwork = iwork
|
| 1180 |
+
self.call_args = [self.rtol, self.atol, self._solout,
|
| 1181 |
+
self.iout, self.work, self.iwork]
|
| 1182 |
+
self.success = 1
|
| 1183 |
+
|
| 1184 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
| 1185 |
+
x, y, iwork, istate = self.runner(*((f, t0, y0, t1) +
|
| 1186 |
+
tuple(self.call_args) + (f_params,)))
|
| 1187 |
+
self.istate = istate
|
| 1188 |
+
if istate < 0:
|
| 1189 |
+
unexpected_istate_msg = f'Unexpected istate={istate:d}'
|
| 1190 |
+
warnings.warn(f'{self.__class__.__name__:s}: '
|
| 1191 |
+
f'{self.messages.get(istate, unexpected_istate_msg):s}',
|
| 1192 |
+
stacklevel=2)
|
| 1193 |
+
self.success = 0
|
| 1194 |
+
return y, x
|
| 1195 |
+
|
| 1196 |
+
def _solout(self, nr, xold, x, y, nd, icomp, con):
|
| 1197 |
+
if self.solout is not None:
|
| 1198 |
+
if self.solout_cmplx:
|
| 1199 |
+
y = y[::2] + 1j * y[1::2]
|
| 1200 |
+
return self.solout(x, y)
|
| 1201 |
+
else:
|
| 1202 |
+
return 1
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
if dopri5.runner is not None:
|
| 1206 |
+
IntegratorBase.integrator_classes.append(dopri5)
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
class dop853(dopri5):
|
| 1210 |
+
runner = getattr(_dop, 'dop853', None)
|
| 1211 |
+
name = 'dop853'
|
| 1212 |
+
|
| 1213 |
+
def __init__(self,
|
| 1214 |
+
rtol=1e-6, atol=1e-12,
|
| 1215 |
+
nsteps=500,
|
| 1216 |
+
max_step=0.0,
|
| 1217 |
+
first_step=0.0, # determined by solver
|
| 1218 |
+
safety=0.9,
|
| 1219 |
+
ifactor=6.0,
|
| 1220 |
+
dfactor=0.3,
|
| 1221 |
+
beta=0.0,
|
| 1222 |
+
method=None,
|
| 1223 |
+
verbosity=-1, # no messages if negative
|
| 1224 |
+
):
|
| 1225 |
+
super().__init__(rtol, atol, nsteps, max_step, first_step, safety,
|
| 1226 |
+
ifactor, dfactor, beta, method, verbosity)
|
| 1227 |
+
|
| 1228 |
+
def reset(self, n, has_jac):
|
| 1229 |
+
work = zeros((11 * n + 21,), float)
|
| 1230 |
+
work[1] = self.safety
|
| 1231 |
+
work[2] = self.dfactor
|
| 1232 |
+
work[3] = self.ifactor
|
| 1233 |
+
work[4] = self.beta
|
| 1234 |
+
work[5] = self.max_step
|
| 1235 |
+
work[6] = self.first_step
|
| 1236 |
+
self.work = work
|
| 1237 |
+
iwork = zeros((21,), _dop_int_dtype)
|
| 1238 |
+
iwork[0] = self.nsteps
|
| 1239 |
+
iwork[2] = self.verbosity
|
| 1240 |
+
self.iwork = iwork
|
| 1241 |
+
self.call_args = [self.rtol, self.atol, self._solout,
|
| 1242 |
+
self.iout, self.work, self.iwork]
|
| 1243 |
+
self.success = 1
|
| 1244 |
+
|
| 1245 |
+
|
| 1246 |
+
if dop853.runner is not None:
|
| 1247 |
+
IntegratorBase.integrator_classes.append(dop853)
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
class lsoda(IntegratorBase):
|
| 1251 |
+
runner = getattr(_lsoda, 'lsoda', None)
|
| 1252 |
+
active_global_handle = 0
|
| 1253 |
+
|
| 1254 |
+
messages = {
|
| 1255 |
+
2: "Integration successful.",
|
| 1256 |
+
-1: "Excess work done on this call (perhaps wrong Dfun type).",
|
| 1257 |
+
-2: "Excess accuracy requested (tolerances too small).",
|
| 1258 |
+
-3: "Illegal input detected (internal error).",
|
| 1259 |
+
-4: "Repeated error test failures (internal error).",
|
| 1260 |
+
-5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
|
| 1261 |
+
-6: "Error weight became zero during problem.",
|
| 1262 |
+
-7: "Internal workspace insufficient to finish (internal error)."
|
| 1263 |
+
}
|
| 1264 |
+
|
| 1265 |
+
def __init__(self,
|
| 1266 |
+
with_jacobian=False,
|
| 1267 |
+
rtol=1e-6, atol=1e-12,
|
| 1268 |
+
lband=None, uband=None,
|
| 1269 |
+
nsteps=500,
|
| 1270 |
+
max_step=0.0, # corresponds to infinite
|
| 1271 |
+
min_step=0.0,
|
| 1272 |
+
first_step=0.0, # determined by solver
|
| 1273 |
+
ixpr=0,
|
| 1274 |
+
max_hnil=0,
|
| 1275 |
+
max_order_ns=12,
|
| 1276 |
+
max_order_s=5,
|
| 1277 |
+
method=None
|
| 1278 |
+
):
|
| 1279 |
+
|
| 1280 |
+
self.with_jacobian = with_jacobian
|
| 1281 |
+
self.rtol = rtol
|
| 1282 |
+
self.atol = atol
|
| 1283 |
+
self.mu = uband
|
| 1284 |
+
self.ml = lband
|
| 1285 |
+
|
| 1286 |
+
self.max_order_ns = max_order_ns
|
| 1287 |
+
self.max_order_s = max_order_s
|
| 1288 |
+
self.nsteps = nsteps
|
| 1289 |
+
self.max_step = max_step
|
| 1290 |
+
self.min_step = min_step
|
| 1291 |
+
self.first_step = first_step
|
| 1292 |
+
self.ixpr = ixpr
|
| 1293 |
+
self.max_hnil = max_hnil
|
| 1294 |
+
self.success = 1
|
| 1295 |
+
|
| 1296 |
+
self.initialized = False
|
| 1297 |
+
|
| 1298 |
+
def reset(self, n, has_jac):
|
| 1299 |
+
# Calculate parameters for Fortran subroutine dvode.
|
| 1300 |
+
if has_jac:
|
| 1301 |
+
if self.mu is None and self.ml is None:
|
| 1302 |
+
jt = 1
|
| 1303 |
+
else:
|
| 1304 |
+
if self.mu is None:
|
| 1305 |
+
self.mu = 0
|
| 1306 |
+
if self.ml is None:
|
| 1307 |
+
self.ml = 0
|
| 1308 |
+
jt = 4
|
| 1309 |
+
else:
|
| 1310 |
+
if self.mu is None and self.ml is None:
|
| 1311 |
+
jt = 2
|
| 1312 |
+
else:
|
| 1313 |
+
if self.mu is None:
|
| 1314 |
+
self.mu = 0
|
| 1315 |
+
if self.ml is None:
|
| 1316 |
+
self.ml = 0
|
| 1317 |
+
jt = 5
|
| 1318 |
+
lrn = 20 + (self.max_order_ns + 4) * n
|
| 1319 |
+
if jt in [1, 2]:
|
| 1320 |
+
lrs = 22 + (self.max_order_s + 4) * n + n * n
|
| 1321 |
+
elif jt in [4, 5]:
|
| 1322 |
+
lrs = 22 + (self.max_order_s + 5 + 2 * self.ml + self.mu) * n
|
| 1323 |
+
else:
|
| 1324 |
+
raise ValueError(f'Unexpected jt={jt}')
|
| 1325 |
+
lrw = max(lrn, lrs)
|
| 1326 |
+
liw = 20 + n
|
| 1327 |
+
rwork = zeros((lrw,), float)
|
| 1328 |
+
rwork[4] = self.first_step
|
| 1329 |
+
rwork[5] = self.max_step
|
| 1330 |
+
rwork[6] = self.min_step
|
| 1331 |
+
self.rwork = rwork
|
| 1332 |
+
iwork = zeros((liw,), _lsoda_int_dtype)
|
| 1333 |
+
if self.ml is not None:
|
| 1334 |
+
iwork[0] = self.ml
|
| 1335 |
+
if self.mu is not None:
|
| 1336 |
+
iwork[1] = self.mu
|
| 1337 |
+
iwork[4] = self.ixpr
|
| 1338 |
+
iwork[5] = self.nsteps
|
| 1339 |
+
iwork[6] = self.max_hnil
|
| 1340 |
+
iwork[7] = self.max_order_ns
|
| 1341 |
+
iwork[8] = self.max_order_s
|
| 1342 |
+
self.iwork = iwork
|
| 1343 |
+
self.call_args = [self.rtol, self.atol, 1, 1,
|
| 1344 |
+
self.rwork, self.iwork, jt]
|
| 1345 |
+
self.success = 1
|
| 1346 |
+
self.initialized = False
|
| 1347 |
+
|
| 1348 |
+
def run(self, f, jac, y0, t0, t1, f_params, jac_params):
|
| 1349 |
+
if self.initialized:
|
| 1350 |
+
self.check_handle()
|
| 1351 |
+
else:
|
| 1352 |
+
self.initialized = True
|
| 1353 |
+
self.acquire_new_handle()
|
| 1354 |
+
args = [f, y0, t0, t1] + self.call_args[:-1] + \
|
| 1355 |
+
[jac, self.call_args[-1], f_params, 0, jac_params]
|
| 1356 |
+
|
| 1357 |
+
with LSODA_LOCK:
|
| 1358 |
+
y1, t, istate = self.runner(*args)
|
| 1359 |
+
|
| 1360 |
+
self.istate = istate
|
| 1361 |
+
if istate < 0:
|
| 1362 |
+
unexpected_istate_msg = f'Unexpected istate={istate:d}'
|
| 1363 |
+
warnings.warn(f'{self.__class__.__name__:s}: '
|
| 1364 |
+
f'{self.messages.get(istate, unexpected_istate_msg):s}',
|
| 1365 |
+
stacklevel=2)
|
| 1366 |
+
self.success = 0
|
| 1367 |
+
else:
|
| 1368 |
+
self.call_args[3] = 2 # upgrade istate from 1 to 2
|
| 1369 |
+
self.istate = 2
|
| 1370 |
+
return y1, t
|
| 1371 |
+
|
| 1372 |
+
def step(self, *args):
|
| 1373 |
+
itask = self.call_args[2]
|
| 1374 |
+
self.call_args[2] = 2
|
| 1375 |
+
r = self.run(*args)
|
| 1376 |
+
self.call_args[2] = itask
|
| 1377 |
+
return r
|
| 1378 |
+
|
| 1379 |
+
def run_relax(self, *args):
|
| 1380 |
+
itask = self.call_args[2]
|
| 1381 |
+
self.call_args[2] = 3
|
| 1382 |
+
r = self.run(*args)
|
| 1383 |
+
self.call_args[2] = itask
|
| 1384 |
+
return r
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
if lsoda.runner:
|
| 1388 |
+
IntegratorBase.integrator_classes.append(lsoda)
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from threading import Lock
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ODE_LOCK = Lock()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ODEintWarning(Warning):
|
| 17 |
+
"""Warning raised during the execution of `odeint`."""
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
_msgs = {2: "Integration successful.",
|
| 22 |
+
1: "Nothing was done; the integration time was 0.",
|
| 23 |
+
-1: "Excess work done on this call (perhaps wrong Dfun type).",
|
| 24 |
+
-2: "Excess accuracy requested (tolerances too small).",
|
| 25 |
+
-3: "Illegal input detected (internal error).",
|
| 26 |
+
-4: "Repeated error test failures (internal error).",
|
| 27 |
+
-5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
|
| 28 |
+
-6: "Error weight became zero during problem.",
|
| 29 |
+
-7: "Internal workspace insufficient to finish (internal error).",
|
| 30 |
+
-8: "Run terminated (internal error)."
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
|
| 35 |
+
ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
|
| 36 |
+
hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
|
| 37 |
+
mxords=5, printmessg=0, tfirst=False):
|
| 38 |
+
"""
|
| 39 |
+
Integrate a system of ordinary differential equations.
|
| 40 |
+
|
| 41 |
+
.. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
|
| 42 |
+
differential equation.
|
| 43 |
+
|
| 44 |
+
Solve a system of ordinary differential equations using lsoda from the
|
| 45 |
+
FORTRAN library odepack.
|
| 46 |
+
|
| 47 |
+
Solves the initial value problem for stiff or non-stiff systems
|
| 48 |
+
of first order ode-s::
|
| 49 |
+
|
| 50 |
+
dy/dt = func(y, t, ...) [or func(t, y, ...)]
|
| 51 |
+
|
| 52 |
+
where y can be a vector.
|
| 53 |
+
|
| 54 |
+
.. note:: By default, the required order of the first two arguments of
|
| 55 |
+
`func` are in the opposite order of the arguments in the system
|
| 56 |
+
definition function used by the `scipy.integrate.ode` class and
|
| 57 |
+
the function `scipy.integrate.solve_ivp`. To use a function with
|
| 58 |
+
the signature ``func(t, y, ...)``, the argument `tfirst` must be
|
| 59 |
+
set to ``True``.
|
| 60 |
+
|
| 61 |
+
Parameters
|
| 62 |
+
----------
|
| 63 |
+
func : callable(y, t, ...) or callable(t, y, ...)
|
| 64 |
+
Computes the derivative of y at t.
|
| 65 |
+
If the signature is ``callable(t, y, ...)``, then the argument
|
| 66 |
+
`tfirst` must be set ``True``.
|
| 67 |
+
`func` must not modify the data in `y`, as it is a
|
| 68 |
+
view of the data used internally by the ODE solver.
|
| 69 |
+
y0 : array
|
| 70 |
+
Initial condition on y (can be a vector).
|
| 71 |
+
t : array
|
| 72 |
+
A sequence of time points for which to solve for y. The initial
|
| 73 |
+
value point should be the first element of this sequence.
|
| 74 |
+
This sequence must be monotonically increasing or monotonically
|
| 75 |
+
decreasing; repeated values are allowed.
|
| 76 |
+
args : tuple, optional
|
| 77 |
+
Extra arguments to pass to function.
|
| 78 |
+
Dfun : callable(y, t, ...) or callable(t, y, ...)
|
| 79 |
+
Gradient (Jacobian) of `func`.
|
| 80 |
+
If the signature is ``callable(t, y, ...)``, then the argument
|
| 81 |
+
`tfirst` must be set ``True``.
|
| 82 |
+
`Dfun` must not modify the data in `y`, as it is a
|
| 83 |
+
view of the data used internally by the ODE solver.
|
| 84 |
+
col_deriv : bool, optional
|
| 85 |
+
True if `Dfun` defines derivatives down columns (faster),
|
| 86 |
+
otherwise `Dfun` should define derivatives across rows.
|
| 87 |
+
full_output : bool, optional
|
| 88 |
+
True if to return a dictionary of optional outputs as the second output
|
| 89 |
+
printmessg : bool, optional
|
| 90 |
+
Whether to print the convergence message
|
| 91 |
+
tfirst : bool, optional
|
| 92 |
+
If True, the first two arguments of `func` (and `Dfun`, if given)
|
| 93 |
+
must ``t, y`` instead of the default ``y, t``.
|
| 94 |
+
|
| 95 |
+
.. versionadded:: 1.1.0
|
| 96 |
+
|
| 97 |
+
Returns
|
| 98 |
+
-------
|
| 99 |
+
y : array, shape (len(t), len(y0))
|
| 100 |
+
Array containing the value of y for each desired time in t,
|
| 101 |
+
with the initial value `y0` in the first row.
|
| 102 |
+
infodict : dict, only returned if full_output == True
|
| 103 |
+
Dictionary containing additional output information
|
| 104 |
+
|
| 105 |
+
======= ============================================================
|
| 106 |
+
key meaning
|
| 107 |
+
======= ============================================================
|
| 108 |
+
'hu' vector of step sizes successfully used for each time step
|
| 109 |
+
'tcur' vector with the value of t reached for each time step
|
| 110 |
+
(will always be at least as large as the input times)
|
| 111 |
+
'tolsf' vector of tolerance scale factors, greater than 1.0,
|
| 112 |
+
computed when a request for too much accuracy was detected
|
| 113 |
+
'tsw' value of t at the time of the last method switch
|
| 114 |
+
(given for each time step)
|
| 115 |
+
'nst' cumulative number of time steps
|
| 116 |
+
'nfe' cumulative number of function evaluations for each time step
|
| 117 |
+
'nje' cumulative number of jacobian evaluations for each time step
|
| 118 |
+
'nqu' a vector of method orders for each successful step
|
| 119 |
+
'imxer' index of the component of largest magnitude in the
|
| 120 |
+
weighted local error vector (e / ewt) on an error return, -1
|
| 121 |
+
otherwise
|
| 122 |
+
'lenrw' the length of the double work array required
|
| 123 |
+
'leniw' the length of integer work array required
|
| 124 |
+
'mused' a vector of method indicators for each successful time step:
|
| 125 |
+
1: adams (nonstiff), 2: bdf (stiff)
|
| 126 |
+
======= ============================================================
|
| 127 |
+
|
| 128 |
+
Other Parameters
|
| 129 |
+
----------------
|
| 130 |
+
ml, mu : int, optional
|
| 131 |
+
If either of these are not None or non-negative, then the
|
| 132 |
+
Jacobian is assumed to be banded. These give the number of
|
| 133 |
+
lower and upper non-zero diagonals in this banded matrix.
|
| 134 |
+
For the banded case, `Dfun` should return a matrix whose
|
| 135 |
+
rows contain the non-zero bands (starting with the lowest diagonal).
|
| 136 |
+
Thus, the return matrix `jac` from `Dfun` should have shape
|
| 137 |
+
``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
|
| 138 |
+
The data in `jac` must be stored such that ``jac[i - j + mu, j]``
|
| 139 |
+
holds the derivative of the ``i``\\ th equation with respect to the
|
| 140 |
+
``j``\\ th state variable. If `col_deriv` is True, the transpose of
|
| 141 |
+
this `jac` must be returned.
|
| 142 |
+
rtol, atol : float, optional
|
| 143 |
+
The input parameters `rtol` and `atol` determine the error
|
| 144 |
+
control performed by the solver. The solver will control the
|
| 145 |
+
vector, e, of estimated local errors in y, according to an
|
| 146 |
+
inequality of the form ``max-norm of (e / ewt) <= 1``,
|
| 147 |
+
where ewt is a vector of positive error weights computed as
|
| 148 |
+
``ewt = rtol * abs(y) + atol``.
|
| 149 |
+
rtol and atol can be either vectors the same length as y or scalars.
|
| 150 |
+
Defaults to 1.49012e-8.
|
| 151 |
+
tcrit : ndarray, optional
|
| 152 |
+
Vector of critical points (e.g., singularities) where integration
|
| 153 |
+
care should be taken.
|
| 154 |
+
h0 : float, (0: solver-determined), optional
|
| 155 |
+
The step size to be attempted on the first step.
|
| 156 |
+
hmax : float, (0: solver-determined), optional
|
| 157 |
+
The maximum absolute step size allowed.
|
| 158 |
+
hmin : float, (0: solver-determined), optional
|
| 159 |
+
The minimum absolute step size allowed.
|
| 160 |
+
ixpr : bool, optional
|
| 161 |
+
Whether to generate extra printing at method switches.
|
| 162 |
+
mxstep : int, (0: solver-determined), optional
|
| 163 |
+
Maximum number of (internally defined) steps allowed for each
|
| 164 |
+
integration point in t.
|
| 165 |
+
mxhnil : int, (0: solver-determined), optional
|
| 166 |
+
Maximum number of messages printed.
|
| 167 |
+
mxordn : int, (0: solver-determined), optional
|
| 168 |
+
Maximum order to be allowed for the non-stiff (Adams) method.
|
| 169 |
+
mxords : int, (0: solver-determined), optional
|
| 170 |
+
Maximum order to be allowed for the stiff (BDF) method.
|
| 171 |
+
|
| 172 |
+
See Also
|
| 173 |
+
--------
|
| 174 |
+
solve_ivp : solve an initial value problem for a system of ODEs
|
| 175 |
+
ode : a more object-oriented integrator based on VODE
|
| 176 |
+
quad : for finding the area under a curve
|
| 177 |
+
|
| 178 |
+
Examples
|
| 179 |
+
--------
|
| 180 |
+
The second order differential equation for the angle `theta` of a
|
| 181 |
+
pendulum acted on by gravity with friction can be written::
|
| 182 |
+
|
| 183 |
+
theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
|
| 184 |
+
|
| 185 |
+
where `b` and `c` are positive constants, and a prime (') denotes a
|
| 186 |
+
derivative. To solve this equation with `odeint`, we must first convert
|
| 187 |
+
it to a system of first order equations. By defining the angular
|
| 188 |
+
velocity ``omega(t) = theta'(t)``, we obtain the system::
|
| 189 |
+
|
| 190 |
+
theta'(t) = omega(t)
|
| 191 |
+
omega'(t) = -b*omega(t) - c*sin(theta(t))
|
| 192 |
+
|
| 193 |
+
Let `y` be the vector [`theta`, `omega`]. We implement this system
|
| 194 |
+
in Python as:
|
| 195 |
+
|
| 196 |
+
>>> import numpy as np
|
| 197 |
+
>>> def pend(y, t, b, c):
|
| 198 |
+
... theta, omega = y
|
| 199 |
+
... dydt = [omega, -b*omega - c*np.sin(theta)]
|
| 200 |
+
... return dydt
|
| 201 |
+
...
|
| 202 |
+
|
| 203 |
+
We assume the constants are `b` = 0.25 and `c` = 5.0:
|
| 204 |
+
|
| 205 |
+
>>> b = 0.25
|
| 206 |
+
>>> c = 5.0
|
| 207 |
+
|
| 208 |
+
For initial conditions, we assume the pendulum is nearly vertical
|
| 209 |
+
with `theta(0)` = `pi` - 0.1, and is initially at rest, so
|
| 210 |
+
`omega(0)` = 0. Then the vector of initial conditions is
|
| 211 |
+
|
| 212 |
+
>>> y0 = [np.pi - 0.1, 0.0]
|
| 213 |
+
|
| 214 |
+
We will generate a solution at 101 evenly spaced samples in the interval
|
| 215 |
+
0 <= `t` <= 10. So our array of times is:
|
| 216 |
+
|
| 217 |
+
>>> t = np.linspace(0, 10, 101)
|
| 218 |
+
|
| 219 |
+
Call `odeint` to generate the solution. To pass the parameters
|
| 220 |
+
`b` and `c` to `pend`, we give them to `odeint` using the `args`
|
| 221 |
+
argument.
|
| 222 |
+
|
| 223 |
+
>>> from scipy.integrate import odeint
|
| 224 |
+
>>> sol = odeint(pend, y0, t, args=(b, c))
|
| 225 |
+
|
| 226 |
+
The solution is an array with shape (101, 2). The first column
|
| 227 |
+
is `theta(t)`, and the second is `omega(t)`. The following code
|
| 228 |
+
plots both components.
|
| 229 |
+
|
| 230 |
+
>>> import matplotlib.pyplot as plt
|
| 231 |
+
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
|
| 232 |
+
>>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
|
| 233 |
+
>>> plt.legend(loc='best')
|
| 234 |
+
>>> plt.xlabel('t')
|
| 235 |
+
>>> plt.grid()
|
| 236 |
+
>>> plt.show()
|
| 237 |
+
"""
|
| 238 |
+
|
| 239 |
+
if ml is None:
|
| 240 |
+
ml = -1 # changed to zero inside function call
|
| 241 |
+
if mu is None:
|
| 242 |
+
mu = -1 # changed to zero inside function call
|
| 243 |
+
|
| 244 |
+
dt = np.diff(t)
|
| 245 |
+
if not ((dt >= 0).all() or (dt <= 0).all()):
|
| 246 |
+
raise ValueError("The values in t must be monotonically increasing "
|
| 247 |
+
"or monotonically decreasing; repeated values are "
|
| 248 |
+
"allowed.")
|
| 249 |
+
|
| 250 |
+
t = copy(t)
|
| 251 |
+
y0 = copy(y0)
|
| 252 |
+
|
| 253 |
+
with ODE_LOCK:
|
| 254 |
+
output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
|
| 255 |
+
full_output, rtol, atol, tcrit, h0, hmax, hmin,
|
| 256 |
+
ixpr, mxstep, mxhnil, mxordn, mxords,
|
| 257 |
+
int(bool(tfirst)))
|
| 258 |
+
if output[-1] < 0:
|
| 259 |
+
warning_msg = (f"{_msgs[output[-1]]} Run with full_output = 1 to "
|
| 260 |
+
f"get quantitative information.")
|
| 261 |
+
warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
|
| 262 |
+
elif printmessg:
|
| 263 |
+
warning_msg = _msgs[output[-1]]
|
| 264 |
+
warnings.warn(warning_msg, ODEintWarning, stacklevel=2)
|
| 265 |
+
|
| 266 |
+
if full_output:
|
| 267 |
+
output[1]['message'] = _msgs[output[-1]]
|
| 268 |
+
|
| 269 |
+
output = output[:-1]
|
| 270 |
+
if len(output) == 1:
|
| 271 |
+
return output[0]
|
| 272 |
+
else:
|
| 273 |
+
return output
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import copy
|
| 3 |
+
import heapq
|
| 4 |
+
import collections
|
| 5 |
+
import functools
|
| 6 |
+
import warnings
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from scipy._lib._util import MapWrapper, _FunctionWrapper
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class LRUDict(collections.OrderedDict):
|
| 14 |
+
def __init__(self, max_size):
|
| 15 |
+
self.__max_size = max_size
|
| 16 |
+
|
| 17 |
+
def __setitem__(self, key, value):
|
| 18 |
+
existing_key = (key in self)
|
| 19 |
+
super().__setitem__(key, value)
|
| 20 |
+
if existing_key:
|
| 21 |
+
self.move_to_end(key)
|
| 22 |
+
elif len(self) > self.__max_size:
|
| 23 |
+
self.popitem(last=False)
|
| 24 |
+
|
| 25 |
+
def update(self, other):
|
| 26 |
+
# Not needed below
|
| 27 |
+
raise NotImplementedError()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SemiInfiniteFunc:
|
| 31 |
+
"""
|
| 32 |
+
Argument transform from (start, +-oo) to (0, 1)
|
| 33 |
+
"""
|
| 34 |
+
def __init__(self, func, start, infty):
|
| 35 |
+
self._func = func
|
| 36 |
+
self._start = start
|
| 37 |
+
self._sgn = -1 if infty < 0 else 1
|
| 38 |
+
|
| 39 |
+
# Overflow threshold for the 1/t**2 factor
|
| 40 |
+
self._tmin = sys.float_info.min**0.5
|
| 41 |
+
|
| 42 |
+
def get_t(self, x):
|
| 43 |
+
z = self._sgn * (x - self._start) + 1
|
| 44 |
+
if z == 0:
|
| 45 |
+
# Can happen only if point not in range
|
| 46 |
+
return np.inf
|
| 47 |
+
return 1 / z
|
| 48 |
+
|
| 49 |
+
def __call__(self, t):
|
| 50 |
+
if t < self._tmin:
|
| 51 |
+
return 0.0
|
| 52 |
+
else:
|
| 53 |
+
x = self._start + self._sgn * (1 - t) / t
|
| 54 |
+
f = self._func(x)
|
| 55 |
+
return self._sgn * (f / t) / t
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class DoubleInfiniteFunc:
|
| 59 |
+
"""
|
| 60 |
+
Argument transform from (-oo, oo) to (-1, 1)
|
| 61 |
+
"""
|
| 62 |
+
def __init__(self, func):
|
| 63 |
+
self._func = func
|
| 64 |
+
|
| 65 |
+
# Overflow threshold for the 1/t**2 factor
|
| 66 |
+
self._tmin = sys.float_info.min**0.5
|
| 67 |
+
|
| 68 |
+
def get_t(self, x):
|
| 69 |
+
s = -1 if x < 0 else 1
|
| 70 |
+
return s / (abs(x) + 1)
|
| 71 |
+
|
| 72 |
+
def __call__(self, t):
|
| 73 |
+
if abs(t) < self._tmin:
|
| 74 |
+
return 0.0
|
| 75 |
+
else:
|
| 76 |
+
x = (1 - abs(t)) / t
|
| 77 |
+
f = self._func(x)
|
| 78 |
+
return (f / t) / t
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _max_norm(x):
|
| 82 |
+
return np.amax(abs(x))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _get_sizeof(obj):
|
| 86 |
+
try:
|
| 87 |
+
return sys.getsizeof(obj)
|
| 88 |
+
except TypeError:
|
| 89 |
+
# occurs on pypy
|
| 90 |
+
if hasattr(obj, '__sizeof__'):
|
| 91 |
+
return int(obj.__sizeof__())
|
| 92 |
+
return 64
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class _Bunch:
|
| 96 |
+
def __init__(self, **kwargs):
|
| 97 |
+
self.__keys = kwargs.keys()
|
| 98 |
+
self.__dict__.update(**kwargs)
|
| 99 |
+
|
| 100 |
+
def __repr__(self):
|
| 101 |
+
key_value_pairs = ', '.join(
|
| 102 |
+
f'{k}={repr(self.__dict__[k])}' for k in self.__keys
|
| 103 |
+
)
|
| 104 |
+
return f"_Bunch({key_value_pairs})"
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def quad_vec(f, a, b, epsabs=1e-200, epsrel=1e-8, norm='2', cache_size=100e6,
|
| 108 |
+
limit=10000, workers=1, points=None, quadrature=None, full_output=False,
|
| 109 |
+
*, args=()):
|
| 110 |
+
r"""Adaptive integration of a vector-valued function.
|
| 111 |
+
|
| 112 |
+
Parameters
|
| 113 |
+
----------
|
| 114 |
+
f : callable
|
| 115 |
+
Vector-valued function f(x) to integrate.
|
| 116 |
+
a : float
|
| 117 |
+
Initial point.
|
| 118 |
+
b : float
|
| 119 |
+
Final point.
|
| 120 |
+
epsabs : float, optional
|
| 121 |
+
Absolute tolerance.
|
| 122 |
+
epsrel : float, optional
|
| 123 |
+
Relative tolerance.
|
| 124 |
+
norm : {'max', '2'}, optional
|
| 125 |
+
Vector norm to use for error estimation.
|
| 126 |
+
cache_size : int, optional
|
| 127 |
+
Number of bytes to use for memoization.
|
| 128 |
+
limit : float or int, optional
|
| 129 |
+
An upper bound on the number of subintervals used in the adaptive
|
| 130 |
+
algorithm.
|
| 131 |
+
workers : int or map-like callable, optional
|
| 132 |
+
If `workers` is an integer, part of the computation is done in
|
| 133 |
+
parallel subdivided to this many tasks (using
|
| 134 |
+
:class:`python:multiprocessing.pool.Pool`).
|
| 135 |
+
Supply `-1` to use all cores available to the Process.
|
| 136 |
+
Alternatively, supply a map-like callable, such as
|
| 137 |
+
:meth:`python:multiprocessing.pool.Pool.map` for evaluating the
|
| 138 |
+
population in parallel.
|
| 139 |
+
This evaluation is carried out as ``workers(func, iterable)``.
|
| 140 |
+
points : list, optional
|
| 141 |
+
List of additional breakpoints.
|
| 142 |
+
quadrature : {'gk21', 'gk15', 'trapezoid'}, optional
|
| 143 |
+
Quadrature rule to use on subintervals.
|
| 144 |
+
Options: 'gk21' (Gauss-Kronrod 21-point rule),
|
| 145 |
+
'gk15' (Gauss-Kronrod 15-point rule),
|
| 146 |
+
'trapezoid' (composite trapezoid rule).
|
| 147 |
+
Default: 'gk21' for finite intervals and 'gk15' for (semi-)infinite
|
| 148 |
+
full_output : bool, optional
|
| 149 |
+
Return an additional ``info`` dictionary.
|
| 150 |
+
args : tuple, optional
|
| 151 |
+
Extra arguments to pass to function, if any.
|
| 152 |
+
|
| 153 |
+
.. versionadded:: 1.8.0
|
| 154 |
+
|
| 155 |
+
Returns
|
| 156 |
+
-------
|
| 157 |
+
res : {float, array-like}
|
| 158 |
+
Estimate for the result
|
| 159 |
+
err : float
|
| 160 |
+
Error estimate for the result in the given norm
|
| 161 |
+
info : dict
|
| 162 |
+
Returned only when ``full_output=True``.
|
| 163 |
+
Info dictionary. Is an object with the attributes:
|
| 164 |
+
|
| 165 |
+
success : bool
|
| 166 |
+
Whether integration reached target precision.
|
| 167 |
+
status : int
|
| 168 |
+
Indicator for convergence, success (0),
|
| 169 |
+
failure (1), and failure due to rounding error (2).
|
| 170 |
+
neval : int
|
| 171 |
+
Number of function evaluations.
|
| 172 |
+
intervals : ndarray, shape (num_intervals, 2)
|
| 173 |
+
Start and end points of subdivision intervals.
|
| 174 |
+
integrals : ndarray, shape (num_intervals, ...)
|
| 175 |
+
Integral for each interval.
|
| 176 |
+
Note that at most ``cache_size`` values are recorded,
|
| 177 |
+
and the array may contains *nan* for missing items.
|
| 178 |
+
errors : ndarray, shape (num_intervals,)
|
| 179 |
+
Estimated integration error for each interval.
|
| 180 |
+
|
| 181 |
+
Notes
|
| 182 |
+
-----
|
| 183 |
+
The algorithm mainly follows the implementation of QUADPACK's
|
| 184 |
+
DQAG* algorithms, implementing global error control and adaptive
|
| 185 |
+
subdivision.
|
| 186 |
+
|
| 187 |
+
The algorithm here has some differences to the QUADPACK approach:
|
| 188 |
+
|
| 189 |
+
Instead of subdividing one interval at a time, the algorithm
|
| 190 |
+
subdivides N intervals with largest errors at once. This enables
|
| 191 |
+
(partial) parallelization of the integration.
|
| 192 |
+
|
| 193 |
+
The logic of subdividing "next largest" intervals first is then
|
| 194 |
+
not implemented, and we rely on the above extension to avoid
|
| 195 |
+
concentrating on "small" intervals only.
|
| 196 |
+
|
| 197 |
+
The Wynn epsilon table extrapolation is not used (QUADPACK uses it
|
| 198 |
+
for infinite intervals). This is because the algorithm here is
|
| 199 |
+
supposed to work on vector-valued functions, in an user-specified
|
| 200 |
+
norm, and the extension of the epsilon algorithm to this case does
|
| 201 |
+
not appear to be widely agreed. For max-norm, using elementwise
|
| 202 |
+
Wynn epsilon could be possible, but we do not do this here with
|
| 203 |
+
the hope that the epsilon extrapolation is mainly useful in
|
| 204 |
+
special cases.
|
| 205 |
+
|
| 206 |
+
References
|
| 207 |
+
----------
|
| 208 |
+
[1] R. Piessens, E. de Doncker, QUADPACK (1983).
|
| 209 |
+
|
| 210 |
+
Examples
|
| 211 |
+
--------
|
| 212 |
+
We can compute integrations of a vector-valued function:
|
| 213 |
+
|
| 214 |
+
>>> from scipy.integrate import quad_vec
|
| 215 |
+
>>> import numpy as np
|
| 216 |
+
>>> import matplotlib.pyplot as plt
|
| 217 |
+
>>> alpha = np.linspace(0.0, 2.0, num=30)
|
| 218 |
+
>>> f = lambda x: x**alpha
|
| 219 |
+
>>> x0, x1 = 0, 2
|
| 220 |
+
>>> y, err = quad_vec(f, x0, x1)
|
| 221 |
+
>>> plt.plot(alpha, y)
|
| 222 |
+
>>> plt.xlabel(r"$\alpha$")
|
| 223 |
+
>>> plt.ylabel(r"$\int_{0}^{2} x^\alpha dx$")
|
| 224 |
+
>>> plt.show()
|
| 225 |
+
|
| 226 |
+
When using the argument `workers`, one should ensure
|
| 227 |
+
that the main module is import-safe, for instance
|
| 228 |
+
by rewriting the example above as:
|
| 229 |
+
|
| 230 |
+
.. code-block:: python
|
| 231 |
+
|
| 232 |
+
from scipy.integrate import quad_vec
|
| 233 |
+
import numpy as np
|
| 234 |
+
import matplotlib.pyplot as plt
|
| 235 |
+
|
| 236 |
+
alpha = np.linspace(0.0, 2.0, num=30)
|
| 237 |
+
x0, x1 = 0, 2
|
| 238 |
+
def f(x):
|
| 239 |
+
return x**alpha
|
| 240 |
+
|
| 241 |
+
if __name__ == "__main__":
|
| 242 |
+
y, err = quad_vec(f, x0, x1, workers=2)
|
| 243 |
+
"""
|
| 244 |
+
a = float(a)
|
| 245 |
+
b = float(b)
|
| 246 |
+
|
| 247 |
+
if args:
|
| 248 |
+
if not isinstance(args, tuple):
|
| 249 |
+
args = (args,)
|
| 250 |
+
|
| 251 |
+
# create a wrapped function to allow the use of map and Pool.map
|
| 252 |
+
f = _FunctionWrapper(f, args)
|
| 253 |
+
|
| 254 |
+
# Use simple transformations to deal with integrals over infinite
|
| 255 |
+
# intervals.
|
| 256 |
+
kwargs = dict(epsabs=epsabs,
|
| 257 |
+
epsrel=epsrel,
|
| 258 |
+
norm=norm,
|
| 259 |
+
cache_size=cache_size,
|
| 260 |
+
limit=limit,
|
| 261 |
+
workers=workers,
|
| 262 |
+
points=points,
|
| 263 |
+
quadrature='gk15' if quadrature is None else quadrature,
|
| 264 |
+
full_output=full_output)
|
| 265 |
+
if np.isfinite(a) and np.isinf(b):
|
| 266 |
+
f2 = SemiInfiniteFunc(f, start=a, infty=b)
|
| 267 |
+
if points is not None:
|
| 268 |
+
kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
|
| 269 |
+
return quad_vec(f2, 0, 1, **kwargs)
|
| 270 |
+
elif np.isfinite(b) and np.isinf(a):
|
| 271 |
+
f2 = SemiInfiniteFunc(f, start=b, infty=a)
|
| 272 |
+
if points is not None:
|
| 273 |
+
kwargs['points'] = tuple(f2.get_t(xp) for xp in points)
|
| 274 |
+
res = quad_vec(f2, 0, 1, **kwargs)
|
| 275 |
+
return (-res[0],) + res[1:]
|
| 276 |
+
elif np.isinf(a) and np.isinf(b):
|
| 277 |
+
sgn = -1 if b < a else 1
|
| 278 |
+
|
| 279 |
+
# NB. explicitly split integral at t=0, which separates
|
| 280 |
+
# the positive and negative sides
|
| 281 |
+
f2 = DoubleInfiniteFunc(f)
|
| 282 |
+
if points is not None:
|
| 283 |
+
kwargs['points'] = (0,) + tuple(f2.get_t(xp) for xp in points)
|
| 284 |
+
else:
|
| 285 |
+
kwargs['points'] = (0,)
|
| 286 |
+
|
| 287 |
+
if a != b:
|
| 288 |
+
res = quad_vec(f2, -1, 1, **kwargs)
|
| 289 |
+
else:
|
| 290 |
+
res = quad_vec(f2, 1, 1, **kwargs)
|
| 291 |
+
|
| 292 |
+
return (res[0]*sgn,) + res[1:]
|
| 293 |
+
elif not (np.isfinite(a) and np.isfinite(b)):
|
| 294 |
+
raise ValueError(f"invalid integration bounds a={a}, b={b}")
|
| 295 |
+
|
| 296 |
+
norm_funcs = {
|
| 297 |
+
None: _max_norm,
|
| 298 |
+
'max': _max_norm,
|
| 299 |
+
'2': np.linalg.norm
|
| 300 |
+
}
|
| 301 |
+
if callable(norm):
|
| 302 |
+
norm_func = norm
|
| 303 |
+
else:
|
| 304 |
+
norm_func = norm_funcs[norm]
|
| 305 |
+
|
| 306 |
+
parallel_count = 128
|
| 307 |
+
min_intervals = 2
|
| 308 |
+
|
| 309 |
+
try:
|
| 310 |
+
_quadrature = {None: _quadrature_gk21,
|
| 311 |
+
'gk21': _quadrature_gk21,
|
| 312 |
+
'gk15': _quadrature_gk15,
|
| 313 |
+
'trapz': _quadrature_trapezoid, # alias for backcompat
|
| 314 |
+
'trapezoid': _quadrature_trapezoid}[quadrature]
|
| 315 |
+
except KeyError as e:
|
| 316 |
+
raise ValueError(f"unknown quadrature {quadrature!r}") from e
|
| 317 |
+
|
| 318 |
+
if quadrature == "trapz":
|
| 319 |
+
msg = ("`quadrature='trapz'` is deprecated in favour of "
|
| 320 |
+
"`quadrature='trapezoid' and will raise an error from SciPy 1.16.0 "
|
| 321 |
+
"onwards.")
|
| 322 |
+
warnings.warn(msg, DeprecationWarning, stacklevel=2)
|
| 323 |
+
|
| 324 |
+
# Initial interval set
|
| 325 |
+
if points is None:
|
| 326 |
+
initial_intervals = [(a, b)]
|
| 327 |
+
else:
|
| 328 |
+
prev = a
|
| 329 |
+
initial_intervals = []
|
| 330 |
+
for p in sorted(points):
|
| 331 |
+
p = float(p)
|
| 332 |
+
if not (a < p < b) or p == prev:
|
| 333 |
+
continue
|
| 334 |
+
initial_intervals.append((prev, p))
|
| 335 |
+
prev = p
|
| 336 |
+
initial_intervals.append((prev, b))
|
| 337 |
+
|
| 338 |
+
global_integral = None
|
| 339 |
+
global_error = None
|
| 340 |
+
rounding_error = None
|
| 341 |
+
interval_cache = None
|
| 342 |
+
intervals = []
|
| 343 |
+
neval = 0
|
| 344 |
+
|
| 345 |
+
for x1, x2 in initial_intervals:
|
| 346 |
+
ig, err, rnd = _quadrature(x1, x2, f, norm_func)
|
| 347 |
+
neval += _quadrature.num_eval
|
| 348 |
+
|
| 349 |
+
if global_integral is None:
|
| 350 |
+
if isinstance(ig, (float, complex)):
|
| 351 |
+
# Specialize for scalars
|
| 352 |
+
if norm_func in (_max_norm, np.linalg.norm):
|
| 353 |
+
norm_func = abs
|
| 354 |
+
|
| 355 |
+
global_integral = ig
|
| 356 |
+
global_error = float(err)
|
| 357 |
+
rounding_error = float(rnd)
|
| 358 |
+
|
| 359 |
+
cache_count = cache_size // _get_sizeof(ig)
|
| 360 |
+
interval_cache = LRUDict(cache_count)
|
| 361 |
+
else:
|
| 362 |
+
global_integral += ig
|
| 363 |
+
global_error += err
|
| 364 |
+
rounding_error += rnd
|
| 365 |
+
|
| 366 |
+
interval_cache[(x1, x2)] = copy.copy(ig)
|
| 367 |
+
intervals.append((-err, x1, x2))
|
| 368 |
+
|
| 369 |
+
heapq.heapify(intervals)
|
| 370 |
+
|
| 371 |
+
CONVERGED = 0
|
| 372 |
+
NOT_CONVERGED = 1
|
| 373 |
+
ROUNDING_ERROR = 2
|
| 374 |
+
NOT_A_NUMBER = 3
|
| 375 |
+
|
| 376 |
+
status_msg = {
|
| 377 |
+
CONVERGED: "Target precision reached.",
|
| 378 |
+
NOT_CONVERGED: "Target precision not reached.",
|
| 379 |
+
ROUNDING_ERROR: "Target precision could not be reached due to rounding error.",
|
| 380 |
+
NOT_A_NUMBER: "Non-finite values encountered."
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
# Process intervals
|
| 384 |
+
with MapWrapper(workers) as mapwrapper:
|
| 385 |
+
ier = NOT_CONVERGED
|
| 386 |
+
|
| 387 |
+
while intervals and len(intervals) < limit:
|
| 388 |
+
# Select intervals with largest errors for subdivision
|
| 389 |
+
tol = max(epsabs, epsrel*norm_func(global_integral))
|
| 390 |
+
|
| 391 |
+
to_process = []
|
| 392 |
+
err_sum = 0
|
| 393 |
+
|
| 394 |
+
for j in range(parallel_count):
|
| 395 |
+
if not intervals:
|
| 396 |
+
break
|
| 397 |
+
|
| 398 |
+
if j > 0 and err_sum > global_error - tol/8:
|
| 399 |
+
# avoid unnecessary parallel splitting
|
| 400 |
+
break
|
| 401 |
+
|
| 402 |
+
interval = heapq.heappop(intervals)
|
| 403 |
+
|
| 404 |
+
neg_old_err, a, b = interval
|
| 405 |
+
old_int = interval_cache.pop((a, b), None)
|
| 406 |
+
to_process.append(
|
| 407 |
+
((-neg_old_err, a, b, old_int), f, norm_func, _quadrature)
|
| 408 |
+
)
|
| 409 |
+
err_sum += -neg_old_err
|
| 410 |
+
|
| 411 |
+
# Subdivide intervals
|
| 412 |
+
for parts in mapwrapper(_subdivide_interval, to_process):
|
| 413 |
+
dint, derr, dround_err, subint, dneval = parts
|
| 414 |
+
neval += dneval
|
| 415 |
+
global_integral += dint
|
| 416 |
+
global_error += derr
|
| 417 |
+
rounding_error += dround_err
|
| 418 |
+
for x in subint:
|
| 419 |
+
x1, x2, ig, err = x
|
| 420 |
+
interval_cache[(x1, x2)] = ig
|
| 421 |
+
heapq.heappush(intervals, (-err, x1, x2))
|
| 422 |
+
|
| 423 |
+
# Termination check
|
| 424 |
+
if len(intervals) >= min_intervals:
|
| 425 |
+
tol = max(epsabs, epsrel*norm_func(global_integral))
|
| 426 |
+
if global_error < tol/8:
|
| 427 |
+
ier = CONVERGED
|
| 428 |
+
break
|
| 429 |
+
if global_error < rounding_error:
|
| 430 |
+
ier = ROUNDING_ERROR
|
| 431 |
+
break
|
| 432 |
+
|
| 433 |
+
if not (np.isfinite(global_error) and np.isfinite(rounding_error)):
|
| 434 |
+
ier = NOT_A_NUMBER
|
| 435 |
+
break
|
| 436 |
+
|
| 437 |
+
res = global_integral
|
| 438 |
+
err = global_error + rounding_error
|
| 439 |
+
|
| 440 |
+
if full_output:
|
| 441 |
+
res_arr = np.asarray(res)
|
| 442 |
+
dummy = np.full(res_arr.shape, np.nan, dtype=res_arr.dtype)
|
| 443 |
+
integrals = np.array([interval_cache.get((z[1], z[2]), dummy)
|
| 444 |
+
for z in intervals], dtype=res_arr.dtype)
|
| 445 |
+
errors = np.array([-z[0] for z in intervals])
|
| 446 |
+
intervals = np.array([[z[1], z[2]] for z in intervals])
|
| 447 |
+
|
| 448 |
+
info = _Bunch(neval=neval,
|
| 449 |
+
success=(ier == CONVERGED),
|
| 450 |
+
status=ier,
|
| 451 |
+
message=status_msg[ier],
|
| 452 |
+
intervals=intervals,
|
| 453 |
+
integrals=integrals,
|
| 454 |
+
errors=errors)
|
| 455 |
+
return (res, err, info)
|
| 456 |
+
else:
|
| 457 |
+
return (res, err)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def _subdivide_interval(args):
|
| 461 |
+
interval, f, norm_func, _quadrature = args
|
| 462 |
+
old_err, a, b, old_int = interval
|
| 463 |
+
|
| 464 |
+
c = 0.5 * (a + b)
|
| 465 |
+
|
| 466 |
+
# Left-hand side
|
| 467 |
+
if getattr(_quadrature, 'cache_size', 0) > 0:
|
| 468 |
+
f = functools.lru_cache(_quadrature.cache_size)(f)
|
| 469 |
+
|
| 470 |
+
s1, err1, round1 = _quadrature(a, c, f, norm_func)
|
| 471 |
+
dneval = _quadrature.num_eval
|
| 472 |
+
s2, err2, round2 = _quadrature(c, b, f, norm_func)
|
| 473 |
+
dneval += _quadrature.num_eval
|
| 474 |
+
if old_int is None:
|
| 475 |
+
old_int, _, _ = _quadrature(a, b, f, norm_func)
|
| 476 |
+
dneval += _quadrature.num_eval
|
| 477 |
+
|
| 478 |
+
if getattr(_quadrature, 'cache_size', 0) > 0:
|
| 479 |
+
dneval = f.cache_info().misses
|
| 480 |
+
|
| 481 |
+
dint = s1 + s2 - old_int
|
| 482 |
+
derr = err1 + err2 - old_err
|
| 483 |
+
dround_err = round1 + round2
|
| 484 |
+
|
| 485 |
+
subintervals = ((a, c, s1, err1), (c, b, s2, err2))
|
| 486 |
+
return dint, derr, dround_err, subintervals, dneval
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _quadrature_trapezoid(x1, x2, f, norm_func):
|
| 490 |
+
"""
|
| 491 |
+
Composite trapezoid quadrature
|
| 492 |
+
"""
|
| 493 |
+
x3 = 0.5*(x1 + x2)
|
| 494 |
+
f1 = f(x1)
|
| 495 |
+
f2 = f(x2)
|
| 496 |
+
f3 = f(x3)
|
| 497 |
+
|
| 498 |
+
s2 = 0.25 * (x2 - x1) * (f1 + 2*f3 + f2)
|
| 499 |
+
|
| 500 |
+
round_err = 0.25 * abs(x2 - x1) * (float(norm_func(f1))
|
| 501 |
+
+ 2*float(norm_func(f3))
|
| 502 |
+
+ float(norm_func(f2))) * 2e-16
|
| 503 |
+
|
| 504 |
+
s1 = 0.5 * (x2 - x1) * (f1 + f2)
|
| 505 |
+
err = 1/3 * float(norm_func(s1 - s2))
|
| 506 |
+
return s2, err, round_err
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
_quadrature_trapezoid.cache_size = 3 * 3
|
| 510 |
+
_quadrature_trapezoid.num_eval = 3
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def _quadrature_gk(a, b, f, norm_func, x, w, v):
|
| 514 |
+
"""
|
| 515 |
+
Generic Gauss-Kronrod quadrature
|
| 516 |
+
"""
|
| 517 |
+
|
| 518 |
+
fv = [0.0]*len(x)
|
| 519 |
+
|
| 520 |
+
c = 0.5 * (a + b)
|
| 521 |
+
h = 0.5 * (b - a)
|
| 522 |
+
|
| 523 |
+
# Gauss-Kronrod
|
| 524 |
+
s_k = 0.0
|
| 525 |
+
s_k_abs = 0.0
|
| 526 |
+
for i in range(len(x)):
|
| 527 |
+
ff = f(c + h*x[i])
|
| 528 |
+
fv[i] = ff
|
| 529 |
+
|
| 530 |
+
vv = v[i]
|
| 531 |
+
|
| 532 |
+
# \int f(x)
|
| 533 |
+
s_k += vv * ff
|
| 534 |
+
# \int |f(x)|
|
| 535 |
+
s_k_abs += vv * abs(ff)
|
| 536 |
+
|
| 537 |
+
# Gauss
|
| 538 |
+
s_g = 0.0
|
| 539 |
+
for i in range(len(w)):
|
| 540 |
+
s_g += w[i] * fv[2*i + 1]
|
| 541 |
+
|
| 542 |
+
# Quadrature of abs-deviation from average
|
| 543 |
+
s_k_dabs = 0.0
|
| 544 |
+
y0 = s_k / 2.0
|
| 545 |
+
for i in range(len(x)):
|
| 546 |
+
# \int |f(x) - y0|
|
| 547 |
+
s_k_dabs += v[i] * abs(fv[i] - y0)
|
| 548 |
+
|
| 549 |
+
# Use similar error estimation as quadpack
|
| 550 |
+
err = float(norm_func((s_k - s_g) * h))
|
| 551 |
+
dabs = float(norm_func(s_k_dabs * h))
|
| 552 |
+
if dabs != 0 and err != 0:
|
| 553 |
+
err = dabs * min(1.0, (200 * err / dabs)**1.5)
|
| 554 |
+
|
| 555 |
+
eps = sys.float_info.epsilon
|
| 556 |
+
round_err = float(norm_func(50 * eps * h * s_k_abs))
|
| 557 |
+
|
| 558 |
+
if round_err > sys.float_info.min:
|
| 559 |
+
err = max(err, round_err)
|
| 560 |
+
|
| 561 |
+
return h * s_k, err, round_err
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def _quadrature_gk21(a, b, f, norm_func):
|
| 565 |
+
"""
|
| 566 |
+
Gauss-Kronrod 21 quadrature with error estimate
|
| 567 |
+
"""
|
| 568 |
+
# Gauss-Kronrod points
|
| 569 |
+
x = (0.995657163025808080735527280689003,
|
| 570 |
+
0.973906528517171720077964012084452,
|
| 571 |
+
0.930157491355708226001207180059508,
|
| 572 |
+
0.865063366688984510732096688423493,
|
| 573 |
+
0.780817726586416897063717578345042,
|
| 574 |
+
0.679409568299024406234327365114874,
|
| 575 |
+
0.562757134668604683339000099272694,
|
| 576 |
+
0.433395394129247190799265943165784,
|
| 577 |
+
0.294392862701460198131126603103866,
|
| 578 |
+
0.148874338981631210884826001129720,
|
| 579 |
+
0,
|
| 580 |
+
-0.148874338981631210884826001129720,
|
| 581 |
+
-0.294392862701460198131126603103866,
|
| 582 |
+
-0.433395394129247190799265943165784,
|
| 583 |
+
-0.562757134668604683339000099272694,
|
| 584 |
+
-0.679409568299024406234327365114874,
|
| 585 |
+
-0.780817726586416897063717578345042,
|
| 586 |
+
-0.865063366688984510732096688423493,
|
| 587 |
+
-0.930157491355708226001207180059508,
|
| 588 |
+
-0.973906528517171720077964012084452,
|
| 589 |
+
-0.995657163025808080735527280689003)
|
| 590 |
+
|
| 591 |
+
# 10-point weights
|
| 592 |
+
w = (0.066671344308688137593568809893332,
|
| 593 |
+
0.149451349150580593145776339657697,
|
| 594 |
+
0.219086362515982043995534934228163,
|
| 595 |
+
0.269266719309996355091226921569469,
|
| 596 |
+
0.295524224714752870173892994651338,
|
| 597 |
+
0.295524224714752870173892994651338,
|
| 598 |
+
0.269266719309996355091226921569469,
|
| 599 |
+
0.219086362515982043995534934228163,
|
| 600 |
+
0.149451349150580593145776339657697,
|
| 601 |
+
0.066671344308688137593568809893332)
|
| 602 |
+
|
| 603 |
+
# 21-point weights
|
| 604 |
+
v = (0.011694638867371874278064396062192,
|
| 605 |
+
0.032558162307964727478818972459390,
|
| 606 |
+
0.054755896574351996031381300244580,
|
| 607 |
+
0.075039674810919952767043140916190,
|
| 608 |
+
0.093125454583697605535065465083366,
|
| 609 |
+
0.109387158802297641899210590325805,
|
| 610 |
+
0.123491976262065851077958109831074,
|
| 611 |
+
0.134709217311473325928054001771707,
|
| 612 |
+
0.142775938577060080797094273138717,
|
| 613 |
+
0.147739104901338491374841515972068,
|
| 614 |
+
0.149445554002916905664936468389821,
|
| 615 |
+
0.147739104901338491374841515972068,
|
| 616 |
+
0.142775938577060080797094273138717,
|
| 617 |
+
0.134709217311473325928054001771707,
|
| 618 |
+
0.123491976262065851077958109831074,
|
| 619 |
+
0.109387158802297641899210590325805,
|
| 620 |
+
0.093125454583697605535065465083366,
|
| 621 |
+
0.075039674810919952767043140916190,
|
| 622 |
+
0.054755896574351996031381300244580,
|
| 623 |
+
0.032558162307964727478818972459390,
|
| 624 |
+
0.011694638867371874278064396062192)
|
| 625 |
+
|
| 626 |
+
return _quadrature_gk(a, b, f, norm_func, x, w, v)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
_quadrature_gk21.num_eval = 21
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def _quadrature_gk15(a, b, f, norm_func):
|
| 633 |
+
"""
|
| 634 |
+
Gauss-Kronrod 15 quadrature with error estimate
|
| 635 |
+
"""
|
| 636 |
+
# Gauss-Kronrod points
|
| 637 |
+
x = (0.991455371120812639206854697526329,
|
| 638 |
+
0.949107912342758524526189684047851,
|
| 639 |
+
0.864864423359769072789712788640926,
|
| 640 |
+
0.741531185599394439863864773280788,
|
| 641 |
+
0.586087235467691130294144838258730,
|
| 642 |
+
0.405845151377397166906606412076961,
|
| 643 |
+
0.207784955007898467600689403773245,
|
| 644 |
+
0.000000000000000000000000000000000,
|
| 645 |
+
-0.207784955007898467600689403773245,
|
| 646 |
+
-0.405845151377397166906606412076961,
|
| 647 |
+
-0.586087235467691130294144838258730,
|
| 648 |
+
-0.741531185599394439863864773280788,
|
| 649 |
+
-0.864864423359769072789712788640926,
|
| 650 |
+
-0.949107912342758524526189684047851,
|
| 651 |
+
-0.991455371120812639206854697526329)
|
| 652 |
+
|
| 653 |
+
# 7-point weights
|
| 654 |
+
w = (0.129484966168869693270611432679082,
|
| 655 |
+
0.279705391489276667901467771423780,
|
| 656 |
+
0.381830050505118944950369775488975,
|
| 657 |
+
0.417959183673469387755102040816327,
|
| 658 |
+
0.381830050505118944950369775488975,
|
| 659 |
+
0.279705391489276667901467771423780,
|
| 660 |
+
0.129484966168869693270611432679082)
|
| 661 |
+
|
| 662 |
+
# 15-point weights
|
| 663 |
+
v = (0.022935322010529224963732008058970,
|
| 664 |
+
0.063092092629978553290700663189204,
|
| 665 |
+
0.104790010322250183839876322541518,
|
| 666 |
+
0.140653259715525918745189590510238,
|
| 667 |
+
0.169004726639267902826583426598550,
|
| 668 |
+
0.190350578064785409913256402421014,
|
| 669 |
+
0.204432940075298892414161999234649,
|
| 670 |
+
0.209482141084727828012999174891714,
|
| 671 |
+
0.204432940075298892414161999234649,
|
| 672 |
+
0.190350578064785409913256402421014,
|
| 673 |
+
0.169004726639267902826583426598550,
|
| 674 |
+
0.140653259715525918745189590510238,
|
| 675 |
+
0.104790010322250183839876322541518,
|
| 676 |
+
0.063092092629978553290700663189204,
|
| 677 |
+
0.022935322010529224963732008058970)
|
| 678 |
+
|
| 679 |
+
return _quadrature_gk(a, b, f, norm_func, x, w, v)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
_quadrature_gk15.num_eval = 15
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e703814f6fc19b664dac20ee3c9a604f4f2dda85a5460cf65f25458c040c45e9
|
| 3 |
+
size 112024
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py
ADDED
|
@@ -0,0 +1,1279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Author: Travis Oliphant 2001
|
| 2 |
+
# Author: Nathan Woods 2013 (nquad &c)
|
| 3 |
+
import sys
|
| 4 |
+
import warnings
|
| 5 |
+
from functools import partial
|
| 6 |
+
|
| 7 |
+
from . import _quadpack
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
__all__ = ["quad", "dblquad", "tplquad", "nquad", "IntegrationWarning"]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class IntegrationWarning(UserWarning):
|
| 14 |
+
"""
|
| 15 |
+
Warning on issues during integration.
|
| 16 |
+
"""
|
| 17 |
+
pass
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def quad(func, a, b, args=(), full_output=0, epsabs=1.49e-8, epsrel=1.49e-8,
|
| 21 |
+
limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50,
|
| 22 |
+
limlst=50, complex_func=False):
|
| 23 |
+
"""
|
| 24 |
+
Compute a definite integral.
|
| 25 |
+
|
| 26 |
+
Integrate func from `a` to `b` (possibly infinite interval) using a
|
| 27 |
+
technique from the Fortran library QUADPACK.
|
| 28 |
+
|
| 29 |
+
Parameters
|
| 30 |
+
----------
|
| 31 |
+
func : {function, scipy.LowLevelCallable}
|
| 32 |
+
A Python function or method to integrate. If `func` takes many
|
| 33 |
+
arguments, it is integrated along the axis corresponding to the
|
| 34 |
+
first argument.
|
| 35 |
+
|
| 36 |
+
If the user desires improved integration performance, then `f` may
|
| 37 |
+
be a `scipy.LowLevelCallable` with one of the signatures::
|
| 38 |
+
|
| 39 |
+
double func(double x)
|
| 40 |
+
double func(double x, void *user_data)
|
| 41 |
+
double func(int n, double *xx)
|
| 42 |
+
double func(int n, double *xx, void *user_data)
|
| 43 |
+
|
| 44 |
+
The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
|
| 45 |
+
In the call forms with ``xx``, ``n`` is the length of the ``xx``
|
| 46 |
+
array which contains ``xx[0] == x`` and the rest of the items are
|
| 47 |
+
numbers contained in the ``args`` argument of quad.
|
| 48 |
+
|
| 49 |
+
In addition, certain ctypes call signatures are supported for
|
| 50 |
+
backward compatibility, but those should not be used in new code.
|
| 51 |
+
a : float
|
| 52 |
+
Lower limit of integration (use -numpy.inf for -infinity).
|
| 53 |
+
b : float
|
| 54 |
+
Upper limit of integration (use numpy.inf for +infinity).
|
| 55 |
+
args : tuple, optional
|
| 56 |
+
Extra arguments to pass to `func`.
|
| 57 |
+
full_output : int, optional
|
| 58 |
+
Non-zero to return a dictionary of integration information.
|
| 59 |
+
If non-zero, warning messages are also suppressed and the
|
| 60 |
+
message is appended to the output tuple.
|
| 61 |
+
complex_func : bool, optional
|
| 62 |
+
Indicate if the function's (`func`) return type is real
|
| 63 |
+
(``complex_func=False``: default) or complex (``complex_func=True``).
|
| 64 |
+
In both cases, the function's argument is real.
|
| 65 |
+
If full_output is also non-zero, the `infodict`, `message`, and
|
| 66 |
+
`explain` for the real and complex components are returned in
|
| 67 |
+
a dictionary with keys "real output" and "imag output".
|
| 68 |
+
|
| 69 |
+
Returns
|
| 70 |
+
-------
|
| 71 |
+
y : float
|
| 72 |
+
The integral of func from `a` to `b`.
|
| 73 |
+
abserr : float
|
| 74 |
+
An estimate of the absolute error in the result.
|
| 75 |
+
infodict : dict
|
| 76 |
+
A dictionary containing additional information.
|
| 77 |
+
message
|
| 78 |
+
A convergence message.
|
| 79 |
+
explain
|
| 80 |
+
Appended only with 'cos' or 'sin' weighting and infinite
|
| 81 |
+
integration limits, it contains an explanation of the codes in
|
| 82 |
+
infodict['ierlst']
|
| 83 |
+
|
| 84 |
+
Other Parameters
|
| 85 |
+
----------------
|
| 86 |
+
epsabs : float or int, optional
|
| 87 |
+
Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
|
| 88 |
+
an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
|
| 89 |
+
where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
|
| 90 |
+
numerical approximation. See `epsrel` below.
|
| 91 |
+
epsrel : float or int, optional
|
| 92 |
+
Relative error tolerance. Default is 1.49e-8.
|
| 93 |
+
If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
|
| 94 |
+
and ``50 * (machine epsilon)``. See `epsabs` above.
|
| 95 |
+
limit : float or int, optional
|
| 96 |
+
An upper bound on the number of subintervals used in the adaptive
|
| 97 |
+
algorithm.
|
| 98 |
+
points : (sequence of floats,ints), optional
|
| 99 |
+
A sequence of break points in the bounded integration interval
|
| 100 |
+
where local difficulties of the integrand may occur (e.g.,
|
| 101 |
+
singularities, discontinuities). The sequence does not have
|
| 102 |
+
to be sorted. Note that this option cannot be used in conjunction
|
| 103 |
+
with ``weight``.
|
| 104 |
+
weight : float or int, optional
|
| 105 |
+
String indicating weighting function. Full explanation for this
|
| 106 |
+
and the remaining arguments can be found below.
|
| 107 |
+
wvar : optional
|
| 108 |
+
Variables for use with weighting functions.
|
| 109 |
+
wopts : optional
|
| 110 |
+
Optional input for reusing Chebyshev moments.
|
| 111 |
+
maxp1 : float or int, optional
|
| 112 |
+
An upper bound on the number of Chebyshev moments.
|
| 113 |
+
limlst : int, optional
|
| 114 |
+
Upper bound on the number of cycles (>=3) for use with a sinusoidal
|
| 115 |
+
weighting and an infinite end-point.
|
| 116 |
+
|
| 117 |
+
See Also
|
| 118 |
+
--------
|
| 119 |
+
dblquad : double integral
|
| 120 |
+
tplquad : triple integral
|
| 121 |
+
nquad : n-dimensional integrals (uses `quad` recursively)
|
| 122 |
+
fixed_quad : fixed-order Gaussian quadrature
|
| 123 |
+
simpson : integrator for sampled data
|
| 124 |
+
romb : integrator for sampled data
|
| 125 |
+
scipy.special : for coefficients and roots of orthogonal polynomials
|
| 126 |
+
|
| 127 |
+
Notes
|
| 128 |
+
-----
|
| 129 |
+
For valid results, the integral must converge; behavior for divergent
|
| 130 |
+
integrals is not guaranteed.
|
| 131 |
+
|
| 132 |
+
**Extra information for quad() inputs and outputs**
|
| 133 |
+
|
| 134 |
+
If full_output is non-zero, then the third output argument
|
| 135 |
+
(infodict) is a dictionary with entries as tabulated below. For
|
| 136 |
+
infinite limits, the range is transformed to (0,1) and the
|
| 137 |
+
optional outputs are given with respect to this transformed range.
|
| 138 |
+
Let M be the input argument limit and let K be infodict['last'].
|
| 139 |
+
The entries are:
|
| 140 |
+
|
| 141 |
+
'neval'
|
| 142 |
+
The number of function evaluations.
|
| 143 |
+
'last'
|
| 144 |
+
The number, K, of subintervals produced in the subdivision process.
|
| 145 |
+
'alist'
|
| 146 |
+
A rank-1 array of length M, the first K elements of which are the
|
| 147 |
+
left end points of the subintervals in the partition of the
|
| 148 |
+
integration range.
|
| 149 |
+
'blist'
|
| 150 |
+
A rank-1 array of length M, the first K elements of which are the
|
| 151 |
+
right end points of the subintervals.
|
| 152 |
+
'rlist'
|
| 153 |
+
A rank-1 array of length M, the first K elements of which are the
|
| 154 |
+
integral approximations on the subintervals.
|
| 155 |
+
'elist'
|
| 156 |
+
A rank-1 array of length M, the first K elements of which are the
|
| 157 |
+
moduli of the absolute error estimates on the subintervals.
|
| 158 |
+
'iord'
|
| 159 |
+
A rank-1 integer array of length M, the first L elements of
|
| 160 |
+
which are pointers to the error estimates over the subintervals
|
| 161 |
+
with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
|
| 162 |
+
sequence ``infodict['iord']`` and let E be the sequence
|
| 163 |
+
``infodict['elist']``. Then ``E[I[1]], ..., E[I[L]]`` forms a
|
| 164 |
+
decreasing sequence.
|
| 165 |
+
|
| 166 |
+
If the input argument points is provided (i.e., it is not None),
|
| 167 |
+
the following additional outputs are placed in the output
|
| 168 |
+
dictionary. Assume the points sequence is of length P.
|
| 169 |
+
|
| 170 |
+
'pts'
|
| 171 |
+
A rank-1 array of length P+2 containing the integration limits
|
| 172 |
+
and the break points of the intervals in ascending order.
|
| 173 |
+
This is an array giving the subintervals over which integration
|
| 174 |
+
will occur.
|
| 175 |
+
'level'
|
| 176 |
+
A rank-1 integer array of length M (=limit), containing the
|
| 177 |
+
subdivision levels of the subintervals, i.e., if (aa,bb) is a
|
| 178 |
+
subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
|
| 179 |
+
are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
|
| 180 |
+
if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
|
| 181 |
+
'ndin'
|
| 182 |
+
A rank-1 integer array of length P+2. After the first integration
|
| 183 |
+
over the intervals (pts[1], pts[2]), the error estimates over some
|
| 184 |
+
of the intervals may have been increased artificially in order to
|
| 185 |
+
put their subdivision forward. This array has ones in slots
|
| 186 |
+
corresponding to the subintervals for which this happens.
|
| 187 |
+
|
| 188 |
+
**Weighting the integrand**
|
| 189 |
+
|
| 190 |
+
The input variables, *weight* and *wvar*, are used to weight the
|
| 191 |
+
integrand by a select list of functions. Different integration
|
| 192 |
+
methods are used to compute the integral with these weighting
|
| 193 |
+
functions, and these do not support specifying break points. The
|
| 194 |
+
possible values of weight and the corresponding weighting functions are.
|
| 195 |
+
|
| 196 |
+
========== =================================== =====================
|
| 197 |
+
``weight`` Weight function used ``wvar``
|
| 198 |
+
========== =================================== =====================
|
| 199 |
+
'cos' cos(w*x) wvar = w
|
| 200 |
+
'sin' sin(w*x) wvar = w
|
| 201 |
+
'alg' g(x) = ((x-a)**alpha)*((b-x)**beta) wvar = (alpha, beta)
|
| 202 |
+
'alg-loga' g(x)*log(x-a) wvar = (alpha, beta)
|
| 203 |
+
'alg-logb' g(x)*log(b-x) wvar = (alpha, beta)
|
| 204 |
+
'alg-log' g(x)*log(x-a)*log(b-x) wvar = (alpha, beta)
|
| 205 |
+
'cauchy' 1/(x-c) wvar = c
|
| 206 |
+
========== =================================== =====================
|
| 207 |
+
|
| 208 |
+
wvar holds the parameter w, (alpha, beta), or c depending on the weight
|
| 209 |
+
selected. In these expressions, a and b are the integration limits.
|
| 210 |
+
|
| 211 |
+
For the 'cos' and 'sin' weighting, additional inputs and outputs are
|
| 212 |
+
available.
|
| 213 |
+
|
| 214 |
+
For finite integration limits, the integration is performed using a
|
| 215 |
+
Clenshaw-Curtis method which uses Chebyshev moments. For repeated
|
| 216 |
+
calculations, these moments are saved in the output dictionary:
|
| 217 |
+
|
| 218 |
+
'momcom'
|
| 219 |
+
The maximum level of Chebyshev moments that have been computed,
|
| 220 |
+
i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
|
| 221 |
+
computed for intervals of length ``|b-a| * 2**(-l)``,
|
| 222 |
+
``l=0,1,...,M_c``.
|
| 223 |
+
'nnlog'
|
| 224 |
+
A rank-1 integer array of length M(=limit), containing the
|
| 225 |
+
subdivision levels of the subintervals, i.e., an element of this
|
| 226 |
+
array is equal to l if the corresponding subinterval is
|
| 227 |
+
``|b-a|* 2**(-l)``.
|
| 228 |
+
'chebmo'
|
| 229 |
+
A rank-2 array of shape (25, maxp1) containing the computed
|
| 230 |
+
Chebyshev moments. These can be passed on to an integration
|
| 231 |
+
over the same interval by passing this array as the second
|
| 232 |
+
element of the sequence wopts and passing infodict['momcom'] as
|
| 233 |
+
the first element.
|
| 234 |
+
|
| 235 |
+
If one of the integration limits is infinite, then a Fourier integral is
|
| 236 |
+
computed (assuming w neq 0). If full_output is 1 and a numerical error
|
| 237 |
+
is encountered, besides the error message attached to the output tuple,
|
| 238 |
+
a dictionary is also appended to the output tuple which translates the
|
| 239 |
+
error codes in the array ``info['ierlst']`` to English messages. The
|
| 240 |
+
output information dictionary contains the following entries instead of
|
| 241 |
+
'last', 'alist', 'blist', 'rlist', and 'elist':
|
| 242 |
+
|
| 243 |
+
'lst'
|
| 244 |
+
The number of subintervals needed for the integration (call it ``K_f``).
|
| 245 |
+
'rslst'
|
| 246 |
+
A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
|
| 247 |
+
contain the integral contribution over the interval
|
| 248 |
+
``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
|
| 249 |
+
and ``k=1,2,...,K_f``.
|
| 250 |
+
'erlst'
|
| 251 |
+
A rank-1 array of length ``M_f`` containing the error estimate
|
| 252 |
+
corresponding to the interval in the same position in
|
| 253 |
+
``infodict['rslist']``.
|
| 254 |
+
'ierlst'
|
| 255 |
+
A rank-1 integer array of length ``M_f`` containing an error flag
|
| 256 |
+
corresponding to the interval in the same position in
|
| 257 |
+
``infodict['rslist']``. See the explanation dictionary (last entry
|
| 258 |
+
in the output tuple) for the meaning of the codes.
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
**Details of QUADPACK level routines**
|
| 262 |
+
|
| 263 |
+
`quad` calls routines from the FORTRAN library QUADPACK. This section
|
| 264 |
+
provides details on the conditions for each routine to be called and a
|
| 265 |
+
short description of each routine. The routine called depends on
|
| 266 |
+
`weight`, `points` and the integration limits `a` and `b`.
|
| 267 |
+
|
| 268 |
+
================ ============== ========== =====================
|
| 269 |
+
QUADPACK routine `weight` `points` infinite bounds
|
| 270 |
+
================ ============== ========== =====================
|
| 271 |
+
qagse None No No
|
| 272 |
+
qagie None No Yes
|
| 273 |
+
qagpe None Yes No
|
| 274 |
+
qawoe 'sin', 'cos' No No
|
| 275 |
+
qawfe 'sin', 'cos' No either `a` or `b`
|
| 276 |
+
qawse 'alg*' No No
|
| 277 |
+
qawce 'cauchy' No No
|
| 278 |
+
================ ============== ========== =====================
|
| 279 |
+
|
| 280 |
+
The following provides a short description from [1]_ for each
|
| 281 |
+
routine.
|
| 282 |
+
|
| 283 |
+
qagse
|
| 284 |
+
is an integrator based on globally adaptive interval
|
| 285 |
+
subdivision in connection with extrapolation, which will
|
| 286 |
+
eliminate the effects of integrand singularities of
|
| 287 |
+
several types.
|
| 288 |
+
qagie
|
| 289 |
+
handles integration over infinite intervals. The infinite range is
|
| 290 |
+
mapped onto a finite interval and subsequently the same strategy as
|
| 291 |
+
in ``QAGS`` is applied.
|
| 292 |
+
qagpe
|
| 293 |
+
serves the same purposes as QAGS, but also allows the
|
| 294 |
+
user to provide explicit information about the location
|
| 295 |
+
and type of trouble-spots i.e. the abscissae of internal
|
| 296 |
+
singularities, discontinuities and other difficulties of
|
| 297 |
+
the integrand function.
|
| 298 |
+
qawoe
|
| 299 |
+
is an integrator for the evaluation of
|
| 300 |
+
:math:`\\int^b_a \\cos(\\omega x)f(x)dx` or
|
| 301 |
+
:math:`\\int^b_a \\sin(\\omega x)f(x)dx`
|
| 302 |
+
over a finite interval [a,b], where :math:`\\omega` and :math:`f`
|
| 303 |
+
are specified by the user. The rule evaluation component is based
|
| 304 |
+
on the modified Clenshaw-Curtis technique
|
| 305 |
+
|
| 306 |
+
An adaptive subdivision scheme is used in connection
|
| 307 |
+
with an extrapolation procedure, which is a modification
|
| 308 |
+
of that in ``QAGS`` and allows the algorithm to deal with
|
| 309 |
+
singularities in :math:`f(x)`.
|
| 310 |
+
qawfe
|
| 311 |
+
calculates the Fourier transform
|
| 312 |
+
:math:`\\int^\\infty_a \\cos(\\omega x)f(x)dx` or
|
| 313 |
+
:math:`\\int^\\infty_a \\sin(\\omega x)f(x)dx`
|
| 314 |
+
for user-provided :math:`\\omega` and :math:`f`. The procedure of
|
| 315 |
+
``QAWO`` is applied on successive finite intervals, and convergence
|
| 316 |
+
acceleration by means of the :math:`\\varepsilon`-algorithm is applied
|
| 317 |
+
to the series of integral approximations.
|
| 318 |
+
qawse
|
| 319 |
+
approximate :math:`\\int^b_a w(x)f(x)dx`, with :math:`a < b` where
|
| 320 |
+
:math:`w(x) = (x-a)^{\\alpha}(b-x)^{\\beta}v(x)` with
|
| 321 |
+
:math:`\\alpha,\\beta > -1`, where :math:`v(x)` may be one of the
|
| 322 |
+
following functions: :math:`1`, :math:`\\log(x-a)`, :math:`\\log(b-x)`,
|
| 323 |
+
:math:`\\log(x-a)\\log(b-x)`.
|
| 324 |
+
|
| 325 |
+
The user specifies :math:`\\alpha`, :math:`\\beta` and the type of the
|
| 326 |
+
function :math:`v`. A globally adaptive subdivision strategy is
|
| 327 |
+
applied, with modified Clenshaw-Curtis integration on those
|
| 328 |
+
subintervals which contain `a` or `b`.
|
| 329 |
+
qawce
|
| 330 |
+
compute :math:`\\int^b_a f(x) / (x-c)dx` where the integral must be
|
| 331 |
+
interpreted as a Cauchy principal value integral, for user specified
|
| 332 |
+
:math:`c` and :math:`f`. The strategy is globally adaptive. Modified
|
| 333 |
+
Clenshaw-Curtis integration is used on those intervals containing the
|
| 334 |
+
point :math:`x = c`.
|
| 335 |
+
|
| 336 |
+
**Integration of Complex Function of a Real Variable**
|
| 337 |
+
|
| 338 |
+
A complex valued function, :math:`f`, of a real variable can be written as
|
| 339 |
+
:math:`f = g + ih`. Similarly, the integral of :math:`f` can be
|
| 340 |
+
written as
|
| 341 |
+
|
| 342 |
+
.. math::
|
| 343 |
+
\\int_a^b f(x) dx = \\int_a^b g(x) dx + i\\int_a^b h(x) dx
|
| 344 |
+
|
| 345 |
+
assuming that the integrals of :math:`g` and :math:`h` exist
|
| 346 |
+
over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
|
| 347 |
+
complex-valued functions by integrating the real and imaginary components
|
| 348 |
+
separately.
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
References
|
| 352 |
+
----------
|
| 353 |
+
|
| 354 |
+
.. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
|
| 355 |
+
Überhuber, Christoph W.; Kahaner, David (1983).
|
| 356 |
+
QUADPACK: A subroutine package for automatic integration.
|
| 357 |
+
Springer-Verlag.
|
| 358 |
+
ISBN 978-3-540-12553-2.
|
| 359 |
+
|
| 360 |
+
.. [2] McCullough, Thomas; Phillips, Keith (1973).
|
| 361 |
+
Foundations of Analysis in the Complex Plane.
|
| 362 |
+
Holt Rinehart Winston.
|
| 363 |
+
ISBN 0-03-086370-8
|
| 364 |
+
|
| 365 |
+
Examples
|
| 366 |
+
--------
|
| 367 |
+
Calculate :math:`\\int^4_0 x^2 dx` and compare with an analytic result
|
| 368 |
+
|
| 369 |
+
>>> from scipy import integrate
|
| 370 |
+
>>> import numpy as np
|
| 371 |
+
>>> x2 = lambda x: x**2
|
| 372 |
+
>>> integrate.quad(x2, 0, 4)
|
| 373 |
+
(21.333333333333332, 2.3684757858670003e-13)
|
| 374 |
+
>>> print(4**3 / 3.) # analytical result
|
| 375 |
+
21.3333333333
|
| 376 |
+
|
| 377 |
+
Calculate :math:`\\int^\\infty_0 e^{-x} dx`
|
| 378 |
+
|
| 379 |
+
>>> invexp = lambda x: np.exp(-x)
|
| 380 |
+
>>> integrate.quad(invexp, 0, np.inf)
|
| 381 |
+
(1.0, 5.842605999138044e-11)
|
| 382 |
+
|
| 383 |
+
Calculate :math:`\\int^1_0 a x \\,dx` for :math:`a = 1, 3`
|
| 384 |
+
|
| 385 |
+
>>> f = lambda x, a: a*x
|
| 386 |
+
>>> y, err = integrate.quad(f, 0, 1, args=(1,))
|
| 387 |
+
>>> y
|
| 388 |
+
0.5
|
| 389 |
+
>>> y, err = integrate.quad(f, 0, 1, args=(3,))
|
| 390 |
+
>>> y
|
| 391 |
+
1.5
|
| 392 |
+
|
| 393 |
+
Calculate :math:`\\int^1_0 x^2 + y^2 dx` with ctypes, holding
|
| 394 |
+
y parameter as 1::
|
| 395 |
+
|
| 396 |
+
testlib.c =>
|
| 397 |
+
double func(int n, double args[n]){
|
| 398 |
+
return args[0]*args[0] + args[1]*args[1];}
|
| 399 |
+
compile to library testlib.*
|
| 400 |
+
|
| 401 |
+
::
|
| 402 |
+
|
| 403 |
+
from scipy import integrate
|
| 404 |
+
import ctypes
|
| 405 |
+
lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
|
| 406 |
+
lib.func.restype = ctypes.c_double
|
| 407 |
+
lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
|
| 408 |
+
integrate.quad(lib.func,0,1,(1))
|
| 409 |
+
#(1.3333333333333333, 1.4802973661668752e-14)
|
| 410 |
+
print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
|
| 411 |
+
# 1.3333333333333333
|
| 412 |
+
|
| 413 |
+
Be aware that pulse shapes and other sharp features as compared to the
|
| 414 |
+
size of the integration interval may not be integrated correctly using
|
| 415 |
+
this method. A simplified example of this limitation is integrating a
|
| 416 |
+
y-axis reflected step function with many zero values within the integrals
|
| 417 |
+
bounds.
|
| 418 |
+
|
| 419 |
+
>>> y = lambda x: 1 if x<=0 else 0
|
| 420 |
+
>>> integrate.quad(y, -1, 1)
|
| 421 |
+
(1.0, 1.1102230246251565e-14)
|
| 422 |
+
>>> integrate.quad(y, -1, 100)
|
| 423 |
+
(1.0000000002199108, 1.0189464580163188e-08)
|
| 424 |
+
>>> integrate.quad(y, -1, 10000)
|
| 425 |
+
(0.0, 0.0)
|
| 426 |
+
|
| 427 |
+
"""
|
| 428 |
+
if not isinstance(args, tuple):
|
| 429 |
+
args = (args,)
|
| 430 |
+
|
| 431 |
+
# check the limits of integration: \int_a^b, expect a < b
|
| 432 |
+
flip, a, b = b < a, min(a, b), max(a, b)
|
| 433 |
+
|
| 434 |
+
if complex_func:
|
| 435 |
+
def imfunc(x, *args):
|
| 436 |
+
return func(x, *args).imag
|
| 437 |
+
|
| 438 |
+
def refunc(x, *args):
|
| 439 |
+
return func(x, *args).real
|
| 440 |
+
|
| 441 |
+
re_retval = quad(refunc, a, b, args, full_output, epsabs,
|
| 442 |
+
epsrel, limit, points, weight, wvar, wopts,
|
| 443 |
+
maxp1, limlst, complex_func=False)
|
| 444 |
+
im_retval = quad(imfunc, a, b, args, full_output, epsabs,
|
| 445 |
+
epsrel, limit, points, weight, wvar, wopts,
|
| 446 |
+
maxp1, limlst, complex_func=False)
|
| 447 |
+
integral = re_retval[0] + 1j*im_retval[0]
|
| 448 |
+
error_estimate = re_retval[1] + 1j*im_retval[1]
|
| 449 |
+
retval = integral, error_estimate
|
| 450 |
+
if full_output:
|
| 451 |
+
msgexp = {}
|
| 452 |
+
msgexp["real"] = re_retval[2:]
|
| 453 |
+
msgexp["imag"] = im_retval[2:]
|
| 454 |
+
retval = retval + (msgexp,)
|
| 455 |
+
|
| 456 |
+
return retval
|
| 457 |
+
|
| 458 |
+
if weight is None:
|
| 459 |
+
retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
|
| 460 |
+
points)
|
| 461 |
+
else:
|
| 462 |
+
if points is not None:
|
| 463 |
+
msg = ("Break points cannot be specified when using weighted integrand.\n"
|
| 464 |
+
"Continuing, ignoring specified points.")
|
| 465 |
+
warnings.warn(msg, IntegrationWarning, stacklevel=2)
|
| 466 |
+
retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
|
| 467 |
+
limlst, limit, maxp1, weight, wvar, wopts)
|
| 468 |
+
|
| 469 |
+
if flip:
|
| 470 |
+
retval = (-retval[0],) + retval[1:]
|
| 471 |
+
|
| 472 |
+
ier = retval[-1]
|
| 473 |
+
if ier == 0:
|
| 474 |
+
return retval[:-1]
|
| 475 |
+
|
| 476 |
+
msgs = {80: "A Python error occurred possibly while calling the function.",
|
| 477 |
+
1: f"The maximum number of subdivisions ({limit}) has been achieved.\n "
|
| 478 |
+
f"If increasing the limit yields no improvement it is advised to "
|
| 479 |
+
f"analyze \n the integrand in order to determine the difficulties. "
|
| 480 |
+
f"If the position of a \n local difficulty can be determined "
|
| 481 |
+
f"(singularity, discontinuity) one will \n probably gain from "
|
| 482 |
+
f"splitting up the interval and calling the integrator \n on the "
|
| 483 |
+
f"subranges. Perhaps a special-purpose integrator should be used.",
|
| 484 |
+
2: "The occurrence of roundoff error is detected, which prevents \n "
|
| 485 |
+
"the requested tolerance from being achieved. "
|
| 486 |
+
"The error may be \n underestimated.",
|
| 487 |
+
3: "Extremely bad integrand behavior occurs at some points of the\n "
|
| 488 |
+
"integration interval.",
|
| 489 |
+
4: "The algorithm does not converge. Roundoff error is detected\n "
|
| 490 |
+
"in the extrapolation table. It is assumed that the requested "
|
| 491 |
+
"tolerance\n cannot be achieved, and that the returned result "
|
| 492 |
+
"(if full_output = 1) is \n the best which can be obtained.",
|
| 493 |
+
5: "The integral is probably divergent, or slowly convergent.",
|
| 494 |
+
6: "The input is invalid.",
|
| 495 |
+
7: "Abnormal termination of the routine. The estimates for result\n "
|
| 496 |
+
"and error are less reliable. It is assumed that the requested "
|
| 497 |
+
"accuracy\n has not been achieved.",
|
| 498 |
+
'unknown': "Unknown error."}
|
| 499 |
+
|
| 500 |
+
if weight in ['cos','sin'] and (b == np.inf or a == -np.inf):
|
| 501 |
+
msgs[1] = (
|
| 502 |
+
"The maximum number of cycles allowed has been achieved., e.e.\n of "
|
| 503 |
+
"subintervals (a+(k-1)c, a+kc) where c = (2*int(abs(omega)+1))\n "
|
| 504 |
+
"*pi/abs(omega), for k = 1, 2, ..., lst. "
|
| 505 |
+
"One can allow more cycles by increasing the value of limlst. "
|
| 506 |
+
"Look at info['ierlst'] with full_output=1."
|
| 507 |
+
)
|
| 508 |
+
msgs[4] = (
|
| 509 |
+
"The extrapolation table constructed for convergence acceleration\n of "
|
| 510 |
+
"the series formed by the integral contributions over the cycles, \n does "
|
| 511 |
+
"not converge to within the requested accuracy. "
|
| 512 |
+
"Look at \n info['ierlst'] with full_output=1."
|
| 513 |
+
)
|
| 514 |
+
msgs[7] = (
|
| 515 |
+
"Bad integrand behavior occurs within one or more of the cycles.\n "
|
| 516 |
+
"Location and type of the difficulty involved can be determined from \n "
|
| 517 |
+
"the vector info['ierlist'] obtained with full_output=1."
|
| 518 |
+
)
|
| 519 |
+
explain = {1: "The maximum number of subdivisions (= limit) has been \n "
|
| 520 |
+
"achieved on this cycle.",
|
| 521 |
+
2: "The occurrence of roundoff error is detected and prevents\n "
|
| 522 |
+
"the tolerance imposed on this cycle from being achieved.",
|
| 523 |
+
3: "Extremely bad integrand behavior occurs at some points of\n "
|
| 524 |
+
"this cycle.",
|
| 525 |
+
4: "The integral over this cycle does not converge (to within the "
|
| 526 |
+
"required accuracy) due to roundoff in the extrapolation "
|
| 527 |
+
"procedure invoked on this cycle. It is assumed that the result "
|
| 528 |
+
"on this interval is the best which can be obtained.",
|
| 529 |
+
5: "The integral over this cycle is probably divergent or "
|
| 530 |
+
"slowly convergent."}
|
| 531 |
+
|
| 532 |
+
try:
|
| 533 |
+
msg = msgs[ier]
|
| 534 |
+
except KeyError:
|
| 535 |
+
msg = msgs['unknown']
|
| 536 |
+
|
| 537 |
+
if ier in [1,2,3,4,5,7]:
|
| 538 |
+
if full_output:
|
| 539 |
+
if weight in ['cos', 'sin'] and (b == np.inf or a == -np.inf):
|
| 540 |
+
return retval[:-1] + (msg, explain)
|
| 541 |
+
else:
|
| 542 |
+
return retval[:-1] + (msg,)
|
| 543 |
+
else:
|
| 544 |
+
warnings.warn(msg, IntegrationWarning, stacklevel=2)
|
| 545 |
+
return retval[:-1]
|
| 546 |
+
|
| 547 |
+
elif ier == 6: # Forensic decision tree when QUADPACK throws ier=6
|
| 548 |
+
if epsabs <= 0: # Small error tolerance - applies to all methods
|
| 549 |
+
if epsrel < max(50 * sys.float_info.epsilon, 5e-29):
|
| 550 |
+
msg = ("If 'epsabs'<=0, 'epsrel' must be greater than both"
|
| 551 |
+
" 5e-29 and 50*(machine epsilon).")
|
| 552 |
+
elif weight in ['sin', 'cos'] and (abs(a) + abs(b) == np.inf):
|
| 553 |
+
msg = ("Sine or cosine weighted integrals with infinite domain"
|
| 554 |
+
" must have 'epsabs'>0.")
|
| 555 |
+
|
| 556 |
+
elif weight is None:
|
| 557 |
+
if points is None: # QAGSE/QAGIE
|
| 558 |
+
msg = ("Invalid 'limit' argument. There must be"
|
| 559 |
+
" at least one subinterval")
|
| 560 |
+
else: # QAGPE
|
| 561 |
+
if not (min(a, b) <= min(points) <= max(points) <= max(a, b)):
|
| 562 |
+
msg = ("All break points in 'points' must lie within the"
|
| 563 |
+
" integration limits.")
|
| 564 |
+
elif len(points) >= limit:
|
| 565 |
+
msg = (f"Number of break points ({len(points):d}) "
|
| 566 |
+
f"must be less than subinterval limit ({limit:d})")
|
| 567 |
+
|
| 568 |
+
else:
|
| 569 |
+
if maxp1 < 1:
|
| 570 |
+
msg = "Chebyshev moment limit maxp1 must be >=1."
|
| 571 |
+
|
| 572 |
+
elif weight in ('cos', 'sin') and abs(a+b) == np.inf: # QAWFE
|
| 573 |
+
msg = "Cycle limit limlst must be >=3."
|
| 574 |
+
|
| 575 |
+
elif weight.startswith('alg'): # QAWSE
|
| 576 |
+
if min(wvar) < -1:
|
| 577 |
+
msg = "wvar parameters (alpha, beta) must both be >= -1."
|
| 578 |
+
if b < a:
|
| 579 |
+
msg = "Integration limits a, b must satistfy a<b."
|
| 580 |
+
|
| 581 |
+
elif weight == 'cauchy' and wvar in (a, b):
|
| 582 |
+
msg = ("Parameter 'wvar' must not equal"
|
| 583 |
+
" integration limits 'a' or 'b'.")
|
| 584 |
+
|
| 585 |
+
raise ValueError(msg)
|
| 586 |
+
|
| 587 |
+
|
| 588 |
+
def _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points):
|
| 589 |
+
infbounds = 0
|
| 590 |
+
if (b != np.inf and a != -np.inf):
|
| 591 |
+
pass # standard integration
|
| 592 |
+
elif (b == np.inf and a != -np.inf):
|
| 593 |
+
infbounds = 1
|
| 594 |
+
bound = a
|
| 595 |
+
elif (b == np.inf and a == -np.inf):
|
| 596 |
+
infbounds = 2
|
| 597 |
+
bound = 0 # ignored
|
| 598 |
+
elif (b != np.inf and a == -np.inf):
|
| 599 |
+
infbounds = -1
|
| 600 |
+
bound = b
|
| 601 |
+
else:
|
| 602 |
+
raise RuntimeError("Infinity comparisons don't work for you.")
|
| 603 |
+
|
| 604 |
+
if points is None:
|
| 605 |
+
if infbounds == 0:
|
| 606 |
+
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
|
| 607 |
+
else:
|
| 608 |
+
return _quadpack._qagie(func, bound, infbounds, args, full_output,
|
| 609 |
+
epsabs, epsrel, limit)
|
| 610 |
+
else:
|
| 611 |
+
if infbounds != 0:
|
| 612 |
+
raise ValueError("Infinity inputs cannot be used with break points.")
|
| 613 |
+
else:
|
| 614 |
+
#Duplicates force function evaluation at singular points
|
| 615 |
+
the_points = np.unique(points)
|
| 616 |
+
the_points = the_points[a < the_points]
|
| 617 |
+
the_points = the_points[the_points < b]
|
| 618 |
+
the_points = np.concatenate((the_points, (0., 0.)))
|
| 619 |
+
return _quadpack._qagpe(func, a, b, the_points, args, full_output,
|
| 620 |
+
epsabs, epsrel, limit)
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def _quad_weight(func, a, b, args, full_output, epsabs, epsrel,
|
| 624 |
+
limlst, limit, maxp1,weight, wvar, wopts):
|
| 625 |
+
if weight not in ['cos','sin','alg','alg-loga','alg-logb','alg-log','cauchy']:
|
| 626 |
+
raise ValueError(f"{weight} not a recognized weighting function.")
|
| 627 |
+
|
| 628 |
+
strdict = {'cos':1,'sin':2,'alg':1,'alg-loga':2,'alg-logb':3,'alg-log':4}
|
| 629 |
+
|
| 630 |
+
if weight in ['cos','sin']:
|
| 631 |
+
integr = strdict[weight]
|
| 632 |
+
if (b != np.inf and a != -np.inf): # finite limits
|
| 633 |
+
if wopts is None: # no precomputed Chebyshev moments
|
| 634 |
+
return _quadpack._qawoe(func, a, b, wvar, integr, args, full_output,
|
| 635 |
+
epsabs, epsrel, limit, maxp1,1)
|
| 636 |
+
else: # precomputed Chebyshev moments
|
| 637 |
+
momcom = wopts[0]
|
| 638 |
+
chebcom = wopts[1]
|
| 639 |
+
return _quadpack._qawoe(func, a, b, wvar, integr, args,
|
| 640 |
+
full_output,epsabs, epsrel, limit, maxp1, 2,
|
| 641 |
+
momcom, chebcom)
|
| 642 |
+
|
| 643 |
+
elif (b == np.inf and a != -np.inf):
|
| 644 |
+
return _quadpack._qawfe(func, a, wvar, integr, args, full_output,
|
| 645 |
+
epsabs, limlst, limit, maxp1)
|
| 646 |
+
elif (b != np.inf and a == -np.inf): # remap function and interval
|
| 647 |
+
if weight == 'cos':
|
| 648 |
+
def thefunc(x,*myargs):
|
| 649 |
+
y = -x
|
| 650 |
+
func = myargs[0]
|
| 651 |
+
myargs = (y,) + myargs[1:]
|
| 652 |
+
return func(*myargs)
|
| 653 |
+
else:
|
| 654 |
+
def thefunc(x,*myargs):
|
| 655 |
+
y = -x
|
| 656 |
+
func = myargs[0]
|
| 657 |
+
myargs = (y,) + myargs[1:]
|
| 658 |
+
return -func(*myargs)
|
| 659 |
+
args = (func,) + args
|
| 660 |
+
return _quadpack._qawfe(thefunc, -b, wvar, integr, args,
|
| 661 |
+
full_output, epsabs, limlst, limit, maxp1)
|
| 662 |
+
else:
|
| 663 |
+
raise ValueError("Cannot integrate with this weight from -Inf to +Inf.")
|
| 664 |
+
else:
|
| 665 |
+
if a in [-np.inf, np.inf] or b in [-np.inf, np.inf]:
|
| 666 |
+
message = "Cannot integrate with this weight over an infinite interval."
|
| 667 |
+
raise ValueError(message)
|
| 668 |
+
|
| 669 |
+
if weight.startswith('alg'):
|
| 670 |
+
integr = strdict[weight]
|
| 671 |
+
return _quadpack._qawse(func, a, b, wvar, integr, args,
|
| 672 |
+
full_output, epsabs, epsrel, limit)
|
| 673 |
+
else: # weight == 'cauchy'
|
| 674 |
+
return _quadpack._qawce(func, a, b, wvar, args, full_output,
|
| 675 |
+
epsabs, epsrel, limit)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def dblquad(func, a, b, gfun, hfun, args=(), epsabs=1.49e-8, epsrel=1.49e-8):
|
| 679 |
+
"""
|
| 680 |
+
Compute a double integral.
|
| 681 |
+
|
| 682 |
+
Return the double (definite) integral of ``func(y, x)`` from ``x = a..b``
|
| 683 |
+
and ``y = gfun(x)..hfun(x)``.
|
| 684 |
+
|
| 685 |
+
Parameters
|
| 686 |
+
----------
|
| 687 |
+
func : callable
|
| 688 |
+
A Python function or method of at least two variables: y must be the
|
| 689 |
+
first argument and x the second argument.
|
| 690 |
+
a, b : float
|
| 691 |
+
The limits of integration in x: `a` < `b`
|
| 692 |
+
gfun : callable or float
|
| 693 |
+
The lower boundary curve in y which is a function taking a single
|
| 694 |
+
floating point argument (x) and returning a floating point result
|
| 695 |
+
or a float indicating a constant boundary curve.
|
| 696 |
+
hfun : callable or float
|
| 697 |
+
The upper boundary curve in y (same requirements as `gfun`).
|
| 698 |
+
args : sequence, optional
|
| 699 |
+
Extra arguments to pass to `func`.
|
| 700 |
+
epsabs : float, optional
|
| 701 |
+
Absolute tolerance passed directly to the inner 1-D quadrature
|
| 702 |
+
integration. Default is 1.49e-8. ``dblquad`` tries to obtain
|
| 703 |
+
an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
|
| 704 |
+
where ``i`` = inner integral of ``func(y, x)`` from ``gfun(x)``
|
| 705 |
+
to ``hfun(x)``, and ``result`` is the numerical approximation.
|
| 706 |
+
See `epsrel` below.
|
| 707 |
+
epsrel : float, optional
|
| 708 |
+
Relative tolerance of the inner 1-D integrals. Default is 1.49e-8.
|
| 709 |
+
If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
|
| 710 |
+
and ``50 * (machine epsilon)``. See `epsabs` above.
|
| 711 |
+
|
| 712 |
+
Returns
|
| 713 |
+
-------
|
| 714 |
+
y : float
|
| 715 |
+
The resultant integral.
|
| 716 |
+
abserr : float
|
| 717 |
+
An estimate of the error.
|
| 718 |
+
|
| 719 |
+
See Also
|
| 720 |
+
--------
|
| 721 |
+
quad : single integral
|
| 722 |
+
tplquad : triple integral
|
| 723 |
+
nquad : N-dimensional integrals
|
| 724 |
+
fixed_quad : fixed-order Gaussian quadrature
|
| 725 |
+
simpson : integrator for sampled data
|
| 726 |
+
romb : integrator for sampled data
|
| 727 |
+
scipy.special : for coefficients and roots of orthogonal polynomials
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
Notes
|
| 731 |
+
-----
|
| 732 |
+
For valid results, the integral must converge; behavior for divergent
|
| 733 |
+
integrals is not guaranteed.
|
| 734 |
+
|
| 735 |
+
**Details of QUADPACK level routines**
|
| 736 |
+
|
| 737 |
+
`quad` calls routines from the FORTRAN library QUADPACK. This section
|
| 738 |
+
provides details on the conditions for each routine to be called and a
|
| 739 |
+
short description of each routine. For each level of integration, ``qagse``
|
| 740 |
+
is used for finite limits or ``qagie`` is used if either limit (or both!)
|
| 741 |
+
are infinite. The following provides a short description from [1]_ for each
|
| 742 |
+
routine.
|
| 743 |
+
|
| 744 |
+
qagse
|
| 745 |
+
is an integrator based on globally adaptive interval
|
| 746 |
+
subdivision in connection with extrapolation, which will
|
| 747 |
+
eliminate the effects of integrand singularities of
|
| 748 |
+
several types.
|
| 749 |
+
qagie
|
| 750 |
+
handles integration over infinite intervals. The infinite range is
|
| 751 |
+
mapped onto a finite interval and subsequently the same strategy as
|
| 752 |
+
in ``QAGS`` is applied.
|
| 753 |
+
|
| 754 |
+
References
|
| 755 |
+
----------
|
| 756 |
+
|
| 757 |
+
.. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
|
| 758 |
+
Überhuber, Christoph W.; Kahaner, David (1983).
|
| 759 |
+
QUADPACK: A subroutine package for automatic integration.
|
| 760 |
+
Springer-Verlag.
|
| 761 |
+
ISBN 978-3-540-12553-2.
|
| 762 |
+
|
| 763 |
+
Examples
|
| 764 |
+
--------
|
| 765 |
+
Compute the double integral of ``x * y**2`` over the box
|
| 766 |
+
``x`` ranging from 0 to 2 and ``y`` ranging from 0 to 1.
|
| 767 |
+
That is, :math:`\\int^{x=2}_{x=0} \\int^{y=1}_{y=0} x y^2 \\,dy \\,dx`.
|
| 768 |
+
|
| 769 |
+
>>> import numpy as np
|
| 770 |
+
>>> from scipy import integrate
|
| 771 |
+
>>> f = lambda y, x: x*y**2
|
| 772 |
+
>>> integrate.dblquad(f, 0, 2, 0, 1)
|
| 773 |
+
(0.6666666666666667, 7.401486830834377e-15)
|
| 774 |
+
|
| 775 |
+
Calculate :math:`\\int^{x=\\pi/4}_{x=0} \\int^{y=\\cos(x)}_{y=\\sin(x)} 1
|
| 776 |
+
\\,dy \\,dx`.
|
| 777 |
+
|
| 778 |
+
>>> f = lambda y, x: 1
|
| 779 |
+
>>> integrate.dblquad(f, 0, np.pi/4, np.sin, np.cos)
|
| 780 |
+
(0.41421356237309503, 1.1083280054755938e-14)
|
| 781 |
+
|
| 782 |
+
Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=2-x}_{y=x} a x y \\,dy \\,dx`
|
| 783 |
+
for :math:`a=1, 3`.
|
| 784 |
+
|
| 785 |
+
>>> f = lambda y, x, a: a*x*y
|
| 786 |
+
>>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(1,))
|
| 787 |
+
(0.33333333333333337, 5.551115123125783e-15)
|
| 788 |
+
>>> integrate.dblquad(f, 0, 1, lambda x: x, lambda x: 2-x, args=(3,))
|
| 789 |
+
(0.9999999999999999, 1.6653345369377348e-14)
|
| 790 |
+
|
| 791 |
+
Compute the two-dimensional Gaussian Integral, which is the integral of the
|
| 792 |
+
Gaussian function :math:`f(x,y) = e^{-(x^{2} + y^{2})}`, over
|
| 793 |
+
:math:`(-\\infty,+\\infty)`. That is, compute the integral
|
| 794 |
+
:math:`\\iint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2})} \\,dy\\,dx`.
|
| 795 |
+
|
| 796 |
+
>>> f = lambda x, y: np.exp(-(x ** 2 + y ** 2))
|
| 797 |
+
>>> integrate.dblquad(f, -np.inf, np.inf, -np.inf, np.inf)
|
| 798 |
+
(3.141592653589777, 2.5173086737433208e-08)
|
| 799 |
+
|
| 800 |
+
"""
|
| 801 |
+
|
| 802 |
+
def temp_ranges(*args):
|
| 803 |
+
return [gfun(args[0]) if callable(gfun) else gfun,
|
| 804 |
+
hfun(args[0]) if callable(hfun) else hfun]
|
| 805 |
+
|
| 806 |
+
return nquad(func, [temp_ranges, [a, b]], args=args,
|
| 807 |
+
opts={"epsabs": epsabs, "epsrel": epsrel})
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
def tplquad(func, a, b, gfun, hfun, qfun, rfun, args=(), epsabs=1.49e-8,
|
| 811 |
+
epsrel=1.49e-8):
|
| 812 |
+
"""
|
| 813 |
+
Compute a triple (definite) integral.
|
| 814 |
+
|
| 815 |
+
Return the triple integral of ``func(z, y, x)`` from ``x = a..b``,
|
| 816 |
+
``y = gfun(x)..hfun(x)``, and ``z = qfun(x,y)..rfun(x,y)``.
|
| 817 |
+
|
| 818 |
+
Parameters
|
| 819 |
+
----------
|
| 820 |
+
func : function
|
| 821 |
+
A Python function or method of at least three variables in the
|
| 822 |
+
order (z, y, x).
|
| 823 |
+
a, b : float
|
| 824 |
+
The limits of integration in x: `a` < `b`
|
| 825 |
+
gfun : function or float
|
| 826 |
+
The lower boundary curve in y which is a function taking a single
|
| 827 |
+
floating point argument (x) and returning a floating point result
|
| 828 |
+
or a float indicating a constant boundary curve.
|
| 829 |
+
hfun : function or float
|
| 830 |
+
The upper boundary curve in y (same requirements as `gfun`).
|
| 831 |
+
qfun : function or float
|
| 832 |
+
The lower boundary surface in z. It must be a function that takes
|
| 833 |
+
two floats in the order (x, y) and returns a float or a float
|
| 834 |
+
indicating a constant boundary surface.
|
| 835 |
+
rfun : function or float
|
| 836 |
+
The upper boundary surface in z. (Same requirements as `qfun`.)
|
| 837 |
+
args : tuple, optional
|
| 838 |
+
Extra arguments to pass to `func`.
|
| 839 |
+
epsabs : float, optional
|
| 840 |
+
Absolute tolerance passed directly to the innermost 1-D quadrature
|
| 841 |
+
integration. Default is 1.49e-8.
|
| 842 |
+
epsrel : float, optional
|
| 843 |
+
Relative tolerance of the innermost 1-D integrals. Default is 1.49e-8.
|
| 844 |
+
|
| 845 |
+
Returns
|
| 846 |
+
-------
|
| 847 |
+
y : float
|
| 848 |
+
The resultant integral.
|
| 849 |
+
abserr : float
|
| 850 |
+
An estimate of the error.
|
| 851 |
+
|
| 852 |
+
See Also
|
| 853 |
+
--------
|
| 854 |
+
quad : Adaptive quadrature using QUADPACK
|
| 855 |
+
fixed_quad : Fixed-order Gaussian quadrature
|
| 856 |
+
dblquad : Double integrals
|
| 857 |
+
nquad : N-dimensional integrals
|
| 858 |
+
romb : Integrators for sampled data
|
| 859 |
+
simpson : Integrators for sampled data
|
| 860 |
+
scipy.special : For coefficients and roots of orthogonal polynomials
|
| 861 |
+
|
| 862 |
+
Notes
|
| 863 |
+
-----
|
| 864 |
+
For valid results, the integral must converge; behavior for divergent
|
| 865 |
+
integrals is not guaranteed.
|
| 866 |
+
|
| 867 |
+
**Details of QUADPACK level routines**
|
| 868 |
+
|
| 869 |
+
`quad` calls routines from the FORTRAN library QUADPACK. This section
|
| 870 |
+
provides details on the conditions for each routine to be called and a
|
| 871 |
+
short description of each routine. For each level of integration, ``qagse``
|
| 872 |
+
is used for finite limits or ``qagie`` is used, if either limit (or both!)
|
| 873 |
+
are infinite. The following provides a short description from [1]_ for each
|
| 874 |
+
routine.
|
| 875 |
+
|
| 876 |
+
qagse
|
| 877 |
+
is an integrator based on globally adaptive interval
|
| 878 |
+
subdivision in connection with extrapolation, which will
|
| 879 |
+
eliminate the effects of integrand singularities of
|
| 880 |
+
several types.
|
| 881 |
+
qagie
|
| 882 |
+
handles integration over infinite intervals. The infinite range is
|
| 883 |
+
mapped onto a finite interval and subsequently the same strategy as
|
| 884 |
+
in ``QAGS`` is applied.
|
| 885 |
+
|
| 886 |
+
References
|
| 887 |
+
----------
|
| 888 |
+
|
| 889 |
+
.. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
|
| 890 |
+
Überhuber, Christoph W.; Kahaner, David (1983).
|
| 891 |
+
QUADPACK: A subroutine package for automatic integration.
|
| 892 |
+
Springer-Verlag.
|
| 893 |
+
ISBN 978-3-540-12553-2.
|
| 894 |
+
|
| 895 |
+
Examples
|
| 896 |
+
--------
|
| 897 |
+
Compute the triple integral of ``x * y * z``, over ``x`` ranging
|
| 898 |
+
from 1 to 2, ``y`` ranging from 2 to 3, ``z`` ranging from 0 to 1.
|
| 899 |
+
That is, :math:`\\int^{x=2}_{x=1} \\int^{y=3}_{y=2} \\int^{z=1}_{z=0} x y z
|
| 900 |
+
\\,dz \\,dy \\,dx`.
|
| 901 |
+
|
| 902 |
+
>>> import numpy as np
|
| 903 |
+
>>> from scipy import integrate
|
| 904 |
+
>>> f = lambda z, y, x: x*y*z
|
| 905 |
+
>>> integrate.tplquad(f, 1, 2, 2, 3, 0, 1)
|
| 906 |
+
(1.8749999999999998, 3.3246447942574074e-14)
|
| 907 |
+
|
| 908 |
+
Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1-2x}_{y=0}
|
| 909 |
+
\\int^{z=1-x-2y}_{z=0} x y z \\,dz \\,dy \\,dx`.
|
| 910 |
+
Note: `qfun`/`rfun` takes arguments in the order (x, y), even though ``f``
|
| 911 |
+
takes arguments in the order (z, y, x).
|
| 912 |
+
|
| 913 |
+
>>> f = lambda z, y, x: x*y*z
|
| 914 |
+
>>> integrate.tplquad(f, 0, 1, 0, lambda x: 1-2*x, 0, lambda x, y: 1-x-2*y)
|
| 915 |
+
(0.05416666666666668, 2.1774196738157757e-14)
|
| 916 |
+
|
| 917 |
+
Calculate :math:`\\int^{x=1}_{x=0} \\int^{y=1}_{y=0} \\int^{z=1}_{z=0}
|
| 918 |
+
a x y z \\,dz \\,dy \\,dx` for :math:`a=1, 3`.
|
| 919 |
+
|
| 920 |
+
>>> f = lambda z, y, x, a: a*x*y*z
|
| 921 |
+
>>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(1,))
|
| 922 |
+
(0.125, 5.527033708952211e-15)
|
| 923 |
+
>>> integrate.tplquad(f, 0, 1, 0, 1, 0, 1, args=(3,))
|
| 924 |
+
(0.375, 1.6581101126856635e-14)
|
| 925 |
+
|
| 926 |
+
Compute the three-dimensional Gaussian Integral, which is the integral of
|
| 927 |
+
the Gaussian function :math:`f(x,y,z) = e^{-(x^{2} + y^{2} + z^{2})}`, over
|
| 928 |
+
:math:`(-\\infty,+\\infty)`. That is, compute the integral
|
| 929 |
+
:math:`\\iiint^{+\\infty}_{-\\infty} e^{-(x^{2} + y^{2} + z^{2})} \\,dz
|
| 930 |
+
\\,dy\\,dx`.
|
| 931 |
+
|
| 932 |
+
>>> f = lambda x, y, z: np.exp(-(x ** 2 + y ** 2 + z ** 2))
|
| 933 |
+
>>> integrate.tplquad(f, -np.inf, np.inf, -np.inf, np.inf, -np.inf, np.inf)
|
| 934 |
+
(5.568327996830833, 4.4619078828029765e-08)
|
| 935 |
+
|
| 936 |
+
"""
|
| 937 |
+
# f(z, y, x)
|
| 938 |
+
# qfun/rfun(x, y)
|
| 939 |
+
# gfun/hfun(x)
|
| 940 |
+
# nquad will hand (y, x, t0, ...) to ranges0
|
| 941 |
+
# nquad will hand (x, t0, ...) to ranges1
|
| 942 |
+
# Only qfun / rfun is different API...
|
| 943 |
+
|
| 944 |
+
def ranges0(*args):
|
| 945 |
+
return [qfun(args[1], args[0]) if callable(qfun) else qfun,
|
| 946 |
+
rfun(args[1], args[0]) if callable(rfun) else rfun]
|
| 947 |
+
|
| 948 |
+
def ranges1(*args):
|
| 949 |
+
return [gfun(args[0]) if callable(gfun) else gfun,
|
| 950 |
+
hfun(args[0]) if callable(hfun) else hfun]
|
| 951 |
+
|
| 952 |
+
ranges = [ranges0, ranges1, [a, b]]
|
| 953 |
+
return nquad(func, ranges, args=args,
|
| 954 |
+
opts={"epsabs": epsabs, "epsrel": epsrel})
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
def nquad(func, ranges, args=None, opts=None, full_output=False):
|
| 958 |
+
r"""
|
| 959 |
+
Integration over multiple variables.
|
| 960 |
+
|
| 961 |
+
Wraps `quad` to enable integration over multiple variables.
|
| 962 |
+
Various options allow improved integration of discontinuous functions, as
|
| 963 |
+
well as the use of weighted integration, and generally finer control of the
|
| 964 |
+
integration process.
|
| 965 |
+
|
| 966 |
+
Parameters
|
| 967 |
+
----------
|
| 968 |
+
func : {callable, scipy.LowLevelCallable}
|
| 969 |
+
The function to be integrated. Has arguments of ``x0, ... xn``,
|
| 970 |
+
``t0, ... tm``, where integration is carried out over ``x0, ... xn``,
|
| 971 |
+
which must be floats. Where ``t0, ... tm`` are extra arguments
|
| 972 |
+
passed in args.
|
| 973 |
+
Function signature should be ``func(x0, x1, ..., xn, t0, t1, ..., tm)``.
|
| 974 |
+
Integration is carried out in order. That is, integration over ``x0``
|
| 975 |
+
is the innermost integral, and ``xn`` is the outermost.
|
| 976 |
+
|
| 977 |
+
If the user desires improved integration performance, then `f` may
|
| 978 |
+
be a `scipy.LowLevelCallable` with one of the signatures::
|
| 979 |
+
|
| 980 |
+
double func(int n, double *xx)
|
| 981 |
+
double func(int n, double *xx, void *user_data)
|
| 982 |
+
|
| 983 |
+
where ``n`` is the number of variables and args. The ``xx`` array
|
| 984 |
+
contains the coordinates and extra arguments. ``user_data`` is the data
|
| 985 |
+
contained in the `scipy.LowLevelCallable`.
|
| 986 |
+
ranges : iterable object
|
| 987 |
+
Each element of ranges may be either a sequence of 2 numbers, or else
|
| 988 |
+
a callable that returns such a sequence. ``ranges[0]`` corresponds to
|
| 989 |
+
integration over x0, and so on. If an element of ranges is a callable,
|
| 990 |
+
then it will be called with all of the integration arguments available,
|
| 991 |
+
as well as any parametric arguments. e.g., if
|
| 992 |
+
``func = f(x0, x1, x2, t0, t1)``, then ``ranges[0]`` may be defined as
|
| 993 |
+
either ``(a, b)`` or else as ``(a, b) = range0(x1, x2, t0, t1)``.
|
| 994 |
+
args : iterable object, optional
|
| 995 |
+
Additional arguments ``t0, ... tn``, required by ``func``, ``ranges``,
|
| 996 |
+
and ``opts``.
|
| 997 |
+
opts : iterable object or dict, optional
|
| 998 |
+
Options to be passed to `quad`. May be empty, a dict, or
|
| 999 |
+
a sequence of dicts or functions that return a dict. If empty, the
|
| 1000 |
+
default options from scipy.integrate.quad are used. If a dict, the same
|
| 1001 |
+
options are used for all levels of integraion. If a sequence, then each
|
| 1002 |
+
element of the sequence corresponds to a particular integration. e.g.,
|
| 1003 |
+
``opts[0]`` corresponds to integration over ``x0``, and so on. If a
|
| 1004 |
+
callable, the signature must be the same as for ``ranges``. The
|
| 1005 |
+
available options together with their default values are:
|
| 1006 |
+
|
| 1007 |
+
- epsabs = 1.49e-08
|
| 1008 |
+
- epsrel = 1.49e-08
|
| 1009 |
+
- limit = 50
|
| 1010 |
+
- points = None
|
| 1011 |
+
- weight = None
|
| 1012 |
+
- wvar = None
|
| 1013 |
+
- wopts = None
|
| 1014 |
+
|
| 1015 |
+
For more information on these options, see `quad`.
|
| 1016 |
+
|
| 1017 |
+
full_output : bool, optional
|
| 1018 |
+
Partial implementation of ``full_output`` from scipy.integrate.quad.
|
| 1019 |
+
The number of integrand function evaluations ``neval`` can be obtained
|
| 1020 |
+
by setting ``full_output=True`` when calling nquad.
|
| 1021 |
+
|
| 1022 |
+
Returns
|
| 1023 |
+
-------
|
| 1024 |
+
result : float
|
| 1025 |
+
The result of the integration.
|
| 1026 |
+
abserr : float
|
| 1027 |
+
The maximum of the estimates of the absolute error in the various
|
| 1028 |
+
integration results.
|
| 1029 |
+
out_dict : dict, optional
|
| 1030 |
+
A dict containing additional information on the integration.
|
| 1031 |
+
|
| 1032 |
+
See Also
|
| 1033 |
+
--------
|
| 1034 |
+
quad : 1-D numerical integration
|
| 1035 |
+
dblquad, tplquad : double and triple integrals
|
| 1036 |
+
fixed_quad : fixed-order Gaussian quadrature
|
| 1037 |
+
|
| 1038 |
+
Notes
|
| 1039 |
+
-----
|
| 1040 |
+
For valid results, the integral must converge; behavior for divergent
|
| 1041 |
+
integrals is not guaranteed.
|
| 1042 |
+
|
| 1043 |
+
**Details of QUADPACK level routines**
|
| 1044 |
+
|
| 1045 |
+
`nquad` calls routines from the FORTRAN library QUADPACK. This section
|
| 1046 |
+
provides details on the conditions for each routine to be called and a
|
| 1047 |
+
short description of each routine. The routine called depends on
|
| 1048 |
+
`weight`, `points` and the integration limits `a` and `b`.
|
| 1049 |
+
|
| 1050 |
+
================ ============== ========== =====================
|
| 1051 |
+
QUADPACK routine `weight` `points` infinite bounds
|
| 1052 |
+
================ ============== ========== =====================
|
| 1053 |
+
qagse None No No
|
| 1054 |
+
qagie None No Yes
|
| 1055 |
+
qagpe None Yes No
|
| 1056 |
+
qawoe 'sin', 'cos' No No
|
| 1057 |
+
qawfe 'sin', 'cos' No either `a` or `b`
|
| 1058 |
+
qawse 'alg*' No No
|
| 1059 |
+
qawce 'cauchy' No No
|
| 1060 |
+
================ ============== ========== =====================
|
| 1061 |
+
|
| 1062 |
+
The following provides a short description from [1]_ for each
|
| 1063 |
+
routine.
|
| 1064 |
+
|
| 1065 |
+
qagse
|
| 1066 |
+
is an integrator based on globally adaptive interval
|
| 1067 |
+
subdivision in connection with extrapolation, which will
|
| 1068 |
+
eliminate the effects of integrand singularities of
|
| 1069 |
+
several types.
|
| 1070 |
+
qagie
|
| 1071 |
+
handles integration over infinite intervals. The infinite range is
|
| 1072 |
+
mapped onto a finite interval and subsequently the same strategy as
|
| 1073 |
+
in ``QAGS`` is applied.
|
| 1074 |
+
qagpe
|
| 1075 |
+
serves the same purposes as QAGS, but also allows the
|
| 1076 |
+
user to provide explicit information about the location
|
| 1077 |
+
and type of trouble-spots i.e. the abscissae of internal
|
| 1078 |
+
singularities, discontinuities and other difficulties of
|
| 1079 |
+
the integrand function.
|
| 1080 |
+
qawoe
|
| 1081 |
+
is an integrator for the evaluation of
|
| 1082 |
+
:math:`\int^b_a \cos(\omega x)f(x)dx` or
|
| 1083 |
+
:math:`\int^b_a \sin(\omega x)f(x)dx`
|
| 1084 |
+
over a finite interval [a,b], where :math:`\omega` and :math:`f`
|
| 1085 |
+
are specified by the user. The rule evaluation component is based
|
| 1086 |
+
on the modified Clenshaw-Curtis technique
|
| 1087 |
+
|
| 1088 |
+
An adaptive subdivision scheme is used in connection
|
| 1089 |
+
with an extrapolation procedure, which is a modification
|
| 1090 |
+
of that in ``QAGS`` and allows the algorithm to deal with
|
| 1091 |
+
singularities in :math:`f(x)`.
|
| 1092 |
+
qawfe
|
| 1093 |
+
calculates the Fourier transform
|
| 1094 |
+
:math:`\int^\infty_a \cos(\omega x)f(x)dx` or
|
| 1095 |
+
:math:`\int^\infty_a \sin(\omega x)f(x)dx`
|
| 1096 |
+
for user-provided :math:`\omega` and :math:`f`. The procedure of
|
| 1097 |
+
``QAWO`` is applied on successive finite intervals, and convergence
|
| 1098 |
+
acceleration by means of the :math:`\varepsilon`-algorithm is applied
|
| 1099 |
+
to the series of integral approximations.
|
| 1100 |
+
qawse
|
| 1101 |
+
approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
|
| 1102 |
+
:math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
|
| 1103 |
+
:math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
|
| 1104 |
+
following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
|
| 1105 |
+
:math:`\log(x-a)\log(b-x)`.
|
| 1106 |
+
|
| 1107 |
+
The user specifies :math:`\alpha`, :math:`\beta` and the type of the
|
| 1108 |
+
function :math:`v`. A globally adaptive subdivision strategy is
|
| 1109 |
+
applied, with modified Clenshaw-Curtis integration on those
|
| 1110 |
+
subintervals which contain `a` or `b`.
|
| 1111 |
+
qawce
|
| 1112 |
+
compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
|
| 1113 |
+
interpreted as a Cauchy principal value integral, for user specified
|
| 1114 |
+
:math:`c` and :math:`f`. The strategy is globally adaptive. Modified
|
| 1115 |
+
Clenshaw-Curtis integration is used on those intervals containing the
|
| 1116 |
+
point :math:`x = c`.
|
| 1117 |
+
|
| 1118 |
+
References
|
| 1119 |
+
----------
|
| 1120 |
+
|
| 1121 |
+
.. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
|
| 1122 |
+
Überhuber, Christoph W.; Kahaner, David (1983).
|
| 1123 |
+
QUADPACK: A subroutine package for automatic integration.
|
| 1124 |
+
Springer-Verlag.
|
| 1125 |
+
ISBN 978-3-540-12553-2.
|
| 1126 |
+
|
| 1127 |
+
Examples
|
| 1128 |
+
--------
|
| 1129 |
+
Calculate
|
| 1130 |
+
|
| 1131 |
+
.. math::
|
| 1132 |
+
|
| 1133 |
+
\int^{1}_{-0.15} \int^{0.8}_{0.13} \int^{1}_{-1} \int^{1}_{0}
|
| 1134 |
+
f(x_0, x_1, x_2, x_3) \,dx_0 \,dx_1 \,dx_2 \,dx_3 ,
|
| 1135 |
+
|
| 1136 |
+
where
|
| 1137 |
+
|
| 1138 |
+
.. math::
|
| 1139 |
+
|
| 1140 |
+
f(x_0, x_1, x_2, x_3) = \begin{cases}
|
| 1141 |
+
x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+1 & (x_0-0.2 x_3-0.5-0.25 x_1 > 0) \\
|
| 1142 |
+
x_0^2+x_1 x_2-x_3^3+ \sin{x_0}+0 & (x_0-0.2 x_3-0.5-0.25 x_1 \leq 0)
|
| 1143 |
+
\end{cases} .
|
| 1144 |
+
|
| 1145 |
+
>>> import numpy as np
|
| 1146 |
+
>>> from scipy import integrate
|
| 1147 |
+
>>> func = lambda x0,x1,x2,x3 : x0**2 + x1*x2 - x3**3 + np.sin(x0) + (
|
| 1148 |
+
... 1 if (x0-.2*x3-.5-.25*x1>0) else 0)
|
| 1149 |
+
>>> def opts0(*args, **kwargs):
|
| 1150 |
+
... return {'points':[0.2*args[2] + 0.5 + 0.25*args[0]]}
|
| 1151 |
+
>>> integrate.nquad(func, [[0,1], [-1,1], [.13,.8], [-.15,1]],
|
| 1152 |
+
... opts=[opts0,{},{},{}], full_output=True)
|
| 1153 |
+
(1.5267454070738633, 2.9437360001402324e-14, {'neval': 388962})
|
| 1154 |
+
|
| 1155 |
+
Calculate
|
| 1156 |
+
|
| 1157 |
+
.. math::
|
| 1158 |
+
|
| 1159 |
+
\int^{t_0+t_1+1}_{t_0+t_1-1}
|
| 1160 |
+
\int^{x_2+t_0^2 t_1^3+1}_{x_2+t_0^2 t_1^3-1}
|
| 1161 |
+
\int^{t_0 x_1+t_1 x_2+1}_{t_0 x_1+t_1 x_2-1}
|
| 1162 |
+
f(x_0,x_1, x_2,t_0,t_1)
|
| 1163 |
+
\,dx_0 \,dx_1 \,dx_2,
|
| 1164 |
+
|
| 1165 |
+
where
|
| 1166 |
+
|
| 1167 |
+
.. math::
|
| 1168 |
+
|
| 1169 |
+
f(x_0, x_1, x_2, t_0, t_1) = \begin{cases}
|
| 1170 |
+
x_0 x_2^2 + \sin{x_1}+2 & (x_0+t_1 x_1-t_0 > 0) \\
|
| 1171 |
+
x_0 x_2^2 +\sin{x_1}+1 & (x_0+t_1 x_1-t_0 \leq 0)
|
| 1172 |
+
\end{cases}
|
| 1173 |
+
|
| 1174 |
+
and :math:`(t_0, t_1) = (0, 1)` .
|
| 1175 |
+
|
| 1176 |
+
>>> def func2(x0, x1, x2, t0, t1):
|
| 1177 |
+
... return x0*x2**2 + np.sin(x1) + 1 + (1 if x0+t1*x1-t0>0 else 0)
|
| 1178 |
+
>>> def lim0(x1, x2, t0, t1):
|
| 1179 |
+
... return [t0*x1 + t1*x2 - 1, t0*x1 + t1*x2 + 1]
|
| 1180 |
+
>>> def lim1(x2, t0, t1):
|
| 1181 |
+
... return [x2 + t0**2*t1**3 - 1, x2 + t0**2*t1**3 + 1]
|
| 1182 |
+
>>> def lim2(t0, t1):
|
| 1183 |
+
... return [t0 + t1 - 1, t0 + t1 + 1]
|
| 1184 |
+
>>> def opts0(x1, x2, t0, t1):
|
| 1185 |
+
... return {'points' : [t0 - t1*x1]}
|
| 1186 |
+
>>> def opts1(x2, t0, t1):
|
| 1187 |
+
... return {}
|
| 1188 |
+
>>> def opts2(t0, t1):
|
| 1189 |
+
... return {}
|
| 1190 |
+
>>> integrate.nquad(func2, [lim0, lim1, lim2], args=(0,1),
|
| 1191 |
+
... opts=[opts0, opts1, opts2])
|
| 1192 |
+
(36.099919226771625, 1.8546948553373528e-07)
|
| 1193 |
+
|
| 1194 |
+
"""
|
| 1195 |
+
depth = len(ranges)
|
| 1196 |
+
ranges = [rng if callable(rng) else _RangeFunc(rng) for rng in ranges]
|
| 1197 |
+
if args is None:
|
| 1198 |
+
args = ()
|
| 1199 |
+
if opts is None:
|
| 1200 |
+
opts = [dict([])] * depth
|
| 1201 |
+
|
| 1202 |
+
if isinstance(opts, dict):
|
| 1203 |
+
opts = [_OptFunc(opts)] * depth
|
| 1204 |
+
else:
|
| 1205 |
+
opts = [opt if callable(opt) else _OptFunc(opt) for opt in opts]
|
| 1206 |
+
return _NQuad(func, ranges, opts, full_output).integrate(*args)
|
| 1207 |
+
|
| 1208 |
+
|
| 1209 |
+
class _RangeFunc:
|
| 1210 |
+
def __init__(self, range_):
|
| 1211 |
+
self.range_ = range_
|
| 1212 |
+
|
| 1213 |
+
def __call__(self, *args):
|
| 1214 |
+
"""Return stored value.
|
| 1215 |
+
|
| 1216 |
+
*args needed because range_ can be float or func, and is called with
|
| 1217 |
+
variable number of parameters.
|
| 1218 |
+
"""
|
| 1219 |
+
return self.range_
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
class _OptFunc:
|
| 1223 |
+
def __init__(self, opt):
|
| 1224 |
+
self.opt = opt
|
| 1225 |
+
|
| 1226 |
+
def __call__(self, *args):
|
| 1227 |
+
"""Return stored dict."""
|
| 1228 |
+
return self.opt
|
| 1229 |
+
|
| 1230 |
+
|
| 1231 |
+
class _NQuad:
|
| 1232 |
+
def __init__(self, func, ranges, opts, full_output):
|
| 1233 |
+
self.abserr = 0
|
| 1234 |
+
self.func = func
|
| 1235 |
+
self.ranges = ranges
|
| 1236 |
+
self.opts = opts
|
| 1237 |
+
self.maxdepth = len(ranges)
|
| 1238 |
+
self.full_output = full_output
|
| 1239 |
+
if self.full_output:
|
| 1240 |
+
self.out_dict = {'neval': 0}
|
| 1241 |
+
|
| 1242 |
+
def integrate(self, *args, **kwargs):
|
| 1243 |
+
depth = kwargs.pop('depth', 0)
|
| 1244 |
+
if kwargs:
|
| 1245 |
+
raise ValueError('unexpected kwargs')
|
| 1246 |
+
|
| 1247 |
+
# Get the integration range and options for this depth.
|
| 1248 |
+
ind = -(depth + 1)
|
| 1249 |
+
fn_range = self.ranges[ind]
|
| 1250 |
+
low, high = fn_range(*args)
|
| 1251 |
+
fn_opt = self.opts[ind]
|
| 1252 |
+
opt = dict(fn_opt(*args))
|
| 1253 |
+
|
| 1254 |
+
if 'points' in opt:
|
| 1255 |
+
opt['points'] = [x for x in opt['points'] if low <= x <= high]
|
| 1256 |
+
if depth + 1 == self.maxdepth:
|
| 1257 |
+
f = self.func
|
| 1258 |
+
else:
|
| 1259 |
+
f = partial(self.integrate, depth=depth+1)
|
| 1260 |
+
quad_r = quad(f, low, high, args=args, full_output=self.full_output,
|
| 1261 |
+
**opt)
|
| 1262 |
+
value = quad_r[0]
|
| 1263 |
+
abserr = quad_r[1]
|
| 1264 |
+
if self.full_output:
|
| 1265 |
+
infodict = quad_r[2]
|
| 1266 |
+
# The 'neval' parameter in full_output returns the total
|
| 1267 |
+
# number of times the integrand function was evaluated.
|
| 1268 |
+
# Therefore, only the innermost integration loop counts.
|
| 1269 |
+
if depth + 1 == self.maxdepth:
|
| 1270 |
+
self.out_dict['neval'] += infodict['neval']
|
| 1271 |
+
self.abserr = max(self.abserr, abserr)
|
| 1272 |
+
if depth > 0:
|
| 1273 |
+
return value
|
| 1274 |
+
else:
|
| 1275 |
+
# Final result of N-D integration with error
|
| 1276 |
+
if self.full_output:
|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+
import math
|
| 4 |
+
import warnings
|
| 5 |
+
from collections import namedtuple
|
| 6 |
+
from collections.abc import Callable
|
| 7 |
+
|
| 8 |
+
from scipy.special import roots_legendre
|
| 9 |
+
from scipy.special import gammaln, logsumexp
|
| 10 |
+
from scipy._lib._util import _rng_spawn
|
| 11 |
+
from scipy._lib._array_api import _asarray, array_namespace, xp_broadcast_promote
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = ['fixed_quad', 'romb',
|
| 15 |
+
'trapezoid', 'simpson',
|
| 16 |
+
'cumulative_trapezoid', 'newton_cotes',
|
| 17 |
+
'qmc_quad', 'cumulative_simpson']
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def trapezoid(y, x=None, dx=1.0, axis=-1):
|
| 21 |
+
r"""
|
| 22 |
+
Integrate along the given axis using the composite trapezoidal rule.
|
| 23 |
+
|
| 24 |
+
If `x` is provided, the integration happens in sequence along its
|
| 25 |
+
elements - they are not sorted.
|
| 26 |
+
|
| 27 |
+
Integrate `y` (`x`) along each 1d slice on the given axis, compute
|
| 28 |
+
:math:`\int y(x) dx`.
|
| 29 |
+
When `x` is specified, this integrates along the parametric curve,
|
| 30 |
+
computing :math:`\int_t y(t) dt =
|
| 31 |
+
\int_t y(t) \left.\frac{dx}{dt}\right|_{x=x(t)} dt`.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
y : array_like
|
| 36 |
+
Input array to integrate.
|
| 37 |
+
x : array_like, optional
|
| 38 |
+
The sample points corresponding to the `y` values. If `x` is None,
|
| 39 |
+
the sample points are assumed to be evenly spaced `dx` apart. The
|
| 40 |
+
default is None.
|
| 41 |
+
dx : scalar, optional
|
| 42 |
+
The spacing between sample points when `x` is None. The default is 1.
|
| 43 |
+
axis : int, optional
|
| 44 |
+
The axis along which to integrate. The default is the last axis.
|
| 45 |
+
|
| 46 |
+
Returns
|
| 47 |
+
-------
|
| 48 |
+
trapezoid : float or ndarray
|
| 49 |
+
Definite integral of `y` = n-dimensional array as approximated along
|
| 50 |
+
a single axis by the trapezoidal rule. If `y` is a 1-dimensional array,
|
| 51 |
+
then the result is a float. If `n` is greater than 1, then the result
|
| 52 |
+
is an `n`-1 dimensional array.
|
| 53 |
+
|
| 54 |
+
See Also
|
| 55 |
+
--------
|
| 56 |
+
cumulative_trapezoid, simpson, romb
|
| 57 |
+
|
| 58 |
+
Notes
|
| 59 |
+
-----
|
| 60 |
+
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
|
| 61 |
+
will be taken from `y` array, by default x-axis distances between
|
| 62 |
+
points will be 1.0, alternatively they can be provided with `x` array
|
| 63 |
+
or with `dx` scalar. Return value will be equal to combined area under
|
| 64 |
+
the red lines.
|
| 65 |
+
|
| 66 |
+
References
|
| 67 |
+
----------
|
| 68 |
+
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Trapezoidal_rule
|
| 69 |
+
|
| 70 |
+
.. [2] Illustration image:
|
| 71 |
+
https://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
|
| 72 |
+
|
| 73 |
+
Examples
|
| 74 |
+
--------
|
| 75 |
+
Use the trapezoidal rule on evenly spaced points:
|
| 76 |
+
|
| 77 |
+
>>> import numpy as np
|
| 78 |
+
>>> from scipy import integrate
|
| 79 |
+
>>> integrate.trapezoid([1, 2, 3])
|
| 80 |
+
4.0
|
| 81 |
+
|
| 82 |
+
The spacing between sample points can be selected by either the
|
| 83 |
+
``x`` or ``dx`` arguments:
|
| 84 |
+
|
| 85 |
+
>>> integrate.trapezoid([1, 2, 3], x=[4, 6, 8])
|
| 86 |
+
8.0
|
| 87 |
+
>>> integrate.trapezoid([1, 2, 3], dx=2)
|
| 88 |
+
8.0
|
| 89 |
+
|
| 90 |
+
Using a decreasing ``x`` corresponds to integrating in reverse:
|
| 91 |
+
|
| 92 |
+
>>> integrate.trapezoid([1, 2, 3], x=[8, 6, 4])
|
| 93 |
+
-8.0
|
| 94 |
+
|
| 95 |
+
More generally ``x`` is used to integrate along a parametric curve. We can
|
| 96 |
+
estimate the integral :math:`\int_0^1 x^2 = 1/3` using:
|
| 97 |
+
|
| 98 |
+
>>> x = np.linspace(0, 1, num=50)
|
| 99 |
+
>>> y = x**2
|
| 100 |
+
>>> integrate.trapezoid(y, x)
|
| 101 |
+
0.33340274885464394
|
| 102 |
+
|
| 103 |
+
Or estimate the area of a circle, noting we repeat the sample which closes
|
| 104 |
+
the curve:
|
| 105 |
+
|
| 106 |
+
>>> theta = np.linspace(0, 2 * np.pi, num=1000, endpoint=True)
|
| 107 |
+
>>> integrate.trapezoid(np.cos(theta), x=np.sin(theta))
|
| 108 |
+
3.141571941375841
|
| 109 |
+
|
| 110 |
+
``trapezoid`` can be applied along a specified axis to do multiple
|
| 111 |
+
computations in one call:
|
| 112 |
+
|
| 113 |
+
>>> a = np.arange(6).reshape(2, 3)
|
| 114 |
+
>>> a
|
| 115 |
+
array([[0, 1, 2],
|
| 116 |
+
[3, 4, 5]])
|
| 117 |
+
>>> integrate.trapezoid(a, axis=0)
|
| 118 |
+
array([1.5, 2.5, 3.5])
|
| 119 |
+
>>> integrate.trapezoid(a, axis=1)
|
| 120 |
+
array([2., 8.])
|
| 121 |
+
"""
|
| 122 |
+
xp = array_namespace(y)
|
| 123 |
+
y = _asarray(y, xp=xp, subok=True)
|
| 124 |
+
# Cannot just use the broadcasted arrays that are returned
|
| 125 |
+
# because trapezoid does not follow normal broadcasting rules
|
| 126 |
+
# cf. https://github.com/scipy/scipy/pull/21524#issuecomment-2354105942
|
| 127 |
+
result_dtype = xp_broadcast_promote(y, force_floating=True, xp=xp)[0].dtype
|
| 128 |
+
nd = y.ndim
|
| 129 |
+
slice1 = [slice(None)]*nd
|
| 130 |
+
slice2 = [slice(None)]*nd
|
| 131 |
+
slice1[axis] = slice(1, None)
|
| 132 |
+
slice2[axis] = slice(None, -1)
|
| 133 |
+
if x is None:
|
| 134 |
+
d = dx
|
| 135 |
+
else:
|
| 136 |
+
x = _asarray(x, xp=xp, subok=True)
|
| 137 |
+
if x.ndim == 1:
|
| 138 |
+
d = x[1:] - x[:-1]
|
| 139 |
+
# make d broadcastable to y
|
| 140 |
+
slice3 = [None] * nd
|
| 141 |
+
slice3[axis] = slice(None)
|
| 142 |
+
d = d[tuple(slice3)]
|
| 143 |
+
else:
|
| 144 |
+
# if x is n-D it should be broadcastable to y
|
| 145 |
+
x = xp.broadcast_to(x, y.shape)
|
| 146 |
+
d = x[tuple(slice1)] - x[tuple(slice2)]
|
| 147 |
+
try:
|
| 148 |
+
ret = xp.sum(
|
| 149 |
+
d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
|
| 150 |
+
axis=axis, dtype=result_dtype
|
| 151 |
+
)
|
| 152 |
+
except ValueError:
|
| 153 |
+
# Operations didn't work, cast to ndarray
|
| 154 |
+
d = xp.asarray(d)
|
| 155 |
+
y = xp.asarray(y)
|
| 156 |
+
ret = xp.sum(
|
| 157 |
+
d * (y[tuple(slice1)] + y[tuple(slice2)]) / 2.0,
|
| 158 |
+
axis=axis, dtype=result_dtype
|
| 159 |
+
)
|
| 160 |
+
return ret
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _cached_roots_legendre(n):
|
| 164 |
+
"""
|
| 165 |
+
Cache roots_legendre results to speed up calls of the fixed_quad
|
| 166 |
+
function.
|
| 167 |
+
"""
|
| 168 |
+
if n in _cached_roots_legendre.cache:
|
| 169 |
+
return _cached_roots_legendre.cache[n]
|
| 170 |
+
|
| 171 |
+
_cached_roots_legendre.cache[n] = roots_legendre(n)
|
| 172 |
+
return _cached_roots_legendre.cache[n]
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
_cached_roots_legendre.cache = dict()
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def fixed_quad(func, a, b, args=(), n=5):
|
| 179 |
+
"""
|
| 180 |
+
Compute a definite integral using fixed-order Gaussian quadrature.
|
| 181 |
+
|
| 182 |
+
Integrate `func` from `a` to `b` using Gaussian quadrature of
|
| 183 |
+
order `n`.
|
| 184 |
+
|
| 185 |
+
Parameters
|
| 186 |
+
----------
|
| 187 |
+
func : callable
|
| 188 |
+
A Python function or method to integrate (must accept vector inputs).
|
| 189 |
+
If integrating a vector-valued function, the returned array must have
|
| 190 |
+
shape ``(..., len(x))``.
|
| 191 |
+
a : float
|
| 192 |
+
Lower limit of integration.
|
| 193 |
+
b : float
|
| 194 |
+
Upper limit of integration.
|
| 195 |
+
args : tuple, optional
|
| 196 |
+
Extra arguments to pass to function, if any.
|
| 197 |
+
n : int, optional
|
| 198 |
+
Order of quadrature integration. Default is 5.
|
| 199 |
+
|
| 200 |
+
Returns
|
| 201 |
+
-------
|
| 202 |
+
val : float
|
| 203 |
+
Gaussian quadrature approximation to the integral
|
| 204 |
+
none : None
|
| 205 |
+
Statically returned value of None
|
| 206 |
+
|
| 207 |
+
See Also
|
| 208 |
+
--------
|
| 209 |
+
quad : adaptive quadrature using QUADPACK
|
| 210 |
+
dblquad : double integrals
|
| 211 |
+
tplquad : triple integrals
|
| 212 |
+
romb : integrators for sampled data
|
| 213 |
+
simpson : integrators for sampled data
|
| 214 |
+
cumulative_trapezoid : cumulative integration for sampled data
|
| 215 |
+
|
| 216 |
+
Examples
|
| 217 |
+
--------
|
| 218 |
+
>>> from scipy import integrate
|
| 219 |
+
>>> import numpy as np
|
| 220 |
+
>>> f = lambda x: x**8
|
| 221 |
+
>>> integrate.fixed_quad(f, 0.0, 1.0, n=4)
|
| 222 |
+
(0.1110884353741496, None)
|
| 223 |
+
>>> integrate.fixed_quad(f, 0.0, 1.0, n=5)
|
| 224 |
+
(0.11111111111111102, None)
|
| 225 |
+
>>> print(1/9.0) # analytical result
|
| 226 |
+
0.1111111111111111
|
| 227 |
+
|
| 228 |
+
>>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=4)
|
| 229 |
+
(0.9999999771971152, None)
|
| 230 |
+
>>> integrate.fixed_quad(np.cos, 0.0, np.pi/2, n=5)
|
| 231 |
+
(1.000000000039565, None)
|
| 232 |
+
>>> np.sin(np.pi/2)-np.sin(0) # analytical result
|
| 233 |
+
1.0
|
| 234 |
+
|
| 235 |
+
"""
|
| 236 |
+
x, w = _cached_roots_legendre(n)
|
| 237 |
+
x = np.real(x)
|
| 238 |
+
if np.isinf(a) or np.isinf(b):
|
| 239 |
+
raise ValueError("Gaussian quadrature is only available for "
|
| 240 |
+
"finite limits.")
|
| 241 |
+
y = (b-a)*(x+1)/2.0 + a
|
| 242 |
+
return (b-a)/2.0 * np.sum(w*func(y, *args), axis=-1), None
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def tupleset(t, i, value):
|
| 246 |
+
l = list(t)
|
| 247 |
+
l[i] = value
|
| 248 |
+
return tuple(l)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def cumulative_trapezoid(y, x=None, dx=1.0, axis=-1, initial=None):
|
| 252 |
+
"""
|
| 253 |
+
Cumulatively integrate y(x) using the composite trapezoidal rule.
|
| 254 |
+
|
| 255 |
+
Parameters
|
| 256 |
+
----------
|
| 257 |
+
y : array_like
|
| 258 |
+
Values to integrate.
|
| 259 |
+
x : array_like, optional
|
| 260 |
+
The coordinate to integrate along. If None (default), use spacing `dx`
|
| 261 |
+
between consecutive elements in `y`.
|
| 262 |
+
dx : float, optional
|
| 263 |
+
Spacing between elements of `y`. Only used if `x` is None.
|
| 264 |
+
axis : int, optional
|
| 265 |
+
Specifies the axis to cumulate. Default is -1 (last axis).
|
| 266 |
+
initial : scalar, optional
|
| 267 |
+
If given, insert this value at the beginning of the returned result.
|
| 268 |
+
0 or None are the only values accepted. Default is None, which means
|
| 269 |
+
`res` has one element less than `y` along the axis of integration.
|
| 270 |
+
|
| 271 |
+
Returns
|
| 272 |
+
-------
|
| 273 |
+
res : ndarray
|
| 274 |
+
The result of cumulative integration of `y` along `axis`.
|
| 275 |
+
If `initial` is None, the shape is such that the axis of integration
|
| 276 |
+
has one less value than `y`. If `initial` is given, the shape is equal
|
| 277 |
+
to that of `y`.
|
| 278 |
+
|
| 279 |
+
See Also
|
| 280 |
+
--------
|
| 281 |
+
numpy.cumsum, numpy.cumprod
|
| 282 |
+
cumulative_simpson : cumulative integration using Simpson's 1/3 rule
|
| 283 |
+
quad : adaptive quadrature using QUADPACK
|
| 284 |
+
fixed_quad : fixed-order Gaussian quadrature
|
| 285 |
+
dblquad : double integrals
|
| 286 |
+
tplquad : triple integrals
|
| 287 |
+
romb : integrators for sampled data
|
| 288 |
+
|
| 289 |
+
Examples
|
| 290 |
+
--------
|
| 291 |
+
>>> from scipy import integrate
|
| 292 |
+
>>> import numpy as np
|
| 293 |
+
>>> import matplotlib.pyplot as plt
|
| 294 |
+
|
| 295 |
+
>>> x = np.linspace(-2, 2, num=20)
|
| 296 |
+
>>> y = x
|
| 297 |
+
>>> y_int = integrate.cumulative_trapezoid(y, x, initial=0)
|
| 298 |
+
>>> plt.plot(x, y_int, 'ro', x, y[0] + 0.5 * x**2, 'b-')
|
| 299 |
+
>>> plt.show()
|
| 300 |
+
|
| 301 |
+
"""
|
| 302 |
+
y = np.asarray(y)
|
| 303 |
+
if y.shape[axis] == 0:
|
| 304 |
+
raise ValueError("At least one point is required along `axis`.")
|
| 305 |
+
if x is None:
|
| 306 |
+
d = dx
|
| 307 |
+
else:
|
| 308 |
+
x = np.asarray(x)
|
| 309 |
+
if x.ndim == 1:
|
| 310 |
+
d = np.diff(x)
|
| 311 |
+
# reshape to correct shape
|
| 312 |
+
shape = [1] * y.ndim
|
| 313 |
+
shape[axis] = -1
|
| 314 |
+
d = d.reshape(shape)
|
| 315 |
+
elif len(x.shape) != len(y.shape):
|
| 316 |
+
raise ValueError("If given, shape of x must be 1-D or the "
|
| 317 |
+
"same as y.")
|
| 318 |
+
else:
|
| 319 |
+
d = np.diff(x, axis=axis)
|
| 320 |
+
|
| 321 |
+
if d.shape[axis] != y.shape[axis] - 1:
|
| 322 |
+
raise ValueError("If given, length of x along axis must be the "
|
| 323 |
+
"same as y.")
|
| 324 |
+
|
| 325 |
+
nd = len(y.shape)
|
| 326 |
+
slice1 = tupleset((slice(None),)*nd, axis, slice(1, None))
|
| 327 |
+
slice2 = tupleset((slice(None),)*nd, axis, slice(None, -1))
|
| 328 |
+
res = np.cumsum(d * (y[slice1] + y[slice2]) / 2.0, axis=axis)
|
| 329 |
+
|
| 330 |
+
if initial is not None:
|
| 331 |
+
if initial != 0:
|
| 332 |
+
raise ValueError("`initial` must be `None` or `0`.")
|
| 333 |
+
if not np.isscalar(initial):
|
| 334 |
+
raise ValueError("`initial` parameter should be a scalar.")
|
| 335 |
+
|
| 336 |
+
shape = list(res.shape)
|
| 337 |
+
shape[axis] = 1
|
| 338 |
+
res = np.concatenate([np.full(shape, initial, dtype=res.dtype), res],
|
| 339 |
+
axis=axis)
|
| 340 |
+
|
| 341 |
+
return res
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def _basic_simpson(y, start, stop, x, dx, axis):
|
| 345 |
+
nd = len(y.shape)
|
| 346 |
+
if start is None:
|
| 347 |
+
start = 0
|
| 348 |
+
step = 2
|
| 349 |
+
slice_all = (slice(None),)*nd
|
| 350 |
+
slice0 = tupleset(slice_all, axis, slice(start, stop, step))
|
| 351 |
+
slice1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
|
| 352 |
+
slice2 = tupleset(slice_all, axis, slice(start+2, stop+2, step))
|
| 353 |
+
|
| 354 |
+
if x is None: # Even-spaced Simpson's rule.
|
| 355 |
+
result = np.sum(y[slice0] + 4.0*y[slice1] + y[slice2], axis=axis)
|
| 356 |
+
result *= dx / 3.0
|
| 357 |
+
else:
|
| 358 |
+
# Account for possibly different spacings.
|
| 359 |
+
# Simpson's rule changes a bit.
|
| 360 |
+
h = np.diff(x, axis=axis)
|
| 361 |
+
sl0 = tupleset(slice_all, axis, slice(start, stop, step))
|
| 362 |
+
sl1 = tupleset(slice_all, axis, slice(start+1, stop+1, step))
|
| 363 |
+
h0 = h[sl0].astype(float, copy=False)
|
| 364 |
+
h1 = h[sl1].astype(float, copy=False)
|
| 365 |
+
hsum = h0 + h1
|
| 366 |
+
hprod = h0 * h1
|
| 367 |
+
h0divh1 = np.true_divide(h0, h1, out=np.zeros_like(h0), where=h1 != 0)
|
| 368 |
+
tmp = hsum/6.0 * (y[slice0] *
|
| 369 |
+
(2.0 - np.true_divide(1.0, h0divh1,
|
| 370 |
+
out=np.zeros_like(h0divh1),
|
| 371 |
+
where=h0divh1 != 0)) +
|
| 372 |
+
y[slice1] * (hsum *
|
| 373 |
+
np.true_divide(hsum, hprod,
|
| 374 |
+
out=np.zeros_like(hsum),
|
| 375 |
+
where=hprod != 0)) +
|
| 376 |
+
y[slice2] * (2.0 - h0divh1))
|
| 377 |
+
result = np.sum(tmp, axis=axis)
|
| 378 |
+
return result
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def simpson(y, x=None, *, dx=1.0, axis=-1):
|
| 382 |
+
"""
|
| 383 |
+
Integrate y(x) using samples along the given axis and the composite
|
| 384 |
+
Simpson's rule. If x is None, spacing of dx is assumed.
|
| 385 |
+
|
| 386 |
+
Parameters
|
| 387 |
+
----------
|
| 388 |
+
y : array_like
|
| 389 |
+
Array to be integrated.
|
| 390 |
+
x : array_like, optional
|
| 391 |
+
If given, the points at which `y` is sampled.
|
| 392 |
+
dx : float, optional
|
| 393 |
+
Spacing of integration points along axis of `x`. Only used when
|
| 394 |
+
`x` is None. Default is 1.
|
| 395 |
+
axis : int, optional
|
| 396 |
+
Axis along which to integrate. Default is the last axis.
|
| 397 |
+
|
| 398 |
+
Returns
|
| 399 |
+
-------
|
| 400 |
+
float
|
| 401 |
+
The estimated integral computed with the composite Simpson's rule.
|
| 402 |
+
|
| 403 |
+
See Also
|
| 404 |
+
--------
|
| 405 |
+
quad : adaptive quadrature using QUADPACK
|
| 406 |
+
fixed_quad : fixed-order Gaussian quadrature
|
| 407 |
+
dblquad : double integrals
|
| 408 |
+
tplquad : triple integrals
|
| 409 |
+
romb : integrators for sampled data
|
| 410 |
+
cumulative_trapezoid : cumulative integration for sampled data
|
| 411 |
+
cumulative_simpson : cumulative integration using Simpson's 1/3 rule
|
| 412 |
+
|
| 413 |
+
Notes
|
| 414 |
+
-----
|
| 415 |
+
For an odd number of samples that are equally spaced the result is
|
| 416 |
+
exact if the function is a polynomial of order 3 or less. If
|
| 417 |
+
the samples are not equally spaced, then the result is exact only
|
| 418 |
+
if the function is a polynomial of order 2 or less.
|
| 419 |
+
|
| 420 |
+
References
|
| 421 |
+
----------
|
| 422 |
+
.. [1] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
|
| 423 |
+
MS Excel and Irregularly-spaced Data. Journal of Mathematical
|
| 424 |
+
Sciences and Mathematics Education. 12 (2): 1-9
|
| 425 |
+
|
| 426 |
+
Examples
|
| 427 |
+
--------
|
| 428 |
+
>>> from scipy import integrate
|
| 429 |
+
>>> import numpy as np
|
| 430 |
+
>>> x = np.arange(0, 10)
|
| 431 |
+
>>> y = np.arange(0, 10)
|
| 432 |
+
|
| 433 |
+
>>> integrate.simpson(y, x=x)
|
| 434 |
+
40.5
|
| 435 |
+
|
| 436 |
+
>>> y = np.power(x, 3)
|
| 437 |
+
>>> integrate.simpson(y, x=x)
|
| 438 |
+
1640.5
|
| 439 |
+
>>> integrate.quad(lambda x: x**3, 0, 9)[0]
|
| 440 |
+
1640.25
|
| 441 |
+
|
| 442 |
+
"""
|
| 443 |
+
y = np.asarray(y)
|
| 444 |
+
nd = len(y.shape)
|
| 445 |
+
N = y.shape[axis]
|
| 446 |
+
last_dx = dx
|
| 447 |
+
returnshape = 0
|
| 448 |
+
if x is not None:
|
| 449 |
+
x = np.asarray(x)
|
| 450 |
+
if len(x.shape) == 1:
|
| 451 |
+
shapex = [1] * nd
|
| 452 |
+
shapex[axis] = x.shape[0]
|
| 453 |
+
saveshape = x.shape
|
| 454 |
+
returnshape = 1
|
| 455 |
+
x = x.reshape(tuple(shapex))
|
| 456 |
+
elif len(x.shape) != len(y.shape):
|
| 457 |
+
raise ValueError("If given, shape of x must be 1-D or the "
|
| 458 |
+
"same as y.")
|
| 459 |
+
if x.shape[axis] != N:
|
| 460 |
+
raise ValueError("If given, length of x along axis must be the "
|
| 461 |
+
"same as y.")
|
| 462 |
+
|
| 463 |
+
if N % 2 == 0:
|
| 464 |
+
val = 0.0
|
| 465 |
+
result = 0.0
|
| 466 |
+
slice_all = (slice(None),) * nd
|
| 467 |
+
|
| 468 |
+
if N == 2:
|
| 469 |
+
# need at least 3 points in integration axis to form parabolic
|
| 470 |
+
# segment. If there are two points then any of 'avg', 'first',
|
| 471 |
+
# 'last' should give the same result.
|
| 472 |
+
slice1 = tupleset(slice_all, axis, -1)
|
| 473 |
+
slice2 = tupleset(slice_all, axis, -2)
|
| 474 |
+
if x is not None:
|
| 475 |
+
last_dx = x[slice1] - x[slice2]
|
| 476 |
+
val += 0.5 * last_dx * (y[slice1] + y[slice2])
|
| 477 |
+
else:
|
| 478 |
+
# use Simpson's rule on first intervals
|
| 479 |
+
result = _basic_simpson(y, 0, N-3, x, dx, axis)
|
| 480 |
+
|
| 481 |
+
slice1 = tupleset(slice_all, axis, -1)
|
| 482 |
+
slice2 = tupleset(slice_all, axis, -2)
|
| 483 |
+
slice3 = tupleset(slice_all, axis, -3)
|
| 484 |
+
|
| 485 |
+
h = np.asarray([dx, dx], dtype=np.float64)
|
| 486 |
+
if x is not None:
|
| 487 |
+
# grab the last two spacings from the appropriate axis
|
| 488 |
+
hm2 = tupleset(slice_all, axis, slice(-2, -1, 1))
|
| 489 |
+
hm1 = tupleset(slice_all, axis, slice(-1, None, 1))
|
| 490 |
+
|
| 491 |
+
diffs = np.float64(np.diff(x, axis=axis))
|
| 492 |
+
h = [np.squeeze(diffs[hm2], axis=axis),
|
| 493 |
+
np.squeeze(diffs[hm1], axis=axis)]
|
| 494 |
+
|
| 495 |
+
# This is the correction for the last interval according to
|
| 496 |
+
# Cartwright.
|
| 497 |
+
# However, I used the equations given at
|
| 498 |
+
# https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule_for_irregularly_spaced_data
|
| 499 |
+
# A footnote on Wikipedia says:
|
| 500 |
+
# Cartwright 2017, Equation 8. The equation in Cartwright is
|
| 501 |
+
# calculating the first interval whereas the equations in the
|
| 502 |
+
# Wikipedia article are adjusting for the last integral. If the
|
| 503 |
+
# proper algebraic substitutions are made, the equation results in
|
| 504 |
+
# the values shown.
|
| 505 |
+
num = 2 * h[1] ** 2 + 3 * h[0] * h[1]
|
| 506 |
+
den = 6 * (h[1] + h[0])
|
| 507 |
+
alpha = np.true_divide(
|
| 508 |
+
num,
|
| 509 |
+
den,
|
| 510 |
+
out=np.zeros_like(den),
|
| 511 |
+
where=den != 0
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
num = h[1] ** 2 + 3.0 * h[0] * h[1]
|
| 515 |
+
den = 6 * h[0]
|
| 516 |
+
beta = np.true_divide(
|
| 517 |
+
num,
|
| 518 |
+
den,
|
| 519 |
+
out=np.zeros_like(den),
|
| 520 |
+
where=den != 0
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
num = 1 * h[1] ** 3
|
| 524 |
+
den = 6 * h[0] * (h[0] + h[1])
|
| 525 |
+
eta = np.true_divide(
|
| 526 |
+
num,
|
| 527 |
+
den,
|
| 528 |
+
out=np.zeros_like(den),
|
| 529 |
+
where=den != 0
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
result += alpha*y[slice1] + beta*y[slice2] - eta*y[slice3]
|
| 533 |
+
|
| 534 |
+
result += val
|
| 535 |
+
else:
|
| 536 |
+
result = _basic_simpson(y, 0, N-2, x, dx, axis)
|
| 537 |
+
if returnshape:
|
| 538 |
+
x = x.reshape(saveshape)
|
| 539 |
+
return result
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def _cumulatively_sum_simpson_integrals(
|
| 543 |
+
y: np.ndarray,
|
| 544 |
+
dx: np.ndarray,
|
| 545 |
+
integration_func: Callable[[np.ndarray, np.ndarray], np.ndarray],
|
| 546 |
+
) -> np.ndarray:
|
| 547 |
+
"""Calculate cumulative sum of Simpson integrals.
|
| 548 |
+
Takes as input the integration function to be used.
|
| 549 |
+
The integration_func is assumed to return the cumulative sum using
|
| 550 |
+
composite Simpson's rule. Assumes the axis of summation is -1.
|
| 551 |
+
"""
|
| 552 |
+
sub_integrals_h1 = integration_func(y, dx)
|
| 553 |
+
sub_integrals_h2 = integration_func(y[..., ::-1], dx[..., ::-1])[..., ::-1]
|
| 554 |
+
|
| 555 |
+
shape = list(sub_integrals_h1.shape)
|
| 556 |
+
shape[-1] += 1
|
| 557 |
+
sub_integrals = np.empty(shape)
|
| 558 |
+
sub_integrals[..., :-1:2] = sub_integrals_h1[..., ::2]
|
| 559 |
+
sub_integrals[..., 1::2] = sub_integrals_h2[..., ::2]
|
| 560 |
+
# Integral over last subinterval can only be calculated from
|
| 561 |
+
# formula for h2
|
| 562 |
+
sub_integrals[..., -1] = sub_integrals_h2[..., -1]
|
| 563 |
+
res = np.cumsum(sub_integrals, axis=-1)
|
| 564 |
+
return res
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
def _cumulative_simpson_equal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
|
| 568 |
+
"""Calculate the Simpson integrals for all h1 intervals assuming equal interval
|
| 569 |
+
widths. The function can also be used to calculate the integral for all
|
| 570 |
+
h2 intervals by reversing the inputs, `y` and `dx`.
|
| 571 |
+
"""
|
| 572 |
+
d = dx[..., :-1]
|
| 573 |
+
f1 = y[..., :-2]
|
| 574 |
+
f2 = y[..., 1:-1]
|
| 575 |
+
f3 = y[..., 2:]
|
| 576 |
+
|
| 577 |
+
# Calculate integral over the subintervals (eqn (10) of Reference [2])
|
| 578 |
+
return d / 3 * (5 * f1 / 4 + 2 * f2 - f3 / 4)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def _cumulative_simpson_unequal_intervals(y: np.ndarray, dx: np.ndarray) -> np.ndarray:
|
| 582 |
+
"""Calculate the Simpson integrals for all h1 intervals assuming unequal interval
|
| 583 |
+
widths. The function can also be used to calculate the integral for all
|
| 584 |
+
h2 intervals by reversing the inputs, `y` and `dx`.
|
| 585 |
+
"""
|
| 586 |
+
x21 = dx[..., :-1]
|
| 587 |
+
x32 = dx[..., 1:]
|
| 588 |
+
f1 = y[..., :-2]
|
| 589 |
+
f2 = y[..., 1:-1]
|
| 590 |
+
f3 = y[..., 2:]
|
| 591 |
+
|
| 592 |
+
x31 = x21 + x32
|
| 593 |
+
x21_x31 = x21/x31
|
| 594 |
+
x21_x32 = x21/x32
|
| 595 |
+
x21x21_x31x32 = x21_x31 * x21_x32
|
| 596 |
+
|
| 597 |
+
# Calculate integral over the subintervals (eqn (8) of Reference [2])
|
| 598 |
+
coeff1 = 3 - x21_x31
|
| 599 |
+
coeff2 = 3 + x21x21_x31x32 + x21_x31
|
| 600 |
+
coeff3 = -x21x21_x31x32
|
| 601 |
+
|
| 602 |
+
return x21/6 * (coeff1*f1 + coeff2*f2 + coeff3*f3)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def _ensure_float_array(arr: npt.ArrayLike) -> np.ndarray:
|
| 606 |
+
arr = np.asarray(arr)
|
| 607 |
+
if np.issubdtype(arr.dtype, np.integer):
|
| 608 |
+
arr = arr.astype(float, copy=False)
|
| 609 |
+
return arr
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def cumulative_simpson(y, *, x=None, dx=1.0, axis=-1, initial=None):
|
| 613 |
+
r"""
|
| 614 |
+
Cumulatively integrate y(x) using the composite Simpson's 1/3 rule.
|
| 615 |
+
The integral of the samples at every point is calculated by assuming a
|
| 616 |
+
quadratic relationship between each point and the two adjacent points.
|
| 617 |
+
|
| 618 |
+
Parameters
|
| 619 |
+
----------
|
| 620 |
+
y : array_like
|
| 621 |
+
Values to integrate. Requires at least one point along `axis`. If two or fewer
|
| 622 |
+
points are provided along `axis`, Simpson's integration is not possible and the
|
| 623 |
+
result is calculated with `cumulative_trapezoid`.
|
| 624 |
+
x : array_like, optional
|
| 625 |
+
The coordinate to integrate along. Must have the same shape as `y` or
|
| 626 |
+
must be 1D with the same length as `y` along `axis`. `x` must also be
|
| 627 |
+
strictly increasing along `axis`.
|
| 628 |
+
If `x` is None (default), integration is performed using spacing `dx`
|
| 629 |
+
between consecutive elements in `y`.
|
| 630 |
+
dx : scalar or array_like, optional
|
| 631 |
+
Spacing between elements of `y`. Only used if `x` is None. Can either
|
| 632 |
+
be a float, or an array with the same shape as `y`, but of length one along
|
| 633 |
+
`axis`. Default is 1.0.
|
| 634 |
+
axis : int, optional
|
| 635 |
+
Specifies the axis to integrate along. Default is -1 (last axis).
|
| 636 |
+
initial : scalar or array_like, optional
|
| 637 |
+
If given, insert this value at the beginning of the returned result,
|
| 638 |
+
and add it to the rest of the result. Default is None, which means no
|
| 639 |
+
value at ``x[0]`` is returned and `res` has one element less than `y`
|
| 640 |
+
along the axis of integration. Can either be a float, or an array with
|
| 641 |
+
the same shape as `y`, but of length one along `axis`.
|
| 642 |
+
|
| 643 |
+
Returns
|
| 644 |
+
-------
|
| 645 |
+
res : ndarray
|
| 646 |
+
The result of cumulative integration of `y` along `axis`.
|
| 647 |
+
If `initial` is None, the shape is such that the axis of integration
|
| 648 |
+
has one less value than `y`. If `initial` is given, the shape is equal
|
| 649 |
+
to that of `y`.
|
| 650 |
+
|
| 651 |
+
See Also
|
| 652 |
+
--------
|
| 653 |
+
numpy.cumsum
|
| 654 |
+
cumulative_trapezoid : cumulative integration using the composite
|
| 655 |
+
trapezoidal rule
|
| 656 |
+
simpson : integrator for sampled data using the Composite Simpson's Rule
|
| 657 |
+
|
| 658 |
+
Notes
|
| 659 |
+
-----
|
| 660 |
+
|
| 661 |
+
.. versionadded:: 1.12.0
|
| 662 |
+
|
| 663 |
+
The composite Simpson's 1/3 method can be used to approximate the definite
|
| 664 |
+
integral of a sampled input function :math:`y(x)` [1]_. The method assumes
|
| 665 |
+
a quadratic relationship over the interval containing any three consecutive
|
| 666 |
+
sampled points.
|
| 667 |
+
|
| 668 |
+
Consider three consecutive points:
|
| 669 |
+
:math:`(x_1, y_1), (x_2, y_2), (x_3, y_3)`.
|
| 670 |
+
|
| 671 |
+
Assuming a quadratic relationship over the three points, the integral over
|
| 672 |
+
the subinterval between :math:`x_1` and :math:`x_2` is given by formula
|
| 673 |
+
(8) of [2]_:
|
| 674 |
+
|
| 675 |
+
.. math::
|
| 676 |
+
\int_{x_1}^{x_2} y(x) dx\ &= \frac{x_2-x_1}{6}\left[\
|
| 677 |
+
\left\{3-\frac{x_2-x_1}{x_3-x_1}\right\} y_1 + \
|
| 678 |
+
\left\{3 + \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} + \
|
| 679 |
+
\frac{x_2-x_1}{x_3-x_1}\right\} y_2\\
|
| 680 |
+
- \frac{(x_2-x_1)^2}{(x_3-x_2)(x_3-x_1)} y_3\right]
|
| 681 |
+
|
| 682 |
+
The integral between :math:`x_2` and :math:`x_3` is given by swapping
|
| 683 |
+
appearances of :math:`x_1` and :math:`x_3`. The integral is estimated
|
| 684 |
+
separately for each subinterval and then cumulatively summed to obtain
|
| 685 |
+
the final result.
|
| 686 |
+
|
| 687 |
+
For samples that are equally spaced, the result is exact if the function
|
| 688 |
+
is a polynomial of order three or less [1]_ and the number of subintervals
|
| 689 |
+
is even. Otherwise, the integral is exact for polynomials of order two or
|
| 690 |
+
less.
|
| 691 |
+
|
| 692 |
+
References
|
| 693 |
+
----------
|
| 694 |
+
.. [1] Wikipedia page: https://en.wikipedia.org/wiki/Simpson's_rule
|
| 695 |
+
.. [2] Cartwright, Kenneth V. Simpson's Rule Cumulative Integration with
|
| 696 |
+
MS Excel and Irregularly-spaced Data. Journal of Mathematical
|
| 697 |
+
Sciences and Mathematics Education. 12 (2): 1-9
|
| 698 |
+
|
| 699 |
+
Examples
|
| 700 |
+
--------
|
| 701 |
+
>>> from scipy import integrate
|
| 702 |
+
>>> import numpy as np
|
| 703 |
+
>>> import matplotlib.pyplot as plt
|
| 704 |
+
>>> x = np.linspace(-2, 2, num=20)
|
| 705 |
+
>>> y = x**2
|
| 706 |
+
>>> y_int = integrate.cumulative_simpson(y, x=x, initial=0)
|
| 707 |
+
>>> fig, ax = plt.subplots()
|
| 708 |
+
>>> ax.plot(x, y_int, 'ro', x, x**3/3 - (x[0])**3/3, 'b-')
|
| 709 |
+
>>> ax.grid()
|
| 710 |
+
>>> plt.show()
|
| 711 |
+
|
| 712 |
+
The output of `cumulative_simpson` is similar to that of iteratively
|
| 713 |
+
calling `simpson` with successively higher upper limits of integration, but
|
| 714 |
+
not identical.
|
| 715 |
+
|
| 716 |
+
>>> def cumulative_simpson_reference(y, x):
|
| 717 |
+
... return np.asarray([integrate.simpson(y[:i], x=x[:i])
|
| 718 |
+
... for i in range(2, len(y) + 1)])
|
| 719 |
+
>>>
|
| 720 |
+
>>> rng = np.random.default_rng(354673834679465)
|
| 721 |
+
>>> x, y = rng.random(size=(2, 10))
|
| 722 |
+
>>> x.sort()
|
| 723 |
+
>>>
|
| 724 |
+
>>> res = integrate.cumulative_simpson(y, x=x)
|
| 725 |
+
>>> ref = cumulative_simpson_reference(y, x)
|
| 726 |
+
>>> equal = np.abs(res - ref) < 1e-15
|
| 727 |
+
>>> equal # not equal when `simpson` has even number of subintervals
|
| 728 |
+
array([False, True, False, True, False, True, False, True, True])
|
| 729 |
+
|
| 730 |
+
This is expected: because `cumulative_simpson` has access to more
|
| 731 |
+
information than `simpson`, it can typically produce more accurate
|
| 732 |
+
estimates of the underlying integral over subintervals.
|
| 733 |
+
|
| 734 |
+
"""
|
| 735 |
+
y = _ensure_float_array(y)
|
| 736 |
+
|
| 737 |
+
# validate `axis` and standardize to work along the last axis
|
| 738 |
+
original_y = y
|
| 739 |
+
original_shape = y.shape
|
| 740 |
+
try:
|
| 741 |
+
y = np.swapaxes(y, axis, -1)
|
| 742 |
+
except IndexError as e:
|
| 743 |
+
message = f"`axis={axis}` is not valid for `y` with `y.ndim={y.ndim}`."
|
| 744 |
+
raise ValueError(message) from e
|
| 745 |
+
if y.shape[-1] < 3:
|
| 746 |
+
res = cumulative_trapezoid(original_y, x, dx=dx, axis=axis, initial=None)
|
| 747 |
+
res = np.swapaxes(res, axis, -1)
|
| 748 |
+
|
| 749 |
+
elif x is not None:
|
| 750 |
+
x = _ensure_float_array(x)
|
| 751 |
+
message = ("If given, shape of `x` must be the same as `y` or 1-D with "
|
| 752 |
+
"the same length as `y` along `axis`.")
|
| 753 |
+
if not (x.shape == original_shape
|
| 754 |
+
or (x.ndim == 1 and len(x) == original_shape[axis])):
|
| 755 |
+
raise ValueError(message)
|
| 756 |
+
|
| 757 |
+
x = np.broadcast_to(x, y.shape) if x.ndim == 1 else np.swapaxes(x, axis, -1)
|
| 758 |
+
dx = np.diff(x, axis=-1)
|
| 759 |
+
if np.any(dx <= 0):
|
| 760 |
+
raise ValueError("Input x must be strictly increasing.")
|
| 761 |
+
res = _cumulatively_sum_simpson_integrals(
|
| 762 |
+
y, dx, _cumulative_simpson_unequal_intervals
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
else:
|
| 766 |
+
dx = _ensure_float_array(dx)
|
| 767 |
+
final_dx_shape = tupleset(original_shape, axis, original_shape[axis] - 1)
|
| 768 |
+
alt_input_dx_shape = tupleset(original_shape, axis, 1)
|
| 769 |
+
message = ("If provided, `dx` must either be a scalar or have the same "
|
| 770 |
+
"shape as `y` but with only 1 point along `axis`.")
|
| 771 |
+
if not (dx.ndim == 0 or dx.shape == alt_input_dx_shape):
|
| 772 |
+
raise ValueError(message)
|
| 773 |
+
dx = np.broadcast_to(dx, final_dx_shape)
|
| 774 |
+
dx = np.swapaxes(dx, axis, -1)
|
| 775 |
+
res = _cumulatively_sum_simpson_integrals(
|
| 776 |
+
y, dx, _cumulative_simpson_equal_intervals
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
if initial is not None:
|
| 780 |
+
initial = _ensure_float_array(initial)
|
| 781 |
+
alt_initial_input_shape = tupleset(original_shape, axis, 1)
|
| 782 |
+
message = ("If provided, `initial` must either be a scalar or have the "
|
| 783 |
+
"same shape as `y` but with only 1 point along `axis`.")
|
| 784 |
+
if not (initial.ndim == 0 or initial.shape == alt_initial_input_shape):
|
| 785 |
+
raise ValueError(message)
|
| 786 |
+
initial = np.broadcast_to(initial, alt_initial_input_shape)
|
| 787 |
+
initial = np.swapaxes(initial, axis, -1)
|
| 788 |
+
|
| 789 |
+
res += initial
|
| 790 |
+
res = np.concatenate((initial, res), axis=-1)
|
| 791 |
+
|
| 792 |
+
res = np.swapaxes(res, -1, axis)
|
| 793 |
+
return res
|
| 794 |
+
|
| 795 |
+
|
| 796 |
+
def romb(y, dx=1.0, axis=-1, show=False):
|
| 797 |
+
"""
|
| 798 |
+
Romberg integration using samples of a function.
|
| 799 |
+
|
| 800 |
+
Parameters
|
| 801 |
+
----------
|
| 802 |
+
y : array_like
|
| 803 |
+
A vector of ``2**k + 1`` equally-spaced samples of a function.
|
| 804 |
+
dx : float, optional
|
| 805 |
+
The sample spacing. Default is 1.
|
| 806 |
+
axis : int, optional
|
| 807 |
+
The axis along which to integrate. Default is -1 (last axis).
|
| 808 |
+
show : bool, optional
|
| 809 |
+
When `y` is a single 1-D array, then if this argument is True
|
| 810 |
+
print the table showing Richardson extrapolation from the
|
| 811 |
+
samples. Default is False.
|
| 812 |
+
|
| 813 |
+
Returns
|
| 814 |
+
-------
|
| 815 |
+
romb : ndarray
|
| 816 |
+
The integrated result for `axis`.
|
| 817 |
+
|
| 818 |
+
See Also
|
| 819 |
+
--------
|
| 820 |
+
quad : adaptive quadrature using QUADPACK
|
| 821 |
+
fixed_quad : fixed-order Gaussian quadrature
|
| 822 |
+
dblquad : double integrals
|
| 823 |
+
tplquad : triple integrals
|
| 824 |
+
simpson : integrators for sampled data
|
| 825 |
+
cumulative_trapezoid : cumulative integration for sampled data
|
| 826 |
+
|
| 827 |
+
Examples
|
| 828 |
+
--------
|
| 829 |
+
>>> from scipy import integrate
|
| 830 |
+
>>> import numpy as np
|
| 831 |
+
>>> x = np.arange(10, 14.25, 0.25)
|
| 832 |
+
>>> y = np.arange(3, 12)
|
| 833 |
+
|
| 834 |
+
>>> integrate.romb(y)
|
| 835 |
+
56.0
|
| 836 |
+
|
| 837 |
+
>>> y = np.sin(np.power(x, 2.5))
|
| 838 |
+
>>> integrate.romb(y)
|
| 839 |
+
-0.742561336672229
|
| 840 |
+
|
| 841 |
+
>>> integrate.romb(y, show=True)
|
| 842 |
+
Richardson Extrapolation Table for Romberg Integration
|
| 843 |
+
======================================================
|
| 844 |
+
-0.81576
|
| 845 |
+
4.63862 6.45674
|
| 846 |
+
-1.10581 -3.02062 -3.65245
|
| 847 |
+
-2.57379 -3.06311 -3.06595 -3.05664
|
| 848 |
+
-1.34093 -0.92997 -0.78776 -0.75160 -0.74256
|
| 849 |
+
======================================================
|
| 850 |
+
-0.742561336672229 # may vary
|
| 851 |
+
|
| 852 |
+
"""
|
| 853 |
+
y = np.asarray(y)
|
| 854 |
+
nd = len(y.shape)
|
| 855 |
+
Nsamps = y.shape[axis]
|
| 856 |
+
Ninterv = Nsamps-1
|
| 857 |
+
n = 1
|
| 858 |
+
k = 0
|
| 859 |
+
while n < Ninterv:
|
| 860 |
+
n <<= 1
|
| 861 |
+
k += 1
|
| 862 |
+
if n != Ninterv:
|
| 863 |
+
raise ValueError("Number of samples must be one plus a "
|
| 864 |
+
"non-negative power of 2.")
|
| 865 |
+
|
| 866 |
+
R = {}
|
| 867 |
+
slice_all = (slice(None),) * nd
|
| 868 |
+
slice0 = tupleset(slice_all, axis, 0)
|
| 869 |
+
slicem1 = tupleset(slice_all, axis, -1)
|
| 870 |
+
h = Ninterv * np.asarray(dx, dtype=float)
|
| 871 |
+
R[(0, 0)] = (y[slice0] + y[slicem1])/2.0*h
|
| 872 |
+
slice_R = slice_all
|
| 873 |
+
start = stop = step = Ninterv
|
| 874 |
+
for i in range(1, k+1):
|
| 875 |
+
start >>= 1
|
| 876 |
+
slice_R = tupleset(slice_R, axis, slice(start, stop, step))
|
| 877 |
+
step >>= 1
|
| 878 |
+
R[(i, 0)] = 0.5*(R[(i-1, 0)] + h*y[slice_R].sum(axis=axis))
|
| 879 |
+
for j in range(1, i+1):
|
| 880 |
+
prev = R[(i, j-1)]
|
| 881 |
+
R[(i, j)] = prev + (prev-R[(i-1, j-1)]) / ((1 << (2*j))-1)
|
| 882 |
+
h /= 2.0
|
| 883 |
+
|
| 884 |
+
if show:
|
| 885 |
+
if not np.isscalar(R[(0, 0)]):
|
| 886 |
+
print("*** Printing table only supported for integrals" +
|
| 887 |
+
" of a single data set.")
|
| 888 |
+
else:
|
| 889 |
+
try:
|
| 890 |
+
precis = show[0]
|
| 891 |
+
except (TypeError, IndexError):
|
| 892 |
+
precis = 5
|
| 893 |
+
try:
|
| 894 |
+
width = show[1]
|
| 895 |
+
except (TypeError, IndexError):
|
| 896 |
+
width = 8
|
| 897 |
+
formstr = "%%%d.%df" % (width, precis)
|
| 898 |
+
|
| 899 |
+
title = "Richardson Extrapolation Table for Romberg Integration"
|
| 900 |
+
print(title, "=" * len(title), sep="\n", end="\n")
|
| 901 |
+
for i in range(k+1):
|
| 902 |
+
for j in range(i+1):
|
| 903 |
+
print(formstr % R[(i, j)], end=" ")
|
| 904 |
+
print()
|
| 905 |
+
print("=" * len(title))
|
| 906 |
+
|
| 907 |
+
return R[(k, k)]
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
# Coefficients for Newton-Cotes quadrature
|
| 911 |
+
#
|
| 912 |
+
# These are the points being used
|
| 913 |
+
# to construct the local interpolating polynomial
|
| 914 |
+
# a are the weights for Newton-Cotes integration
|
| 915 |
+
# B is the error coefficient.
|
| 916 |
+
# error in these coefficients grows as N gets larger.
|
| 917 |
+
# or as samples are closer and closer together
|
| 918 |
+
|
| 919 |
+
# You can use maxima to find these rational coefficients
|
| 920 |
+
# for equally spaced data using the commands
|
| 921 |
+
# a(i,N) := (integrate(product(r-j,j,0,i-1) * product(r-j,j,i+1,N),r,0,N)
|
| 922 |
+
# / ((N-i)! * i!) * (-1)^(N-i));
|
| 923 |
+
# Be(N) := N^(N+2)/(N+2)! * (N/(N+3) - sum((i/N)^(N+2)*a(i,N),i,0,N));
|
| 924 |
+
# Bo(N) := N^(N+1)/(N+1)! * (N/(N+2) - sum((i/N)^(N+1)*a(i,N),i,0,N));
|
| 925 |
+
# B(N) := (if (mod(N,2)=0) then Be(N) else Bo(N));
|
| 926 |
+
#
|
| 927 |
+
# pre-computed for equally-spaced weights
|
| 928 |
+
#
|
| 929 |
+
# num_a, den_a, int_a, num_B, den_B = _builtincoeffs[N]
|
| 930 |
+
#
|
| 931 |
+
# a = num_a*array(int_a)/den_a
|
| 932 |
+
# B = num_B*1.0 / den_B
|
| 933 |
+
#
|
| 934 |
+
# integrate(f(x),x,x_0,x_N) = dx*sum(a*f(x_i)) + B*(dx)^(2k+3) f^(2k+2)(x*)
|
| 935 |
+
# where k = N // 2
|
| 936 |
+
#
|
| 937 |
+
_builtincoeffs = {
|
| 938 |
+
1: (1,2,[1,1],-1,12),
|
| 939 |
+
2: (1,3,[1,4,1],-1,90),
|
| 940 |
+
3: (3,8,[1,3,3,1],-3,80),
|
| 941 |
+
4: (2,45,[7,32,12,32,7],-8,945),
|
| 942 |
+
5: (5,288,[19,75,50,50,75,19],-275,12096),
|
| 943 |
+
6: (1,140,[41,216,27,272,27,216,41],-9,1400),
|
| 944 |
+
7: (7,17280,[751,3577,1323,2989,2989,1323,3577,751],-8183,518400),
|
| 945 |
+
8: (4,14175,[989,5888,-928,10496,-4540,10496,-928,5888,989],
|
| 946 |
+
-2368,467775),
|
| 947 |
+
9: (9,89600,[2857,15741,1080,19344,5778,5778,19344,1080,
|
| 948 |
+
15741,2857], -4671, 394240),
|
| 949 |
+
10: (5,299376,[16067,106300,-48525,272400,-260550,427368,
|
| 950 |
+
-260550,272400,-48525,106300,16067],
|
| 951 |
+
-673175, 163459296),
|
| 952 |
+
11: (11,87091200,[2171465,13486539,-3237113, 25226685,-9595542,
|
| 953 |
+
15493566,15493566,-9595542,25226685,-3237113,
|
| 954 |
+
13486539,2171465], -2224234463, 237758976000),
|
| 955 |
+
12: (1, 5255250, [1364651,9903168,-7587864,35725120,-51491295,
|
| 956 |
+
87516288,-87797136,87516288,-51491295,35725120,
|
| 957 |
+
-7587864,9903168,1364651], -3012, 875875),
|
| 958 |
+
13: (13, 402361344000,[8181904909, 56280729661, -31268252574,
|
| 959 |
+
156074417954,-151659573325,206683437987,
|
| 960 |
+
-43111992612,-43111992612,206683437987,
|
| 961 |
+
-151659573325,156074417954,-31268252574,
|
| 962 |
+
56280729661,8181904909], -2639651053,
|
| 963 |
+
344881152000),
|
| 964 |
+
14: (7, 2501928000, [90241897,710986864,-770720657,3501442784,
|
| 965 |
+
-6625093363,12630121616,-16802270373,19534438464,
|
| 966 |
+
-16802270373,12630121616,-6625093363,3501442784,
|
| 967 |
+
-770720657,710986864,90241897], -3740727473,
|
| 968 |
+
1275983280000)
|
| 969 |
+
}
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
def newton_cotes(rn, equal=0):
|
| 973 |
+
r"""
|
| 974 |
+
Return weights and error coefficient for Newton-Cotes integration.
|
| 975 |
+
|
| 976 |
+
Suppose we have (N+1) samples of f at the positions
|
| 977 |
+
x_0, x_1, ..., x_N. Then an N-point Newton-Cotes formula for the
|
| 978 |
+
integral between x_0 and x_N is:
|
| 979 |
+
|
| 980 |
+
:math:`\int_{x_0}^{x_N} f(x)dx = \Delta x \sum_{i=0}^{N} a_i f(x_i)
|
| 981 |
+
+ B_N (\Delta x)^{N+2} f^{N+1} (\xi)`
|
| 982 |
+
|
| 983 |
+
where :math:`\xi \in [x_0,x_N]`
|
| 984 |
+
and :math:`\Delta x = \frac{x_N-x_0}{N}` is the average samples spacing.
|
| 985 |
+
|
| 986 |
+
If the samples are equally-spaced and N is even, then the error
|
| 987 |
+
term is :math:`B_N (\Delta x)^{N+3} f^{N+2}(\xi)`.
|
| 988 |
+
|
| 989 |
+
Parameters
|
| 990 |
+
----------
|
| 991 |
+
rn : int
|
| 992 |
+
The integer order for equally-spaced data or the relative positions of
|
| 993 |
+
the samples with the first sample at 0 and the last at N, where N+1 is
|
| 994 |
+
the length of `rn`. N is the order of the Newton-Cotes integration.
|
| 995 |
+
equal : int, optional
|
| 996 |
+
Set to 1 to enforce equally spaced data.
|
| 997 |
+
|
| 998 |
+
Returns
|
| 999 |
+
-------
|
| 1000 |
+
an : ndarray
|
| 1001 |
+
1-D array of weights to apply to the function at the provided sample
|
| 1002 |
+
positions.
|
| 1003 |
+
B : float
|
| 1004 |
+
Error coefficient.
|
| 1005 |
+
|
| 1006 |
+
Notes
|
| 1007 |
+
-----
|
| 1008 |
+
Normally, the Newton-Cotes rules are used on smaller integration
|
| 1009 |
+
regions and a composite rule is used to return the total integral.
|
| 1010 |
+
|
| 1011 |
+
Examples
|
| 1012 |
+
--------
|
| 1013 |
+
Compute the integral of sin(x) in [0, :math:`\pi`]:
|
| 1014 |
+
|
| 1015 |
+
>>> from scipy.integrate import newton_cotes
|
| 1016 |
+
>>> import numpy as np
|
| 1017 |
+
>>> def f(x):
|
| 1018 |
+
... return np.sin(x)
|
| 1019 |
+
>>> a = 0
|
| 1020 |
+
>>> b = np.pi
|
| 1021 |
+
>>> exact = 2
|
| 1022 |
+
>>> for N in [2, 4, 6, 8, 10]:
|
| 1023 |
+
... x = np.linspace(a, b, N + 1)
|
| 1024 |
+
... an, B = newton_cotes(N, 1)
|
| 1025 |
+
... dx = (b - a) / N
|
| 1026 |
+
... quad = dx * np.sum(an * f(x))
|
| 1027 |
+
... error = abs(quad - exact)
|
| 1028 |
+
... print('{:2d} {:10.9f} {:.5e}'.format(N, quad, error))
|
| 1029 |
+
...
|
| 1030 |
+
2 2.094395102 9.43951e-02
|
| 1031 |
+
4 1.998570732 1.42927e-03
|
| 1032 |
+
6 2.000017814 1.78136e-05
|
| 1033 |
+
8 1.999999835 1.64725e-07
|
| 1034 |
+
10 2.000000001 1.14677e-09
|
| 1035 |
+
|
| 1036 |
+
"""
|
| 1037 |
+
try:
|
| 1038 |
+
N = len(rn)-1
|
| 1039 |
+
if equal:
|
| 1040 |
+
rn = np.arange(N+1)
|
| 1041 |
+
elif np.all(np.diff(rn) == 1):
|
| 1042 |
+
equal = 1
|
| 1043 |
+
except Exception:
|
| 1044 |
+
N = rn
|
| 1045 |
+
rn = np.arange(N+1)
|
| 1046 |
+
equal = 1
|
| 1047 |
+
|
| 1048 |
+
if equal and N in _builtincoeffs:
|
| 1049 |
+
na, da, vi, nb, db = _builtincoeffs[N]
|
| 1050 |
+
an = na * np.array(vi, dtype=float) / da
|
| 1051 |
+
return an, float(nb)/db
|
| 1052 |
+
|
| 1053 |
+
if (rn[0] != 0) or (rn[-1] != N):
|
| 1054 |
+
raise ValueError("The sample positions must start at 0"
|
| 1055 |
+
" and end at N")
|
| 1056 |
+
yi = rn / float(N)
|
| 1057 |
+
ti = 2 * yi - 1
|
| 1058 |
+
nvec = np.arange(N+1)
|
| 1059 |
+
C = ti ** nvec[:, np.newaxis]
|
| 1060 |
+
Cinv = np.linalg.inv(C)
|
| 1061 |
+
# improve precision of result
|
| 1062 |
+
for i in range(2):
|
| 1063 |
+
Cinv = 2*Cinv - Cinv.dot(C).dot(Cinv)
|
| 1064 |
+
vec = 2.0 / (nvec[::2]+1)
|
| 1065 |
+
ai = Cinv[:, ::2].dot(vec) * (N / 2.)
|
| 1066 |
+
|
| 1067 |
+
if (N % 2 == 0) and equal:
|
| 1068 |
+
BN = N/(N+3.)
|
| 1069 |
+
power = N+2
|
| 1070 |
+
else:
|
| 1071 |
+
BN = N/(N+2.)
|
| 1072 |
+
power = N+1
|
| 1073 |
+
|
| 1074 |
+
BN = BN - np.dot(yi**power, ai)
|
| 1075 |
+
p1 = power+1
|
| 1076 |
+
fac = power*math.log(N) - gammaln(p1)
|
| 1077 |
+
fac = math.exp(fac)
|
| 1078 |
+
return ai, BN*fac
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
def _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log):
|
| 1082 |
+
|
| 1083 |
+
# lazy import to avoid issues with partially-initialized submodule
|
| 1084 |
+
if not hasattr(qmc_quad, 'qmc'):
|
| 1085 |
+
from scipy import stats
|
| 1086 |
+
qmc_quad.stats = stats
|
| 1087 |
+
else:
|
| 1088 |
+
stats = qmc_quad.stats
|
| 1089 |
+
|
| 1090 |
+
if not callable(func):
|
| 1091 |
+
message = "`func` must be callable."
|
| 1092 |
+
raise TypeError(message)
|
| 1093 |
+
|
| 1094 |
+
# a, b will be modified, so copy. Oh well if it's copied twice.
|
| 1095 |
+
a = np.atleast_1d(a).copy()
|
| 1096 |
+
b = np.atleast_1d(b).copy()
|
| 1097 |
+
a, b = np.broadcast_arrays(a, b)
|
| 1098 |
+
dim = a.shape[0]
|
| 1099 |
+
|
| 1100 |
+
try:
|
| 1101 |
+
func((a + b) / 2)
|
| 1102 |
+
except Exception as e:
|
| 1103 |
+
message = ("`func` must evaluate the integrand at points within "
|
| 1104 |
+
"the integration range; e.g. `func( (a + b) / 2)` "
|
| 1105 |
+
"must return the integrand at the centroid of the "
|
| 1106 |
+
"integration volume.")
|
| 1107 |
+
raise ValueError(message) from e
|
| 1108 |
+
|
| 1109 |
+
try:
|
| 1110 |
+
func(np.array([a, b]).T)
|
| 1111 |
+
vfunc = func
|
| 1112 |
+
except Exception as e:
|
| 1113 |
+
message = ("Exception encountered when attempting vectorized call to "
|
| 1114 |
+
f"`func`: {e}. For better performance, `func` should "
|
| 1115 |
+
"accept two-dimensional array `x` with shape `(len(a), "
|
| 1116 |
+
"n_points)` and return an array of the integrand value at "
|
| 1117 |
+
"each of the `n_points.")
|
| 1118 |
+
warnings.warn(message, stacklevel=3)
|
| 1119 |
+
|
| 1120 |
+
def vfunc(x):
|
| 1121 |
+
return np.apply_along_axis(func, axis=-1, arr=x)
|
| 1122 |
+
|
| 1123 |
+
n_points_int = np.int64(n_points)
|
| 1124 |
+
if n_points != n_points_int:
|
| 1125 |
+
message = "`n_points` must be an integer."
|
| 1126 |
+
raise TypeError(message)
|
| 1127 |
+
|
| 1128 |
+
n_estimates_int = np.int64(n_estimates)
|
| 1129 |
+
if n_estimates != n_estimates_int:
|
| 1130 |
+
message = "`n_estimates` must be an integer."
|
| 1131 |
+
raise TypeError(message)
|
| 1132 |
+
|
| 1133 |
+
if qrng is None:
|
| 1134 |
+
qrng = stats.qmc.Halton(dim)
|
| 1135 |
+
elif not isinstance(qrng, stats.qmc.QMCEngine):
|
| 1136 |
+
message = "`qrng` must be an instance of scipy.stats.qmc.QMCEngine."
|
| 1137 |
+
raise TypeError(message)
|
| 1138 |
+
|
| 1139 |
+
if qrng.d != a.shape[0]:
|
| 1140 |
+
message = ("`qrng` must be initialized with dimensionality equal to "
|
| 1141 |
+
"the number of variables in `a`, i.e., "
|
| 1142 |
+
"`qrng.random().shape[-1]` must equal `a.shape[0]`.")
|
| 1143 |
+
raise ValueError(message)
|
| 1144 |
+
|
| 1145 |
+
rng_seed = getattr(qrng, 'rng_seed', None)
|
| 1146 |
+
rng = stats._qmc.check_random_state(rng_seed)
|
| 1147 |
+
|
| 1148 |
+
if log not in {True, False}:
|
| 1149 |
+
message = "`log` must be boolean (`True` or `False`)."
|
| 1150 |
+
raise TypeError(message)
|
| 1151 |
+
|
| 1152 |
+
return (vfunc, a, b, n_points_int, n_estimates_int, qrng, rng, log, stats)
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
QMCQuadResult = namedtuple('QMCQuadResult', ['integral', 'standard_error'])
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
def qmc_quad(func, a, b, *, n_estimates=8, n_points=1024, qrng=None,
|
| 1159 |
+
log=False):
|
| 1160 |
+
"""
|
| 1161 |
+
Compute an integral in N-dimensions using Quasi-Monte Carlo quadrature.
|
| 1162 |
+
|
| 1163 |
+
Parameters
|
| 1164 |
+
----------
|
| 1165 |
+
func : callable
|
| 1166 |
+
The integrand. Must accept a single argument ``x``, an array which
|
| 1167 |
+
specifies the point(s) at which to evaluate the scalar-valued
|
| 1168 |
+
integrand, and return the value(s) of the integrand.
|
| 1169 |
+
For efficiency, the function should be vectorized to accept an array of
|
| 1170 |
+
shape ``(d, n_points)``, where ``d`` is the number of variables (i.e.
|
| 1171 |
+
the dimensionality of the function domain) and `n_points` is the number
|
| 1172 |
+
of quadrature points, and return an array of shape ``(n_points,)``,
|
| 1173 |
+
the integrand at each quadrature point.
|
| 1174 |
+
a, b : array-like
|
| 1175 |
+
One-dimensional arrays specifying the lower and upper integration
|
| 1176 |
+
limits, respectively, of each of the ``d`` variables.
|
| 1177 |
+
n_estimates, n_points : int, optional
|
| 1178 |
+
`n_estimates` (default: 8) statistically independent QMC samples, each
|
| 1179 |
+
of `n_points` (default: 1024) points, will be generated by `qrng`.
|
| 1180 |
+
The total number of points at which the integrand `func` will be
|
| 1181 |
+
evaluated is ``n_points * n_estimates``. See Notes for details.
|
| 1182 |
+
qrng : `~scipy.stats.qmc.QMCEngine`, optional
|
| 1183 |
+
An instance of the QMCEngine from which to sample QMC points.
|
| 1184 |
+
The QMCEngine must be initialized to a number of dimensions ``d``
|
| 1185 |
+
corresponding with the number of variables ``x1, ..., xd`` passed to
|
| 1186 |
+
`func`.
|
| 1187 |
+
The provided QMCEngine is used to produce the first integral estimate.
|
| 1188 |
+
If `n_estimates` is greater than one, additional QMCEngines are
|
| 1189 |
+
spawned from the first (with scrambling enabled, if it is an option.)
|
| 1190 |
+
If a QMCEngine is not provided, the default `scipy.stats.qmc.Halton`
|
| 1191 |
+
will be initialized with the number of dimensions determine from
|
| 1192 |
+
the length of `a`.
|
| 1193 |
+
log : boolean, default: False
|
| 1194 |
+
When set to True, `func` returns the log of the integrand, and
|
| 1195 |
+
the result object contains the log of the integral.
|
| 1196 |
+
|
| 1197 |
+
Returns
|
| 1198 |
+
-------
|
| 1199 |
+
result : object
|
| 1200 |
+
A result object with attributes:
|
| 1201 |
+
|
| 1202 |
+
integral : float
|
| 1203 |
+
The estimate of the integral.
|
| 1204 |
+
standard_error :
|
| 1205 |
+
The error estimate. See Notes for interpretation.
|
| 1206 |
+
|
| 1207 |
+
Notes
|
| 1208 |
+
-----
|
| 1209 |
+
Values of the integrand at each of the `n_points` points of a QMC sample
|
| 1210 |
+
are used to produce an estimate of the integral. This estimate is drawn
|
| 1211 |
+
from a population of possible estimates of the integral, the value of
|
| 1212 |
+
which we obtain depends on the particular points at which the integral
|
| 1213 |
+
was evaluated. We perform this process `n_estimates` times, each time
|
| 1214 |
+
evaluating the integrand at different scrambled QMC points, effectively
|
| 1215 |
+
drawing i.i.d. random samples from the population of integral estimates.
|
| 1216 |
+
The sample mean :math:`m` of these integral estimates is an
|
| 1217 |
+
unbiased estimator of the true value of the integral, and the standard
|
| 1218 |
+
error of the mean :math:`s` of these estimates may be used to generate
|
| 1219 |
+
confidence intervals using the t distribution with ``n_estimates - 1``
|
| 1220 |
+
degrees of freedom. Perhaps counter-intuitively, increasing `n_points`
|
| 1221 |
+
while keeping the total number of function evaluation points
|
| 1222 |
+
``n_points * n_estimates`` fixed tends to reduce the actual error, whereas
|
| 1223 |
+
increasing `n_estimates` tends to decrease the error estimate.
|
| 1224 |
+
|
| 1225 |
+
Examples
|
| 1226 |
+
--------
|
| 1227 |
+
QMC quadrature is particularly useful for computing integrals in higher
|
| 1228 |
+
dimensions. An example integrand is the probability density function
|
| 1229 |
+
of a multivariate normal distribution.
|
| 1230 |
+
|
| 1231 |
+
>>> import numpy as np
|
| 1232 |
+
>>> from scipy import stats
|
| 1233 |
+
>>> dim = 8
|
| 1234 |
+
>>> mean = np.zeros(dim)
|
| 1235 |
+
>>> cov = np.eye(dim)
|
| 1236 |
+
>>> def func(x):
|
| 1237 |
+
... # `multivariate_normal` expects the _last_ axis to correspond with
|
| 1238 |
+
... # the dimensionality of the space, so `x` must be transposed
|
| 1239 |
+
... return stats.multivariate_normal.pdf(x.T, mean, cov)
|
| 1240 |
+
|
| 1241 |
+
To compute the integral over the unit hypercube:
|
| 1242 |
+
|
| 1243 |
+
>>> from scipy.integrate import qmc_quad
|
| 1244 |
+
>>> a = np.zeros(dim)
|
| 1245 |
+
>>> b = np.ones(dim)
|
| 1246 |
+
>>> rng = np.random.default_rng()
|
| 1247 |
+
>>> qrng = stats.qmc.Halton(d=dim, seed=rng)
|
| 1248 |
+
>>> n_estimates = 8
|
| 1249 |
+
>>> res = qmc_quad(func, a, b, n_estimates=n_estimates, qrng=qrng)
|
| 1250 |
+
>>> res.integral, res.standard_error
|
| 1251 |
+
(0.00018429555666024108, 1.0389431116001344e-07)
|
| 1252 |
+
|
| 1253 |
+
A two-sided, 99% confidence interval for the integral may be estimated
|
| 1254 |
+
as:
|
| 1255 |
+
|
| 1256 |
+
>>> t = stats.t(df=n_estimates-1, loc=res.integral,
|
| 1257 |
+
... scale=res.standard_error)
|
| 1258 |
+
>>> t.interval(0.99)
|
| 1259 |
+
(0.0001839319802536469, 0.00018465913306683527)
|
| 1260 |
+
|
| 1261 |
+
Indeed, the value reported by `scipy.stats.multivariate_normal` is
|
| 1262 |
+
within this range.
|
| 1263 |
+
|
| 1264 |
+
>>> stats.multivariate_normal.cdf(b, mean, cov, lower_limit=a)
|
| 1265 |
+
0.00018430867675187443
|
| 1266 |
+
|
| 1267 |
+
"""
|
| 1268 |
+
args = _qmc_quad_iv(func, a, b, n_points, n_estimates, qrng, log)
|
| 1269 |
+
func, a, b, n_points, n_estimates, qrng, rng, log, stats = args
|
| 1270 |
+
|
| 1271 |
+
def sum_product(integrands, dA, log=False):
|
| 1272 |
+
if log:
|
| 1273 |
+
return logsumexp(integrands) + np.log(dA)
|
| 1274 |
+
else:
|
| 1275 |
+
return np.sum(integrands * dA)
|
| 1276 |
+
|
| 1277 |
+
def mean(estimates, log=False):
|
| 1278 |
+
if log:
|
| 1279 |
+
return logsumexp(estimates) - np.log(n_estimates)
|
| 1280 |
+
else:
|
| 1281 |
+
return np.mean(estimates)
|
| 1282 |
+
|
| 1283 |
+
def std(estimates, m=None, ddof=0, log=False):
|
| 1284 |
+
m = m or mean(estimates, log)
|
| 1285 |
+
if log:
|
| 1286 |
+
estimates, m = np.broadcast_arrays(estimates, m)
|
| 1287 |
+
temp = np.vstack((estimates, m + np.pi * 1j))
|
| 1288 |
+
diff = logsumexp(temp, axis=0)
|
| 1289 |
+
return np.real(0.5 * (logsumexp(2 * diff)
|
| 1290 |
+
- np.log(n_estimates - ddof)))
|
| 1291 |
+
else:
|
| 1292 |
+
return np.std(estimates, ddof=ddof)
|
| 1293 |
+
|
| 1294 |
+
def sem(estimates, m=None, s=None, log=False):
|
| 1295 |
+
m = m or mean(estimates, log)
|
| 1296 |
+
s = s or std(estimates, m, ddof=1, log=log)
|
| 1297 |
+
if log:
|
| 1298 |
+
return s - 0.5*np.log(n_estimates)
|
| 1299 |
+
else:
|
| 1300 |
+
return s / np.sqrt(n_estimates)
|
| 1301 |
+
|
| 1302 |
+
# The sign of the integral depends on the order of the limits. Fix this by
|
| 1303 |
+
# ensuring that lower bounds are indeed lower and setting sign of resulting
|
| 1304 |
+
# integral manually
|
| 1305 |
+
if np.any(a == b):
|
| 1306 |
+
message = ("A lower limit was equal to an upper limit, so the value "
|
| 1307 |
+
"of the integral is zero by definition.")
|
| 1308 |
+
warnings.warn(message, stacklevel=2)
|
| 1309 |
+
return QMCQuadResult(-np.inf if log else 0, 0)
|
| 1310 |
+
|
| 1311 |
+
i_swap = b < a
|
| 1312 |
+
sign = (-1)**(i_swap.sum(axis=-1)) # odd # of swaps -> negative
|
| 1313 |
+
a[i_swap], b[i_swap] = b[i_swap], a[i_swap]
|
| 1314 |
+
|
| 1315 |
+
A = np.prod(b - a)
|
| 1316 |
+
dA = A / n_points
|
| 1317 |
+
|
| 1318 |
+
estimates = np.zeros(n_estimates)
|
| 1319 |
+
rngs = _rng_spawn(qrng.rng, n_estimates)
|
| 1320 |
+
for i in range(n_estimates):
|
| 1321 |
+
# Generate integral estimate
|
| 1322 |
+
sample = qrng.random(n_points)
|
| 1323 |
+
# The rationale for transposing is that this allows users to easily
|
| 1324 |
+
# unpack `x` into separate variables, if desired. This is consistent
|
| 1325 |
+
# with the `xx` array passed into the `scipy.integrate.nquad` `func`.
|
| 1326 |
+
x = stats.qmc.scale(sample, a, b).T # (n_dim, n_points)
|
| 1327 |
+
integrands = func(x)
|
| 1328 |
+
estimates[i] = sum_product(integrands, dA, log)
|
| 1329 |
+
|
| 1330 |
+
# Get a new, independently-scrambled QRNG for next time
|
| 1331 |
+
qrng = type(qrng)(seed=rngs[i], **qrng._init_quad)
|
| 1332 |
+
|
| 1333 |
+
integral = mean(estimates, log)
|
| 1334 |
+
standard_error = sem(estimates, m=integral, log=log)
|
| 1335 |
+
integral = integral + np.pi*1j if (log and sign < 0) else integral*sign
|
| 1336 |
+
return QMCQuadResult(integral, standard_error)
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Numerical cubature algorithms"""
|
| 2 |
+
|
| 3 |
+
from ._base import (
|
| 4 |
+
Rule, FixedRule,
|
| 5 |
+
NestedFixedRule,
|
| 6 |
+
ProductNestedFixed,
|
| 7 |
+
)
|
| 8 |
+
from ._genz_malik import GenzMalikCubature
|
| 9 |
+
from ._gauss_kronrod import GaussKronrodQuadrature
|
| 10 |
+
from ._gauss_legendre import GaussLegendreQuadrature
|
| 11 |
+
|
| 12 |
+
__all__ = [s for s in dir() if not s.startswith('_')]
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (672 Bytes). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc
ADDED
|
Binary file (4.87 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc
ADDED
|
Binary file (5.08 kB). View file
|
|
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scipy._lib._array_api import array_namespace, xp_size
|
| 2 |
+
|
| 3 |
+
from functools import cached_property
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Rule:
|
| 7 |
+
"""
|
| 8 |
+
Base class for numerical integration algorithms (cubatures).
|
| 9 |
+
|
| 10 |
+
Finds an estimate for the integral of ``f`` over the region described by two arrays
|
| 11 |
+
``a`` and ``b`` via `estimate`, and find an estimate for the error of this
|
| 12 |
+
approximation via `estimate_error`.
|
| 13 |
+
|
| 14 |
+
If a subclass does not implement its own `estimate_error`, then it will use a
|
| 15 |
+
default error estimate based on the difference between the estimate over the whole
|
| 16 |
+
region and the sum of estimates over that region divided into ``2^ndim`` subregions.
|
| 17 |
+
|
| 18 |
+
See Also
|
| 19 |
+
--------
|
| 20 |
+
FixedRule
|
| 21 |
+
|
| 22 |
+
Examples
|
| 23 |
+
--------
|
| 24 |
+
In the following, a custom rule is created which uses 3D Genz-Malik cubature for
|
| 25 |
+
the estimate of the integral, and the difference between this estimate and a less
|
| 26 |
+
accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the
|
| 27 |
+
error.
|
| 28 |
+
|
| 29 |
+
>>> import numpy as np
|
| 30 |
+
>>> from scipy.integrate import cubature
|
| 31 |
+
>>> from scipy.integrate._rules import (
|
| 32 |
+
... Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature
|
| 33 |
+
... )
|
| 34 |
+
>>> def f(x, r, alphas):
|
| 35 |
+
... # f(x) = cos(2*pi*r + alpha @ x)
|
| 36 |
+
... # Need to allow r and alphas to be arbitrary shape
|
| 37 |
+
... npoints, ndim = x.shape[0], x.shape[-1]
|
| 38 |
+
... alphas_reshaped = alphas[np.newaxis, :]
|
| 39 |
+
... x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
|
| 40 |
+
... return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1))
|
| 41 |
+
>>> genz = GenzMalikCubature(ndim=3)
|
| 42 |
+
>>> gauss = GaussKronrodQuadrature(npoints=21)
|
| 43 |
+
>>> # Gauss-Kronrod is 1D, so we find the 3D product rule:
|
| 44 |
+
>>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss])
|
| 45 |
+
>>> class CustomRule(Rule):
|
| 46 |
+
... def estimate(self, f, a, b, args=()):
|
| 47 |
+
... return genz.estimate(f, a, b, args)
|
| 48 |
+
... def estimate_error(self, f, a, b, args=()):
|
| 49 |
+
... return np.abs(
|
| 50 |
+
... genz.estimate(f, a, b, args)
|
| 51 |
+
... - gauss_3d.estimate(f, a, b, args)
|
| 52 |
+
... )
|
| 53 |
+
>>> rng = np.random.default_rng()
|
| 54 |
+
>>> res = cubature(
|
| 55 |
+
... f=f,
|
| 56 |
+
... a=np.array([0, 0, 0]),
|
| 57 |
+
... b=np.array([1, 1, 1]),
|
| 58 |
+
... rule=CustomRule(),
|
| 59 |
+
... args=(rng.random((2,)), rng.random((3, 2, 3)))
|
| 60 |
+
... )
|
| 61 |
+
>>> res.estimate
|
| 62 |
+
array([[-0.95179502, 0.12444608],
|
| 63 |
+
[-0.96247411, 0.60866385],
|
| 64 |
+
[-0.97360014, 0.25515587]])
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def estimate(self, f, a, b, args=()):
|
| 68 |
+
r"""
|
| 69 |
+
Calculate estimate of integral of `f` in rectangular region described by
|
| 70 |
+
corners `a` and ``b``.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
f : callable
|
| 75 |
+
Function to integrate. `f` must have the signature::
|
| 76 |
+
f(x : ndarray, \*args) -> ndarray
|
| 77 |
+
|
| 78 |
+
`f` should accept arrays ``x`` of shape::
|
| 79 |
+
(npoints, ndim)
|
| 80 |
+
|
| 81 |
+
and output arrays of shape::
|
| 82 |
+
(npoints, output_dim_1, ..., output_dim_n)
|
| 83 |
+
|
| 84 |
+
In this case, `estimate` will return arrays of shape::
|
| 85 |
+
(output_dim_1, ..., output_dim_n)
|
| 86 |
+
a, b : ndarray
|
| 87 |
+
Lower and upper limits of integration as rank-1 arrays specifying the left
|
| 88 |
+
and right endpoints of the intervals being integrated over. Infinite limits
|
| 89 |
+
are currently not supported.
|
| 90 |
+
args : tuple, optional
|
| 91 |
+
Additional positional args passed to ``f``, if any.
|
| 92 |
+
|
| 93 |
+
Returns
|
| 94 |
+
-------
|
| 95 |
+
est : ndarray
|
| 96 |
+
Result of estimation. If `f` returns arrays of shape ``(npoints,
|
| 97 |
+
output_dim_1, ..., output_dim_n)``, then `est` will be of shape
|
| 98 |
+
``(output_dim_1, ..., output_dim_n)``.
|
| 99 |
+
"""
|
| 100 |
+
raise NotImplementedError
|
| 101 |
+
|
| 102 |
+
def estimate_error(self, f, a, b, args=()):
|
| 103 |
+
r"""
|
| 104 |
+
Estimate the error of the approximation for the integral of `f` in rectangular
|
| 105 |
+
region described by corners `a` and `b`.
|
| 106 |
+
|
| 107 |
+
If a subclass does not override this method, then a default error estimator is
|
| 108 |
+
used. This estimates the error as ``|est - refined_est|`` where ``est`` is
|
| 109 |
+
``estimate(f, a, b)`` and ``refined_est`` is the sum of
|
| 110 |
+
``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each
|
| 111 |
+
subregion of the region described by ``a`` and ``b``. In the 1D case, this
|
| 112 |
+
is equivalent to comparing the integral over an entire interval ``[a, b]`` to
|
| 113 |
+
the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]``
|
| 114 |
+
and ``[(a+b)/2, b]``.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
----------
|
| 118 |
+
f : callable
|
| 119 |
+
Function to estimate error for. `f` must have the signature::
|
| 120 |
+
f(x : ndarray, \*args) -> ndarray
|
| 121 |
+
|
| 122 |
+
`f` should accept arrays `x` of shape::
|
| 123 |
+
(npoints, ndim)
|
| 124 |
+
|
| 125 |
+
and output arrays of shape::
|
| 126 |
+
(npoints, output_dim_1, ..., output_dim_n)
|
| 127 |
+
|
| 128 |
+
In this case, `estimate` will return arrays of shape::
|
| 129 |
+
(output_dim_1, ..., output_dim_n)
|
| 130 |
+
a, b : ndarray
|
| 131 |
+
Lower and upper limits of integration as rank-1 arrays specifying the left
|
| 132 |
+
and right endpoints of the intervals being integrated over. Infinite limits
|
| 133 |
+
are currently not supported.
|
| 134 |
+
args : tuple, optional
|
| 135 |
+
Additional positional args passed to `f`, if any.
|
| 136 |
+
|
| 137 |
+
Returns
|
| 138 |
+
-------
|
| 139 |
+
err_est : ndarray
|
| 140 |
+
Result of error estimation. If `f` returns arrays of shape
|
| 141 |
+
``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
|
| 142 |
+
of shape ``(output_dim_1, ..., output_dim_n)``.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
est = self.estimate(f, a, b, args)
|
| 146 |
+
refined_est = 0
|
| 147 |
+
|
| 148 |
+
for a_k, b_k in _split_subregion(a, b):
|
| 149 |
+
refined_est += self.estimate(f, a_k, b_k, args)
|
| 150 |
+
|
| 151 |
+
return self.xp.abs(est - refined_est)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class FixedRule(Rule):
|
| 155 |
+
"""
|
| 156 |
+
A rule implemented as the weighted sum of function evaluations at fixed nodes.
|
| 157 |
+
|
| 158 |
+
Attributes
|
| 159 |
+
----------
|
| 160 |
+
nodes_and_weights : (ndarray, ndarray)
|
| 161 |
+
A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the
|
| 162 |
+
corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D
|
| 163 |
+
cubature rules (quadratures) and more generally for N-D cubature rules, it
|
| 164 |
+
should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape
|
| 165 |
+
``(num_nodes,)``. The nodes and weights should be for integrals over
|
| 166 |
+
:math:`[-1, 1]^n`.
|
| 167 |
+
|
| 168 |
+
See Also
|
| 169 |
+
--------
|
| 170 |
+
GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature
|
| 171 |
+
|
| 172 |
+
Examples
|
| 173 |
+
--------
|
| 174 |
+
|
| 175 |
+
Implementing Simpson's 1/3 rule:
|
| 176 |
+
|
| 177 |
+
>>> import numpy as np
|
| 178 |
+
>>> from scipy.integrate._rules import FixedRule
|
| 179 |
+
>>> class SimpsonsQuad(FixedRule):
|
| 180 |
+
... @property
|
| 181 |
+
... def nodes_and_weights(self):
|
| 182 |
+
... nodes = np.array([-1, 0, 1])
|
| 183 |
+
... weights = np.array([1/3, 4/3, 1/3])
|
| 184 |
+
... return (nodes, weights)
|
| 185 |
+
>>> rule = SimpsonsQuad()
|
| 186 |
+
>>> rule.estimate(
|
| 187 |
+
... f=lambda x: x**2,
|
| 188 |
+
... a=np.array([0]),
|
| 189 |
+
... b=np.array([1]),
|
| 190 |
+
... )
|
| 191 |
+
[0.3333333]
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def __init__(self):
|
| 195 |
+
self.xp = None
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def nodes_and_weights(self):
|
| 199 |
+
raise NotImplementedError
|
| 200 |
+
|
| 201 |
+
def estimate(self, f, a, b, args=()):
|
| 202 |
+
r"""
|
| 203 |
+
Calculate estimate of integral of `f` in rectangular region described by
|
| 204 |
+
corners `a` and `b` as ``sum(weights * f(nodes))``.
|
| 205 |
+
|
| 206 |
+
Nodes and weights will automatically be adjusted from calculating integrals over
|
| 207 |
+
:math:`[-1, 1]^n` to :math:`[a, b]^n`.
|
| 208 |
+
|
| 209 |
+
Parameters
|
| 210 |
+
----------
|
| 211 |
+
f : callable
|
| 212 |
+
Function to integrate. `f` must have the signature::
|
| 213 |
+
f(x : ndarray, \*args) -> ndarray
|
| 214 |
+
|
| 215 |
+
`f` should accept arrays `x` of shape::
|
| 216 |
+
(npoints, ndim)
|
| 217 |
+
|
| 218 |
+
and output arrays of shape::
|
| 219 |
+
(npoints, output_dim_1, ..., output_dim_n)
|
| 220 |
+
|
| 221 |
+
In this case, `estimate` will return arrays of shape::
|
| 222 |
+
(output_dim_1, ..., output_dim_n)
|
| 223 |
+
a, b : ndarray
|
| 224 |
+
Lower and upper limits of integration as rank-1 arrays specifying the left
|
| 225 |
+
and right endpoints of the intervals being integrated over. Infinite limits
|
| 226 |
+
are currently not supported.
|
| 227 |
+
args : tuple, optional
|
| 228 |
+
Additional positional args passed to `f`, if any.
|
| 229 |
+
|
| 230 |
+
Returns
|
| 231 |
+
-------
|
| 232 |
+
est : ndarray
|
| 233 |
+
Result of estimation. If `f` returns arrays of shape ``(npoints,
|
| 234 |
+
output_dim_1, ..., output_dim_n)``, then `est` will be of shape
|
| 235 |
+
``(output_dim_1, ..., output_dim_n)``.
|
| 236 |
+
"""
|
| 237 |
+
nodes, weights = self.nodes_and_weights
|
| 238 |
+
|
| 239 |
+
if self.xp is None:
|
| 240 |
+
self.xp = array_namespace(nodes)
|
| 241 |
+
|
| 242 |
+
return _apply_fixed_rule(f, a, b, nodes, weights, args, self.xp)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class NestedFixedRule(FixedRule):
|
| 246 |
+
r"""
|
| 247 |
+
A cubature rule with error estimate given by the difference between two underlying
|
| 248 |
+
fixed rules.
|
| 249 |
+
|
| 250 |
+
If constructed as ``NestedFixedRule(higher, lower)``, this will use::
|
| 251 |
+
|
| 252 |
+
estimate(f, a, b) := higher.estimate(f, a, b)
|
| 253 |
+
estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)|
|
| 254 |
+
|
| 255 |
+
(where the absolute value is taken elementwise).
|
| 256 |
+
|
| 257 |
+
Attributes
|
| 258 |
+
----------
|
| 259 |
+
higher : Rule
|
| 260 |
+
Higher accuracy rule.
|
| 261 |
+
|
| 262 |
+
lower : Rule
|
| 263 |
+
Lower accuracy rule.
|
| 264 |
+
|
| 265 |
+
See Also
|
| 266 |
+
--------
|
| 267 |
+
GaussKronrodQuadrature
|
| 268 |
+
|
| 269 |
+
Examples
|
| 270 |
+
--------
|
| 271 |
+
|
| 272 |
+
>>> from scipy.integrate import cubature
|
| 273 |
+
>>> from scipy.integrate._rules import (
|
| 274 |
+
... GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed
|
| 275 |
+
... )
|
| 276 |
+
>>> higher = GaussLegendreQuadrature(10)
|
| 277 |
+
>>> lower = GaussLegendreQuadrature(5)
|
| 278 |
+
>>> rule = NestedFixedRule(
|
| 279 |
+
... higher,
|
| 280 |
+
... lower
|
| 281 |
+
... )
|
| 282 |
+
>>> rule_2d = ProductNestedFixed([rule, rule])
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
def __init__(self, higher, lower):
|
| 286 |
+
self.higher = higher
|
| 287 |
+
self.lower = lower
|
| 288 |
+
self.xp = None
|
| 289 |
+
|
| 290 |
+
@property
|
| 291 |
+
def nodes_and_weights(self):
|
| 292 |
+
if self.higher is not None:
|
| 293 |
+
return self.higher.nodes_and_weights
|
| 294 |
+
else:
|
| 295 |
+
raise NotImplementedError
|
| 296 |
+
|
| 297 |
+
@property
|
| 298 |
+
def lower_nodes_and_weights(self):
|
| 299 |
+
if self.lower is not None:
|
| 300 |
+
return self.lower.nodes_and_weights
|
| 301 |
+
else:
|
| 302 |
+
raise NotImplementedError
|
| 303 |
+
|
| 304 |
+
def estimate_error(self, f, a, b, args=()):
|
| 305 |
+
r"""
|
| 306 |
+
Estimate the error of the approximation for the integral of `f` in rectangular
|
| 307 |
+
region described by corners `a` and `b`.
|
| 308 |
+
|
| 309 |
+
Parameters
|
| 310 |
+
----------
|
| 311 |
+
f : callable
|
| 312 |
+
Function to estimate error for. `f` must have the signature::
|
| 313 |
+
f(x : ndarray, \*args) -> ndarray
|
| 314 |
+
|
| 315 |
+
`f` should accept arrays `x` of shape::
|
| 316 |
+
(npoints, ndim)
|
| 317 |
+
|
| 318 |
+
and output arrays of shape::
|
| 319 |
+
(npoints, output_dim_1, ..., output_dim_n)
|
| 320 |
+
|
| 321 |
+
In this case, `estimate` will return arrays of shape::
|
| 322 |
+
(output_dim_1, ..., output_dim_n)
|
| 323 |
+
a, b : ndarray
|
| 324 |
+
Lower and upper limits of integration as rank-1 arrays specifying the left
|
| 325 |
+
and right endpoints of the intervals being integrated over. Infinite limits
|
| 326 |
+
are currently not supported.
|
| 327 |
+
args : tuple, optional
|
| 328 |
+
Additional positional args passed to `f`, if any.
|
| 329 |
+
|
| 330 |
+
Returns
|
| 331 |
+
-------
|
| 332 |
+
err_est : ndarray
|
| 333 |
+
Result of error estimation. If `f` returns arrays of shape
|
| 334 |
+
``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
|
| 335 |
+
of shape ``(output_dim_1, ..., output_dim_n)``.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
nodes, weights = self.nodes_and_weights
|
| 339 |
+
lower_nodes, lower_weights = self.lower_nodes_and_weights
|
| 340 |
+
|
| 341 |
+
if self.xp is None:
|
| 342 |
+
self.xp = array_namespace(nodes)
|
| 343 |
+
|
| 344 |
+
error_nodes = self.xp.concat([nodes, lower_nodes], axis=0)
|
| 345 |
+
error_weights = self.xp.concat([weights, -lower_weights], axis=0)
|
| 346 |
+
|
| 347 |
+
return self.xp.abs(
|
| 348 |
+
_apply_fixed_rule(f, a, b, error_nodes, error_weights, args, self.xp)
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class ProductNestedFixed(NestedFixedRule):
|
| 353 |
+
"""
|
| 354 |
+
Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D
|
| 355 |
+
`NestedFixedRule` quadrature rules.
|
| 356 |
+
|
| 357 |
+
Given a list of N 1-dimensional quadrature rules which support error estimation
|
| 358 |
+
using NestedFixedRule, this will find the N-dimensional cubature rule obtained by
|
| 359 |
+
taking the Cartesian product of their nodes, and estimating the error by taking the
|
| 360 |
+
difference with a lower-accuracy N-dimensional cubature rule obtained using the
|
| 361 |
+
``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules.
|
| 362 |
+
|
| 363 |
+
Parameters
|
| 364 |
+
----------
|
| 365 |
+
base_rules : list of NestedFixedRule
|
| 366 |
+
List of base 1-dimensional `NestedFixedRule` quadrature rules.
|
| 367 |
+
|
| 368 |
+
Attributes
|
| 369 |
+
----------
|
| 370 |
+
base_rules : list of NestedFixedRule
|
| 371 |
+
List of base 1-dimensional `NestedFixedRule` qudarature rules.
|
| 372 |
+
|
| 373 |
+
Examples
|
| 374 |
+
--------
|
| 375 |
+
|
| 376 |
+
Evaluate a 2D integral by taking the product of two 1D rules:
|
| 377 |
+
|
| 378 |
+
>>> import numpy as np
|
| 379 |
+
>>> from scipy.integrate import cubature
|
| 380 |
+
>>> from scipy.integrate._rules import (
|
| 381 |
+
... ProductNestedFixed, GaussKronrodQuadrature
|
| 382 |
+
... )
|
| 383 |
+
>>> def f(x):
|
| 384 |
+
... # f(x) = cos(x_1) + cos(x_2)
|
| 385 |
+
... return np.sum(np.cos(x), axis=-1)
|
| 386 |
+
>>> rule = ProductNestedFixed(
|
| 387 |
+
... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
|
| 388 |
+
... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule
|
| 389 |
+
>>> a, b = np.array([0, 0]), np.array([1, 1])
|
| 390 |
+
>>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
|
| 391 |
+
np.float64(1.682941969615793)
|
| 392 |
+
>>> rule.estimate_error(f, a, b)
|
| 393 |
+
np.float64(2.220446049250313e-16)
|
| 394 |
+
"""
|
| 395 |
+
|
| 396 |
+
def __init__(self, base_rules):
|
| 397 |
+
for rule in base_rules:
|
| 398 |
+
if not isinstance(rule, NestedFixedRule):
|
| 399 |
+
raise ValueError("base rules for product need to be instance of"
|
| 400 |
+
"NestedFixedRule")
|
| 401 |
+
|
| 402 |
+
self.base_rules = base_rules
|
| 403 |
+
self.xp = None
|
| 404 |
+
|
| 405 |
+
@cached_property
|
| 406 |
+
def nodes_and_weights(self):
|
| 407 |
+
nodes = _cartesian_product(
|
| 408 |
+
[rule.nodes_and_weights[0] for rule in self.base_rules]
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
if self.xp is None:
|
| 412 |
+
self.xp = array_namespace(nodes)
|
| 413 |
+
|
| 414 |
+
weights = self.xp.prod(
|
| 415 |
+
_cartesian_product(
|
| 416 |
+
[rule.nodes_and_weights[1] for rule in self.base_rules]
|
| 417 |
+
),
|
| 418 |
+
axis=-1,
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return nodes, weights
|
| 422 |
+
|
| 423 |
+
@cached_property
|
| 424 |
+
def lower_nodes_and_weights(self):
|
| 425 |
+
nodes = _cartesian_product(
|
| 426 |
+
[cubature.lower_nodes_and_weights[0] for cubature in self.base_rules]
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
if self.xp is None:
|
| 430 |
+
self.xp = array_namespace(nodes)
|
| 431 |
+
|
| 432 |
+
weights = self.xp.prod(
|
| 433 |
+
_cartesian_product(
|
| 434 |
+
[cubature.lower_nodes_and_weights[1] for cubature in self.base_rules]
|
| 435 |
+
),
|
| 436 |
+
axis=-1,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
return nodes, weights
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _cartesian_product(arrays):
|
| 443 |
+
xp = array_namespace(*arrays)
|
| 444 |
+
|
| 445 |
+
arrays_ix = xp.meshgrid(*arrays, indexing='ij')
|
| 446 |
+
result = xp.reshape(xp.stack(arrays_ix, axis=-1), (-1, len(arrays)))
|
| 447 |
+
|
| 448 |
+
return result
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _split_subregion(a, b, xp, split_at=None):
|
| 452 |
+
"""
|
| 453 |
+
Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates
|
| 454 |
+
of all subregions, which in this case would be::
|
| 455 |
+
|
| 456 |
+
([0, 0], [1/2, 1/2]),
|
| 457 |
+
([0, 1/2], [1/2, 1]),
|
| 458 |
+
([1/2, 0], [1, 1/2]),
|
| 459 |
+
([1/2, 1/2], [1, 1])
|
| 460 |
+
"""
|
| 461 |
+
xp = array_namespace(a, b)
|
| 462 |
+
|
| 463 |
+
if split_at is None:
|
| 464 |
+
split_at = (a + b) / 2
|
| 465 |
+
|
| 466 |
+
left = [xp.asarray([a[i], split_at[i]]) for i in range(a.shape[0])]
|
| 467 |
+
right = [xp.asarray([split_at[i], b[i]]) for i in range(b.shape[0])]
|
| 468 |
+
|
| 469 |
+
a_sub = _cartesian_product(left)
|
| 470 |
+
b_sub = _cartesian_product(right)
|
| 471 |
+
|
| 472 |
+
for i in range(a_sub.shape[0]):
|
| 473 |
+
yield a_sub[i, ...], b_sub[i, ...]
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def _apply_fixed_rule(f, a, b, orig_nodes, orig_weights, args, xp):
|
| 477 |
+
# Downcast nodes and weights to common dtype of a and b
|
| 478 |
+
result_dtype = a.dtype
|
| 479 |
+
orig_nodes = xp.astype(orig_nodes, result_dtype)
|
| 480 |
+
orig_weights = xp.astype(orig_weights, result_dtype)
|
| 481 |
+
|
| 482 |
+
# Ensure orig_nodes are at least 2D, since 1D cubature methods can return arrays of
|
| 483 |
+
# shape (npoints,) rather than (npoints, 1)
|
| 484 |
+
if orig_nodes.ndim == 1:
|
| 485 |
+
orig_nodes = orig_nodes[:, None]
|
| 486 |
+
|
| 487 |
+
rule_ndim = orig_nodes.shape[-1]
|
| 488 |
+
|
| 489 |
+
a_ndim = xp_size(a)
|
| 490 |
+
b_ndim = xp_size(b)
|
| 491 |
+
|
| 492 |
+
if rule_ndim != a_ndim or rule_ndim != b_ndim:
|
| 493 |
+
raise ValueError(f"rule and function are of incompatible dimension, nodes have"
|
| 494 |
+
f"ndim {rule_ndim}, while limit of integration has ndim"
|
| 495 |
+
f"a_ndim={a_ndim}, b_ndim={b_ndim}")
|
| 496 |
+
|
| 497 |
+
lengths = b - a
|
| 498 |
+
|
| 499 |
+
# The underlying rule is for the hypercube [-1, 1]^n.
|
| 500 |
+
#
|
| 501 |
+
# To handle arbitrary regions of integration, it's necessary to apply a linear
|
| 502 |
+
# change of coordinates to map each interval [a[i], b[i]] to [-1, 1].
|
| 503 |
+
nodes = (orig_nodes + 1) * (lengths * 0.5) + a
|
| 504 |
+
|
| 505 |
+
# Also need to multiply the weights by a scale factor equal to the determinant
|
| 506 |
+
# of the Jacobian for this coordinate change.
|
| 507 |
+
weight_scale_factor = xp.prod(lengths, dtype=result_dtype) / 2**rule_ndim
|
| 508 |
+
weights = orig_weights * weight_scale_factor
|
| 509 |
+
|
| 510 |
+
f_nodes = f(nodes, *args)
|
| 511 |
+
weights_reshaped = xp.reshape(weights, (-1, *([1] * (f_nodes.ndim - 1))))
|
| 512 |
+
|
| 513 |
+
# f(nodes) will have shape (num_nodes, output_dim_1, ..., output_dim_n)
|
| 514 |
+
# Summing along the first axis means estimate will shape (output_dim_1, ...,
|
| 515 |
+
# output_dim_n)
|
| 516 |
+
est = xp.sum(weights_reshaped * f_nodes, axis=0, dtype=result_dtype)
|
| 517 |
+
|
| 518 |
+
return est
|
evalkit_eagle/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scipy._lib._array_api import np_compat, array_namespace
|
| 2 |
+
|
| 3 |
+
from functools import cached_property
|
| 4 |
+
|
| 5 |
+
from ._base import NestedFixedRule
|
| 6 |
+
from ._gauss_legendre import GaussLegendreQuadrature
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class GaussKronrodQuadrature(NestedFixedRule):
|
| 10 |
+
"""
|
| 11 |
+
Gauss-Kronrod quadrature.
|
| 12 |
+
|
| 13 |
+
Gauss-Kronrod rules consist of two quadrature rules, one higher-order and one
|
| 14 |
+
lower-order. The higher-order rule is used as the estimate of the integral and the
|
| 15 |
+
difference between them is used as an estimate for the error.
|
| 16 |
+
|
| 17 |
+
Gauss-Kronrod is a 1D rule. To use it for multidimensional integrals, it will be
|
| 18 |
+
necessary to use ProductNestedFixed and multiple Gauss-Kronrod rules. See Examples.
|
| 19 |
+
|
| 20 |
+
For n-node Gauss-Kronrod, the lower-order rule has ``n//2`` nodes, which are the
|
| 21 |
+
ordinary Gauss-Legendre nodes with corresponding weights. The higher-order rule has
|
| 22 |
+
``n`` nodes, ``n//2`` of which are the same as the lower-order rule and the
|
| 23 |
+
remaining nodes are the Kronrod extension of those nodes.
|
| 24 |
+
|
| 25 |
+
Parameters
|
| 26 |
+
----------
|
| 27 |
+
npoints : int
|
| 28 |
+
Number of nodes for the higher-order rule.
|
| 29 |
+
|
| 30 |
+
xp : array_namespace, optional
|
| 31 |
+
The namespace for the node and weight arrays. Default is None, where NumPy is
|
| 32 |
+
used.
|
| 33 |
+
|
| 34 |
+
Attributes
|
| 35 |
+
----------
|
| 36 |
+
lower : Rule
|
| 37 |
+
Lower-order rule.
|
| 38 |
+
|
| 39 |
+
References
|
| 40 |
+
----------
|
| 41 |
+
.. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
|
| 42 |
+
Integration, files: dqk21.f, dqk15.f (1983).
|
| 43 |
+
|
| 44 |
+
Examples
|
| 45 |
+
--------
|
| 46 |
+
Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
|
| 47 |
+
estimates will also be arrays, despite the fact that this is a 1D problem.
|
| 48 |
+
|
| 49 |
+
>>> import numpy as np
|
| 50 |
+
>>> from scipy.integrate import cubature
|
| 51 |
+
>>> from scipy.integrate._rules import GaussKronrodQuadrature
|
| 52 |
+
>>> def f(x):
|
| 53 |
+
... return np.cos(x)
|
| 54 |
+
>>> rule = GaussKronrodQuadrature(21) # Use 21-point GaussKronrod
|
| 55 |
+
>>> a, b = np.array([0]), np.array([1])
|
| 56 |
+
>>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
|
| 57 |
+
array([0.84147098])
|
| 58 |
+
>>> rule.estimate_error(f, a, b)
|
| 59 |
+
array([1.11022302e-16])
|
| 60 |
+
|
| 61 |
+
Evaluate a 2D integral. Note that in this example ``f`` returns a float, so the
|
| 62 |
+
estimates will also be floats.
|
| 63 |
+
|
| 64 |
+
>>> import numpy as np
|
| 65 |
+
>>> from scipy.integrate import cubature
|
| 66 |
+
>>> from scipy.integrate._rules import (
|
| 67 |
+
... ProductNestedFixed, GaussKronrodQuadrature
|
| 68 |
+
... )
|
| 69 |
+
>>> def f(x):
|
| 70 |
+
... # f(x) = cos(x_1) + cos(x_2)
|
| 71 |
+
... return np.sum(np.cos(x), axis=-1)
|
| 72 |
+
>>> rule = ProductNestedFixed(
|
| 73 |
+
... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
|
| 74 |
+
... ) # Use 15-point Gauss-Kronrod
|
| 75 |
+
>>> a, b = np.array([0, 0]), np.array([1, 1])
|
| 76 |
+
>>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
|
| 77 |
+
np.float64(1.682941969615793)
|
| 78 |
+
>>> rule.estimate_error(f, a, b)
|
| 79 |
+
np.float64(2.220446049250313e-16)
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, npoints, xp=None):
|
| 83 |
+
# TODO: nodes and weights are currently hard-coded for values 15 and 21, but in
|
| 84 |
+
# the future it would be best to compute the Kronrod extension of the lower rule
|
| 85 |
+
if npoints != 15 and npoints != 21:
|
| 86 |
+
raise NotImplementedError("Gauss-Kronrod quadrature is currently only"
|
| 87 |
+
"supported for 15 or 21 nodes")
|
| 88 |
+
|
| 89 |
+
self.npoints = npoints
|
| 90 |
+
|
| 91 |
+
if xp is None:
|
| 92 |
+
xp = np_compat
|
| 93 |
+
|
| 94 |
+
self.xp = array_namespace(xp.empty(0))
|
| 95 |
+
|
| 96 |
+
self.gauss = GaussLegendreQuadrature(npoints//2, xp=self.xp)
|
| 97 |
+
|
| 98 |
+
@cached_property
|
| 99 |
+
def nodes_and_weights(self):
|
| 100 |
+
# These values are from QUADPACK's `dqk21.f` and `dqk15.f` (1983).
|
| 101 |
+
if self.npoints == 21:
|
| 102 |
+
nodes = self.xp.asarray(
|
| 103 |
+
[
|
| 104 |
+
0.995657163025808080735527280689003,
|
| 105 |
+
0.973906528517171720077964012084452,
|
| 106 |
+
0.930157491355708226001207180059508,
|
| 107 |
+
0.865063366688984510732096688423493,
|
| 108 |
+
0.780817726586416897063717578345042,
|
| 109 |
+
0.679409568299024406234327365114874,
|
| 110 |
+
0.562757134668604683339000099272694,
|
| 111 |
+
0.433395394129247190799265943165784,
|
| 112 |
+
0.294392862701460198131126603103866,
|
| 113 |
+
0.148874338981631210884826001129720,
|
| 114 |
+
0,
|
| 115 |
+
-0.148874338981631210884826001129720,
|
| 116 |
+
-0.294392862701460198131126603103866,
|
| 117 |
+
-0.433395394129247190799265943165784,
|
| 118 |
+
-0.562757134668604683339000099272694,
|
| 119 |
+
-0.679409568299024406234327365114874,
|
| 120 |
+
-0.780817726586416897063717578345042,
|
| 121 |
+
-0.865063366688984510732096688423493,
|
| 122 |
+
-0.930157491355708226001207180059508,
|
| 123 |
+
-0.973906528517171720077964012084452,
|
| 124 |
+
-0.995657163025808080735527280689003,
|
| 125 |
+
],
|
| 126 |
+
dtype=self.xp.float64,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
weights = self.xp.asarray(
|
| 130 |
+
[
|
| 131 |
+
0.011694638867371874278064396062192,
|
| 132 |
+
0.032558162307964727478818972459390,
|
| 133 |
+
0.054755896574351996031381300244580,
|
| 134 |
+
0.075039674810919952767043140916190,
|
| 135 |
+
0.093125454583697605535065465083366,
|
| 136 |
+
0.109387158802297641899210590325805,
|
| 137 |
+
0.123491976262065851077958109831074,
|
| 138 |
+
0.134709217311473325928054001771707,
|
| 139 |
+
0.142775938577060080797094273138717,
|
| 140 |
+
0.147739104901338491374841515972068,
|
| 141 |
+
0.149445554002916905664936468389821,
|
| 142 |
+
0.147739104901338491374841515972068,
|
| 143 |
+
0.142775938577060080797094273138717,
|
| 144 |
+
0.134709217311473325928054001771707,
|
| 145 |
+
0.123491976262065851077958109831074,
|
| 146 |
+
0.109387158802297641899210590325805,
|
| 147 |
+
0.093125454583697605535065465083366,
|
| 148 |
+
0.075039674810919952767043140916190,
|
| 149 |
+
0.054755896574351996031381300244580,
|
| 150 |
+
0.032558162307964727478818972459390,
|
| 151 |
+
0.011694638867371874278064396062192,
|
| 152 |
+
],
|
| 153 |
+
dtype=self.xp.float64,
|
| 154 |
+
)
|
| 155 |
+
elif self.npoints == 15:
|
| 156 |
+
nodes = self.xp.asarray(
|
| 157 |
+
[
|
| 158 |
+
0.991455371120812639206854697526329,
|
| 159 |
+
0.949107912342758524526189684047851,
|
| 160 |
+
0.864864423359769072789712788640926,
|
| 161 |
+
0.741531185599394439863864773280788,
|
| 162 |
+
0.586087235467691130294144838258730,
|
| 163 |
+
0.405845151377397166906606412076961,
|
| 164 |
+
0.207784955007898467600689403773245,
|
| 165 |
+
0.000000000000000000000000000000000,
|
| 166 |
+
-0.207784955007898467600689403773245,
|
| 167 |
+
-0.405845151377397166906606412076961,
|
| 168 |
+
-0.586087235467691130294144838258730,
|
| 169 |
+
-0.741531185599394439863864773280788,
|
| 170 |
+
-0.864864423359769072789712788640926,
|
| 171 |
+
-0.949107912342758524526189684047851,
|
| 172 |
+
-0.991455371120812639206854697526329,
|
| 173 |
+
],
|
| 174 |
+
dtype=self.xp.float64,
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
weights = self.xp.asarray(
|
| 178 |
+
[
|
| 179 |
+
0.022935322010529224963732008058970,
|
| 180 |
+
0.063092092629978553290700663189204,
|
| 181 |
+
0.104790010322250183839876322541518,
|
| 182 |
+
0.140653259715525918745189590510238,
|
| 183 |
+
0.169004726639267902826583426598550,
|
| 184 |
+
0.190350578064785409913256402421014,
|
| 185 |
+
0.204432940075298892414161999234649,
|
| 186 |
+
0.209482141084727828012999174891714,
|
| 187 |
+
0.204432940075298892414161999234649,
|
| 188 |
+
0.190350578064785409913256402421014,
|
| 189 |
+
0.169004726639267902826583426598550,
|
| 190 |
+
0.140653259715525918745189590510238,
|
| 191 |
+
0.104790010322250183839876322541518,
|
| 192 |
+
0.063092092629978553290700663189204,
|
| 193 |
+
0.022935322010529224963732008058970,
|
| 194 |
+
],
|
| 195 |
+
dtype=self.xp.float64,
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
return nodes, weights
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def lower_nodes_and_weights(self):
|
| 202 |
+
return self.gauss.nodes_and_weights
|