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 +8 -0
- evalkit_tf449/lib/python3.10/site-packages/cv2/cv2.abi3.so +3 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/__pycache__/conftest.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__init__.py +122 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_bvp.py +1154 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_cubature.py +728 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so +3 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__init__.py +8 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/radau.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/base.py +290 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/bdf.py +478 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/common.py +451 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py +193 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py +224 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py +572 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_lebedev.py +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so +3 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ode.py +1388 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so +3 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py +273 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py +682 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so +3 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quadpack_py.py +1279 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quadrature.py +1336 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__init__.py +12 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/_base.py +518 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py +202 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py +62 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/_genz_malik.py +210 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py +1382 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so +0 -0
- infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so +3 -0
.gitattributes
CHANGED
|
@@ -2421,3 +2421,11 @@ infer_4_30_0/lib/python3.10/site-packages/scipy/sparse/csgraph/_traversal.cpytho
|
|
| 2421 |
infer_4_30_0/lib/python3.10/site-packages/scipy/sparse/csgraph/_matching.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2422 |
infer_4_30_0/lib/python3.10/site-packages/scipy/special/__pycache__/_basic.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 2423 |
infer_4_30_0/lib/python3.10/site-packages/scipy/sparse/csgraph/_reordering.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2421 |
infer_4_30_0/lib/python3.10/site-packages/scipy/sparse/csgraph/_matching.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2422 |
infer_4_30_0/lib/python3.10/site-packages/scipy/special/__pycache__/_basic.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 2423 |
infer_4_30_0/lib/python3.10/site-packages/scipy/sparse/csgraph/_reordering.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2424 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2425 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quadpack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2426 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2427 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_lsoda.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2428 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_vode.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2429 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_dop.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2430 |
+
infer_4_30_0/lib/python3.10/site-packages/scipy/sparse/_csparsetools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 2431 |
+
evalkit_tf449/lib/python3.10/site-packages/cv2/cv2.abi3.so filter=lfs diff=lfs merge=lfs -text
|
evalkit_tf449/lib/python3.10/site-packages/cv2/cv2.abi3.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c4139433b8ab5a656c13b1261028599d827254c21268dd17312c6f6cae1e7dc4
|
| 3 |
+
size 65859185
|
infer_4_30_0/lib/python3.10/site-packages/scipy/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (3.66 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/__pycache__/conftest.cpython-310.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
infer_4_30_0/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
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/_bvp.cpython-310.pyc
ADDED
|
Binary file (35.7 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/_ode.cpython-310.pyc
ADDED
|
Binary file (38.4 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc
ADDED
|
Binary file (620 Bytes). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/lsoda.cpython-310.pyc
ADDED
|
Binary file (586 Bytes). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/quadpack.cpython-310.pyc
ADDED
|
Binary file (648 Bytes). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/__pycache__/vode.cpython-310.pyc
ADDED
|
Binary file (623 Bytes). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_bvp.py
ADDED
|
@@ -0,0 +1,1154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 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)
|
infer_4_30_0/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
|
infer_4_30_0/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
|
infer_4_30_0/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
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (541 Bytes). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/common.cpython-310.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/dop853_coefficients.cpython-310.pyc
ADDED
|
Binary file (4.92 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/ivp.cpython-310.pyc
ADDED
|
Binary file (29.3 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/__pycache__/lsoda.cpython-310.pyc
ADDED
|
Binary file (8.5 kB). View file
|
|
|
infer_4_30_0/lib/python3.10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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
|
infer_4_30_0/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
|
infer_4_30_0/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_JAC_MIN_FACTOR)
|
| 450 |
+
|
| 451 |
+
return diff, factor
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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978178381316732e-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
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/lsoda.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.integrate import ode
|
| 3 |
+
from .common import validate_tol, validate_first_step, warn_extraneous
|
| 4 |
+
from .base import OdeSolver, DenseOutput
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class LSODA(OdeSolver):
|
| 8 |
+
"""Adams/BDF method with automatic stiffness detection and switching.
|
| 9 |
+
|
| 10 |
+
This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
|
| 11 |
+
automatically between the nonstiff Adams method and the stiff BDF method.
|
| 12 |
+
The method was originally detailed in [2]_.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
fun : callable
|
| 17 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 18 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 19 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 20 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 21 |
+
information.
|
| 22 |
+
t0 : float
|
| 23 |
+
Initial time.
|
| 24 |
+
y0 : array_like, shape (n,)
|
| 25 |
+
Initial state.
|
| 26 |
+
t_bound : float
|
| 27 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 28 |
+
determines the direction of the integration.
|
| 29 |
+
first_step : float or None, optional
|
| 30 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 31 |
+
should choose.
|
| 32 |
+
min_step : float, optional
|
| 33 |
+
Minimum allowed step size. Default is 0.0, i.e., the step size is not
|
| 34 |
+
bounded and determined solely by the solver.
|
| 35 |
+
max_step : float, optional
|
| 36 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 37 |
+
bounded and determined solely by the solver.
|
| 38 |
+
rtol, atol : float and array_like, optional
|
| 39 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 40 |
+
estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
|
| 41 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 42 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 43 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 44 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 45 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 46 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 47 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 48 |
+
than `atol`. If components of y have different scales, it might be
|
| 49 |
+
beneficial to set different `atol` values for different components by
|
| 50 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 51 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 52 |
+
jac : None or callable, optional
|
| 53 |
+
Jacobian matrix of the right-hand side of the system with respect to
|
| 54 |
+
``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
|
| 55 |
+
equal to ``d f_i / d y_j``. The function will be called as
|
| 56 |
+
``jac(t, y)``. If None (default), the Jacobian will be
|
| 57 |
+
approximated by finite differences. It is generally recommended to
|
| 58 |
+
provide the Jacobian rather than relying on a finite-difference
|
| 59 |
+
approximation.
|
| 60 |
+
lband, uband : int or None
|
| 61 |
+
Parameters defining the bandwidth of the Jacobian,
|
| 62 |
+
i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
|
| 63 |
+
these requires your jac routine to return the Jacobian in the packed format:
|
| 64 |
+
the returned array must have ``n`` columns and ``uband + lband + 1``
|
| 65 |
+
rows in which Jacobian diagonals are written. Specifically
|
| 66 |
+
``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
|
| 67 |
+
in `scipy.linalg.solve_banded` (check for an illustration).
|
| 68 |
+
These parameters can be also used with ``jac=None`` to reduce the
|
| 69 |
+
number of Jacobian elements estimated by finite differences.
|
| 70 |
+
vectorized : bool, optional
|
| 71 |
+
Whether `fun` may be called in a vectorized fashion. False (default)
|
| 72 |
+
is recommended for this solver.
|
| 73 |
+
|
| 74 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 75 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 76 |
+
|
| 77 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 78 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 79 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 80 |
+
the returned array is the time derivative of the state corresponding
|
| 81 |
+
with a column of ``y``).
|
| 82 |
+
|
| 83 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 84 |
+
approximation of the Jacobian by methods 'Radau' and 'BDF', but
|
| 85 |
+
will result in slower execution for this solver.
|
| 86 |
+
|
| 87 |
+
Attributes
|
| 88 |
+
----------
|
| 89 |
+
n : int
|
| 90 |
+
Number of equations.
|
| 91 |
+
status : string
|
| 92 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 93 |
+
t_bound : float
|
| 94 |
+
Boundary time.
|
| 95 |
+
direction : float
|
| 96 |
+
Integration direction: +1 or -1.
|
| 97 |
+
t : float
|
| 98 |
+
Current time.
|
| 99 |
+
y : ndarray
|
| 100 |
+
Current state.
|
| 101 |
+
t_old : float
|
| 102 |
+
Previous time. None if no steps were made yet.
|
| 103 |
+
nfev : int
|
| 104 |
+
Number of evaluations of the right-hand side.
|
| 105 |
+
njev : int
|
| 106 |
+
Number of evaluations of the Jacobian.
|
| 107 |
+
|
| 108 |
+
References
|
| 109 |
+
----------
|
| 110 |
+
.. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
|
| 111 |
+
Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
|
| 112 |
+
pp. 55-64, 1983.
|
| 113 |
+
.. [2] L. Petzold, "Automatic selection of methods for solving stiff and
|
| 114 |
+
nonstiff systems of ordinary differential equations", SIAM Journal
|
| 115 |
+
on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
|
| 116 |
+
1983.
|
| 117 |
+
"""
|
| 118 |
+
def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
|
| 119 |
+
max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
|
| 120 |
+
uband=None, vectorized=False, **extraneous):
|
| 121 |
+
warn_extraneous(extraneous)
|
| 122 |
+
super().__init__(fun, t0, y0, t_bound, vectorized)
|
| 123 |
+
|
| 124 |
+
if first_step is None:
|
| 125 |
+
first_step = 0 # LSODA value for automatic selection.
|
| 126 |
+
else:
|
| 127 |
+
first_step = validate_first_step(first_step, t0, t_bound)
|
| 128 |
+
|
| 129 |
+
first_step *= self.direction
|
| 130 |
+
|
| 131 |
+
if max_step == np.inf:
|
| 132 |
+
max_step = 0 # LSODA value for infinity.
|
| 133 |
+
elif max_step <= 0:
|
| 134 |
+
raise ValueError("`max_step` must be positive.")
|
| 135 |
+
|
| 136 |
+
if min_step < 0:
|
| 137 |
+
raise ValueError("`min_step` must be nonnegative.")
|
| 138 |
+
|
| 139 |
+
rtol, atol = validate_tol(rtol, atol, self.n)
|
| 140 |
+
|
| 141 |
+
solver = ode(self.fun, jac)
|
| 142 |
+
solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
|
| 143 |
+
min_step=min_step, first_step=first_step,
|
| 144 |
+
lband=lband, uband=uband)
|
| 145 |
+
solver.set_initial_value(y0, t0)
|
| 146 |
+
|
| 147 |
+
# Inject t_bound into rwork array as needed for itask=5.
|
| 148 |
+
solver._integrator.rwork[0] = self.t_bound
|
| 149 |
+
solver._integrator.call_args[4] = solver._integrator.rwork
|
| 150 |
+
|
| 151 |
+
self._lsoda_solver = solver
|
| 152 |
+
|
| 153 |
+
def _step_impl(self):
|
| 154 |
+
solver = self._lsoda_solver
|
| 155 |
+
integrator = solver._integrator
|
| 156 |
+
|
| 157 |
+
# From lsoda.step and lsoda.integrate itask=5 means take a single
|
| 158 |
+
# step and do not go past t_bound.
|
| 159 |
+
itask = integrator.call_args[2]
|
| 160 |
+
integrator.call_args[2] = 5
|
| 161 |
+
solver._y, solver.t = integrator.run(
|
| 162 |
+
solver.f, solver.jac or (lambda: None), solver._y, solver.t,
|
| 163 |
+
self.t_bound, solver.f_params, solver.jac_params)
|
| 164 |
+
integrator.call_args[2] = itask
|
| 165 |
+
|
| 166 |
+
if solver.successful():
|
| 167 |
+
self.t = solver.t
|
| 168 |
+
self.y = solver._y
|
| 169 |
+
# From LSODA Fortran source njev is equal to nlu.
|
| 170 |
+
self.njev = integrator.iwork[12]
|
| 171 |
+
self.nlu = integrator.iwork[12]
|
| 172 |
+
return True, None
|
| 173 |
+
else:
|
| 174 |
+
return False, 'Unexpected istate in LSODA.'
|
| 175 |
+
|
| 176 |
+
def _dense_output_impl(self):
|
| 177 |
+
iwork = self._lsoda_solver._integrator.iwork
|
| 178 |
+
rwork = self._lsoda_solver._integrator.rwork
|
| 179 |
+
|
| 180 |
+
# We want to produce the Nordsieck history array, yh, up to the order
|
| 181 |
+
# used in the last successful iteration. The step size is unimportant
|
| 182 |
+
# because it will be scaled out in LsodaDenseOutput. Some additional
|
| 183 |
+
# work may be required because ODEPACK's LSODA implementation produces
|
| 184 |
+
# the Nordsieck history in the state needed for the next iteration.
|
| 185 |
+
|
| 186 |
+
# iwork[13] contains order from last successful iteration, while
|
| 187 |
+
# iwork[14] contains order to be attempted next.
|
| 188 |
+
order = iwork[13]
|
| 189 |
+
|
| 190 |
+
# rwork[11] contains the step size to be attempted next, while
|
| 191 |
+
# rwork[10] contains step size from last successful iteration.
|
| 192 |
+
h = rwork[11]
|
| 193 |
+
|
| 194 |
+
# rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
|
| 195 |
+
# Nordsieck array in state needed for next iteration. We want
|
| 196 |
+
# the entries up to order for the last successful step so use the
|
| 197 |
+
# following.
|
| 198 |
+
yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
|
| 199 |
+
(self.n, order + 1), order='F').copy()
|
| 200 |
+
if iwork[14] < order:
|
| 201 |
+
# If the order is set to decrease then the final column of yh
|
| 202 |
+
# has not been updated within ODEPACK's LSODA
|
| 203 |
+
# implementation because this column will not be used in the
|
| 204 |
+
# next iteration. We must rescale this column to make the
|
| 205 |
+
# associated step size consistent with the other columns.
|
| 206 |
+
yh[:, -1] *= (h / rwork[10]) ** order
|
| 207 |
+
|
| 208 |
+
return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class LsodaDenseOutput(DenseOutput):
|
| 212 |
+
def __init__(self, t_old, t, h, order, yh):
|
| 213 |
+
super().__init__(t_old, t)
|
| 214 |
+
self.h = h
|
| 215 |
+
self.yh = yh
|
| 216 |
+
self.p = np.arange(order + 1)
|
| 217 |
+
|
| 218 |
+
def _call_impl(self, t):
|
| 219 |
+
if t.ndim == 0:
|
| 220 |
+
x = ((t - self.t) / self.h) ** self.p
|
| 221 |
+
else:
|
| 222 |
+
x = ((t - self.t) / self.h) ** self.p[:, None]
|
| 223 |
+
|
| 224 |
+
return np.dot(self.yh, x)
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/radau.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from scipy.linalg import lu_factor, lu_solve
|
| 3 |
+
from scipy.sparse import csc_matrix, issparse, eye
|
| 4 |
+
from scipy.sparse.linalg import splu
|
| 5 |
+
from scipy.optimize._numdiff import group_columns
|
| 6 |
+
from .common import (validate_max_step, validate_tol, select_initial_step,
|
| 7 |
+
norm, num_jac, EPS, warn_extraneous,
|
| 8 |
+
validate_first_step)
|
| 9 |
+
from .base import OdeSolver, DenseOutput
|
| 10 |
+
|
| 11 |
+
S6 = 6 ** 0.5
|
| 12 |
+
|
| 13 |
+
# Butcher tableau. A is not used directly, see below.
|
| 14 |
+
C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
|
| 15 |
+
E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
|
| 16 |
+
|
| 17 |
+
# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
|
| 18 |
+
# and a complex conjugate pair. They are written below.
|
| 19 |
+
MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
|
| 20 |
+
MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
|
| 21 |
+
- 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
|
| 22 |
+
|
| 23 |
+
# These are transformation matrices.
|
| 24 |
+
T = np.array([
|
| 25 |
+
[0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
|
| 26 |
+
[0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
|
| 27 |
+
[1, 1, 0]])
|
| 28 |
+
TI = np.array([
|
| 29 |
+
[4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
|
| 30 |
+
[-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
|
| 31 |
+
[0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
|
| 32 |
+
# These linear combinations are used in the algorithm.
|
| 33 |
+
TI_REAL = TI[0]
|
| 34 |
+
TI_COMPLEX = TI[1] + 1j * TI[2]
|
| 35 |
+
|
| 36 |
+
# Interpolator coefficients.
|
| 37 |
+
P = np.array([
|
| 38 |
+
[13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
|
| 39 |
+
[13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
|
| 40 |
+
[1/3, -8/3, 10/3]])
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
NEWTON_MAXITER = 6 # Maximum number of Newton iterations.
|
| 44 |
+
MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
|
| 45 |
+
MAX_FACTOR = 10 # Maximum allowed increase in a step size.
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
|
| 49 |
+
LU_real, LU_complex, solve_lu):
|
| 50 |
+
"""Solve the collocation system.
|
| 51 |
+
|
| 52 |
+
Parameters
|
| 53 |
+
----------
|
| 54 |
+
fun : callable
|
| 55 |
+
Right-hand side of the system.
|
| 56 |
+
t : float
|
| 57 |
+
Current time.
|
| 58 |
+
y : ndarray, shape (n,)
|
| 59 |
+
Current state.
|
| 60 |
+
h : float
|
| 61 |
+
Step to try.
|
| 62 |
+
Z0 : ndarray, shape (3, n)
|
| 63 |
+
Initial guess for the solution. It determines new values of `y` at
|
| 64 |
+
``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
|
| 65 |
+
scale : ndarray, shape (n)
|
| 66 |
+
Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
|
| 67 |
+
tol : float
|
| 68 |
+
Tolerance to which solve the system. This value is compared with
|
| 69 |
+
the normalized by `scale` error.
|
| 70 |
+
LU_real, LU_complex
|
| 71 |
+
LU decompositions of the system Jacobians.
|
| 72 |
+
solve_lu : callable
|
| 73 |
+
Callable which solves a linear system given a LU decomposition. The
|
| 74 |
+
signature is ``solve_lu(LU, b)``.
|
| 75 |
+
|
| 76 |
+
Returns
|
| 77 |
+
-------
|
| 78 |
+
converged : bool
|
| 79 |
+
Whether iterations converged.
|
| 80 |
+
n_iter : int
|
| 81 |
+
Number of completed iterations.
|
| 82 |
+
Z : ndarray, shape (3, n)
|
| 83 |
+
Found solution.
|
| 84 |
+
rate : float
|
| 85 |
+
The rate of convergence.
|
| 86 |
+
"""
|
| 87 |
+
n = y.shape[0]
|
| 88 |
+
M_real = MU_REAL / h
|
| 89 |
+
M_complex = MU_COMPLEX / h
|
| 90 |
+
|
| 91 |
+
W = TI.dot(Z0)
|
| 92 |
+
Z = Z0
|
| 93 |
+
|
| 94 |
+
F = np.empty((3, n))
|
| 95 |
+
ch = h * C
|
| 96 |
+
|
| 97 |
+
dW_norm_old = None
|
| 98 |
+
dW = np.empty_like(W)
|
| 99 |
+
converged = False
|
| 100 |
+
rate = None
|
| 101 |
+
for k in range(NEWTON_MAXITER):
|
| 102 |
+
for i in range(3):
|
| 103 |
+
F[i] = fun(t + ch[i], y + Z[i])
|
| 104 |
+
|
| 105 |
+
if not np.all(np.isfinite(F)):
|
| 106 |
+
break
|
| 107 |
+
|
| 108 |
+
f_real = F.T.dot(TI_REAL) - M_real * W[0]
|
| 109 |
+
f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
|
| 110 |
+
|
| 111 |
+
dW_real = solve_lu(LU_real, f_real)
|
| 112 |
+
dW_complex = solve_lu(LU_complex, f_complex)
|
| 113 |
+
|
| 114 |
+
dW[0] = dW_real
|
| 115 |
+
dW[1] = dW_complex.real
|
| 116 |
+
dW[2] = dW_complex.imag
|
| 117 |
+
|
| 118 |
+
dW_norm = norm(dW / scale)
|
| 119 |
+
if dW_norm_old is not None:
|
| 120 |
+
rate = dW_norm / dW_norm_old
|
| 121 |
+
|
| 122 |
+
if (rate is not None and (rate >= 1 or
|
| 123 |
+
rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
|
| 124 |
+
break
|
| 125 |
+
|
| 126 |
+
W += dW
|
| 127 |
+
Z = T.dot(W)
|
| 128 |
+
|
| 129 |
+
if (dW_norm == 0 or
|
| 130 |
+
rate is not None and rate / (1 - rate) * dW_norm < tol):
|
| 131 |
+
converged = True
|
| 132 |
+
break
|
| 133 |
+
|
| 134 |
+
dW_norm_old = dW_norm
|
| 135 |
+
|
| 136 |
+
return converged, k + 1, Z, rate
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
|
| 140 |
+
"""Predict by which factor to increase/decrease the step size.
|
| 141 |
+
|
| 142 |
+
The algorithm is described in [1]_.
|
| 143 |
+
|
| 144 |
+
Parameters
|
| 145 |
+
----------
|
| 146 |
+
h_abs, h_abs_old : float
|
| 147 |
+
Current and previous values of the step size, `h_abs_old` can be None
|
| 148 |
+
(see Notes).
|
| 149 |
+
error_norm, error_norm_old : float
|
| 150 |
+
Current and previous values of the error norm, `error_norm_old` can
|
| 151 |
+
be None (see Notes).
|
| 152 |
+
|
| 153 |
+
Returns
|
| 154 |
+
-------
|
| 155 |
+
factor : float
|
| 156 |
+
Predicted factor.
|
| 157 |
+
|
| 158 |
+
Notes
|
| 159 |
+
-----
|
| 160 |
+
If `h_abs_old` and `error_norm_old` are both not None then a two-step
|
| 161 |
+
algorithm is used, otherwise a one-step algorithm is used.
|
| 162 |
+
|
| 163 |
+
References
|
| 164 |
+
----------
|
| 165 |
+
.. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
|
| 166 |
+
Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
| 167 |
+
"""
|
| 168 |
+
if error_norm_old is None or h_abs_old is None or error_norm == 0:
|
| 169 |
+
multiplier = 1
|
| 170 |
+
else:
|
| 171 |
+
multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
|
| 172 |
+
|
| 173 |
+
with np.errstate(divide='ignore'):
|
| 174 |
+
factor = min(1, multiplier) * error_norm ** -0.25
|
| 175 |
+
|
| 176 |
+
return factor
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class Radau(OdeSolver):
|
| 180 |
+
"""Implicit Runge-Kutta method of Radau IIA family of order 5.
|
| 181 |
+
|
| 182 |
+
The implementation follows [1]_. The error is controlled with a
|
| 183 |
+
third-order accurate embedded formula. A cubic polynomial which satisfies
|
| 184 |
+
the collocation conditions is used for the dense output.
|
| 185 |
+
|
| 186 |
+
Parameters
|
| 187 |
+
----------
|
| 188 |
+
fun : callable
|
| 189 |
+
Right-hand side of the system: the time derivative of the state ``y``
|
| 190 |
+
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
|
| 191 |
+
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
|
| 192 |
+
return an array of the same shape as ``y``. See `vectorized` for more
|
| 193 |
+
information.
|
| 194 |
+
t0 : float
|
| 195 |
+
Initial time.
|
| 196 |
+
y0 : array_like, shape (n,)
|
| 197 |
+
Initial state.
|
| 198 |
+
t_bound : float
|
| 199 |
+
Boundary time - the integration won't continue beyond it. It also
|
| 200 |
+
determines the direction of the integration.
|
| 201 |
+
first_step : float or None, optional
|
| 202 |
+
Initial step size. Default is ``None`` which means that the algorithm
|
| 203 |
+
should choose.
|
| 204 |
+
max_step : float, optional
|
| 205 |
+
Maximum allowed step size. Default is np.inf, i.e., the step size is not
|
| 206 |
+
bounded and determined solely by the solver.
|
| 207 |
+
rtol, atol : float and array_like, optional
|
| 208 |
+
Relative and absolute tolerances. The solver keeps the local error
|
| 209 |
+
estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
|
| 210 |
+
relative accuracy (number of correct digits), while `atol` controls
|
| 211 |
+
absolute accuracy (number of correct decimal places). To achieve the
|
| 212 |
+
desired `rtol`, set `atol` to be smaller than the smallest value that
|
| 213 |
+
can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
|
| 214 |
+
allowable error. If `atol` is larger than ``rtol * abs(y)`` the
|
| 215 |
+
number of correct digits is not guaranteed. Conversely, to achieve the
|
| 216 |
+
desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
|
| 217 |
+
than `atol`. If components of y have different scales, it might be
|
| 218 |
+
beneficial to set different `atol` values for different components by
|
| 219 |
+
passing array_like with shape (n,) for `atol`. Default values are
|
| 220 |
+
1e-3 for `rtol` and 1e-6 for `atol`.
|
| 221 |
+
jac : {None, array_like, sparse_matrix, callable}, optional
|
| 222 |
+
Jacobian matrix of the right-hand side of the system with respect to
|
| 223 |
+
y, required by this method. The Jacobian matrix has shape (n, n) and
|
| 224 |
+
its element (i, j) is equal to ``d f_i / d y_j``.
|
| 225 |
+
There are three ways to define the Jacobian:
|
| 226 |
+
|
| 227 |
+
* If array_like or sparse_matrix, the Jacobian is assumed to
|
| 228 |
+
be constant.
|
| 229 |
+
* If callable, the Jacobian is assumed to depend on both
|
| 230 |
+
t and y; it will be called as ``jac(t, y)`` as necessary.
|
| 231 |
+
For the 'Radau' and 'BDF' methods, the return value might be a
|
| 232 |
+
sparse matrix.
|
| 233 |
+
* If None (default), the Jacobian will be approximated by
|
| 234 |
+
finite differences.
|
| 235 |
+
|
| 236 |
+
It is generally recommended to provide the Jacobian rather than
|
| 237 |
+
relying on a finite-difference approximation.
|
| 238 |
+
jac_sparsity : {None, array_like, sparse matrix}, optional
|
| 239 |
+
Defines a sparsity structure of the Jacobian matrix for a
|
| 240 |
+
finite-difference approximation. Its shape must be (n, n). This argument
|
| 241 |
+
is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
|
| 242 |
+
elements in *each* row, providing the sparsity structure will greatly
|
| 243 |
+
speed up the computations [2]_. A zero entry means that a corresponding
|
| 244 |
+
element in the Jacobian is always zero. If None (default), the Jacobian
|
| 245 |
+
is assumed to be dense.
|
| 246 |
+
vectorized : bool, optional
|
| 247 |
+
Whether `fun` can be called in a vectorized fashion. Default is False.
|
| 248 |
+
|
| 249 |
+
If ``vectorized`` is False, `fun` will always be called with ``y`` of
|
| 250 |
+
shape ``(n,)``, where ``n = len(y0)``.
|
| 251 |
+
|
| 252 |
+
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
|
| 253 |
+
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
|
| 254 |
+
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
|
| 255 |
+
the returned array is the time derivative of the state corresponding
|
| 256 |
+
with a column of ``y``).
|
| 257 |
+
|
| 258 |
+
Setting ``vectorized=True`` allows for faster finite difference
|
| 259 |
+
approximation of the Jacobian by this method, but may result in slower
|
| 260 |
+
execution overall in some circumstances (e.g. small ``len(y0)``).
|
| 261 |
+
|
| 262 |
+
Attributes
|
| 263 |
+
----------
|
| 264 |
+
n : int
|
| 265 |
+
Number of equations.
|
| 266 |
+
status : string
|
| 267 |
+
Current status of the solver: 'running', 'finished' or 'failed'.
|
| 268 |
+
t_bound : float
|
| 269 |
+
Boundary time.
|
| 270 |
+
direction : float
|
| 271 |
+
Integration direction: +1 or -1.
|
| 272 |
+
t : float
|
| 273 |
+
Current time.
|
| 274 |
+
y : ndarray
|
| 275 |
+
Current state.
|
| 276 |
+
t_old : float
|
| 277 |
+
Previous time. None if no steps were made yet.
|
| 278 |
+
step_size : float
|
| 279 |
+
Size of the last successful step. None if no steps were made yet.
|
| 280 |
+
nfev : int
|
| 281 |
+
Number of evaluations of the right-hand side.
|
| 282 |
+
njev : int
|
| 283 |
+
Number of evaluations of the Jacobian.
|
| 284 |
+
nlu : int
|
| 285 |
+
Number of LU decompositions.
|
| 286 |
+
|
| 287 |
+
References
|
| 288 |
+
----------
|
| 289 |
+
.. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
|
| 290 |
+
Stiff and Differential-Algebraic Problems", Sec. IV.8.
|
| 291 |
+
.. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
|
| 292 |
+
sparse Jacobian matrices", Journal of the Institute of Mathematics
|
| 293 |
+
and its Applications, 13, pp. 117-120, 1974.
|
| 294 |
+
"""
|
| 295 |
+
def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
|
| 296 |
+
rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
|
| 297 |
+
vectorized=False, first_step=None, **extraneous):
|
| 298 |
+
warn_extraneous(extraneous)
|
| 299 |
+
super().__init__(fun, t0, y0, t_bound, vectorized)
|
| 300 |
+
self.y_old = None
|
| 301 |
+
self.max_step = validate_max_step(max_step)
|
| 302 |
+
self.rtol, self.atol = validate_tol(rtol, atol, self.n)
|
| 303 |
+
self.f = self.fun(self.t, self.y)
|
| 304 |
+
# Select initial step assuming the same order which is used to control
|
| 305 |
+
# the error.
|
| 306 |
+
if first_step is None:
|
| 307 |
+
self.h_abs = select_initial_step(
|
| 308 |
+
self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
|
| 309 |
+
3, self.rtol, self.atol)
|
| 310 |
+
else:
|
| 311 |
+
self.h_abs = validate_first_step(first_step, t0, t_bound)
|
| 312 |
+
self.h_abs_old = None
|
| 313 |
+
self.error_norm_old = None
|
| 314 |
+
|
| 315 |
+
self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
|
| 316 |
+
self.sol = None
|
| 317 |
+
|
| 318 |
+
self.jac_factor = None
|
| 319 |
+
self.jac, self.J = self._validate_jac(jac, jac_sparsity)
|
| 320 |
+
if issparse(self.J):
|
| 321 |
+
def lu(A):
|
| 322 |
+
self.nlu += 1
|
| 323 |
+
return splu(A)
|
| 324 |
+
|
| 325 |
+
def solve_lu(LU, b):
|
| 326 |
+
return LU.solve(b)
|
| 327 |
+
|
| 328 |
+
I = eye(self.n, format='csc')
|
| 329 |
+
else:
|
| 330 |
+
def lu(A):
|
| 331 |
+
self.nlu += 1
|
| 332 |
+
return lu_factor(A, overwrite_a=True)
|
| 333 |
+
|
| 334 |
+
def solve_lu(LU, b):
|
| 335 |
+
return lu_solve(LU, b, overwrite_b=True)
|
| 336 |
+
|
| 337 |
+
I = np.identity(self.n)
|
| 338 |
+
|
| 339 |
+
self.lu = lu
|
| 340 |
+
self.solve_lu = solve_lu
|
| 341 |
+
self.I = I
|
| 342 |
+
|
| 343 |
+
self.current_jac = True
|
| 344 |
+
self.LU_real = None
|
| 345 |
+
self.LU_complex = None
|
| 346 |
+
self.Z = None
|
| 347 |
+
|
| 348 |
+
def _validate_jac(self, jac, sparsity):
|
| 349 |
+
t0 = self.t
|
| 350 |
+
y0 = self.y
|
| 351 |
+
|
| 352 |
+
if jac is None:
|
| 353 |
+
if sparsity is not None:
|
| 354 |
+
if issparse(sparsity):
|
| 355 |
+
sparsity = csc_matrix(sparsity)
|
| 356 |
+
groups = group_columns(sparsity)
|
| 357 |
+
sparsity = (sparsity, groups)
|
| 358 |
+
|
| 359 |
+
def jac_wrapped(t, y, f):
|
| 360 |
+
self.njev += 1
|
| 361 |
+
J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
|
| 362 |
+
self.atol, self.jac_factor,
|
| 363 |
+
sparsity)
|
| 364 |
+
return J
|
| 365 |
+
J = jac_wrapped(t0, y0, self.f)
|
| 366 |
+
elif callable(jac):
|
| 367 |
+
J = jac(t0, y0)
|
| 368 |
+
self.njev = 1
|
| 369 |
+
if issparse(J):
|
| 370 |
+
J = csc_matrix(J)
|
| 371 |
+
|
| 372 |
+
def jac_wrapped(t, y, _=None):
|
| 373 |
+
self.njev += 1
|
| 374 |
+
return csc_matrix(jac(t, y), dtype=float)
|
| 375 |
+
|
| 376 |
+
else:
|
| 377 |
+
J = np.asarray(J, dtype=float)
|
| 378 |
+
|
| 379 |
+
def jac_wrapped(t, y, _=None):
|
| 380 |
+
self.njev += 1
|
| 381 |
+
return np.asarray(jac(t, y), dtype=float)
|
| 382 |
+
|
| 383 |
+
if J.shape != (self.n, self.n):
|
| 384 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 385 |
+
f" but actually has {J.shape}.")
|
| 386 |
+
else:
|
| 387 |
+
if issparse(jac):
|
| 388 |
+
J = csc_matrix(jac)
|
| 389 |
+
else:
|
| 390 |
+
J = np.asarray(jac, dtype=float)
|
| 391 |
+
|
| 392 |
+
if J.shape != (self.n, self.n):
|
| 393 |
+
raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
|
| 394 |
+
f" but actually has {J.shape}.")
|
| 395 |
+
jac_wrapped = None
|
| 396 |
+
|
| 397 |
+
return jac_wrapped, J
|
| 398 |
+
|
| 399 |
+
def _step_impl(self):
|
| 400 |
+
t = self.t
|
| 401 |
+
y = self.y
|
| 402 |
+
f = self.f
|
| 403 |
+
|
| 404 |
+
max_step = self.max_step
|
| 405 |
+
atol = self.atol
|
| 406 |
+
rtol = self.rtol
|
| 407 |
+
|
| 408 |
+
min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
|
| 409 |
+
if self.h_abs > max_step:
|
| 410 |
+
h_abs = max_step
|
| 411 |
+
h_abs_old = None
|
| 412 |
+
error_norm_old = None
|
| 413 |
+
elif self.h_abs < min_step:
|
| 414 |
+
h_abs = min_step
|
| 415 |
+
h_abs_old = None
|
| 416 |
+
error_norm_old = None
|
| 417 |
+
else:
|
| 418 |
+
h_abs = self.h_abs
|
| 419 |
+
h_abs_old = self.h_abs_old
|
| 420 |
+
error_norm_old = self.error_norm_old
|
| 421 |
+
|
| 422 |
+
J = self.J
|
| 423 |
+
LU_real = self.LU_real
|
| 424 |
+
LU_complex = self.LU_complex
|
| 425 |
+
|
| 426 |
+
current_jac = self.current_jac
|
| 427 |
+
jac = self.jac
|
| 428 |
+
|
| 429 |
+
rejected = False
|
| 430 |
+
step_accepted = False
|
| 431 |
+
message = None
|
| 432 |
+
while not step_accepted:
|
| 433 |
+
if h_abs < min_step:
|
| 434 |
+
return False, self.TOO_SMALL_STEP
|
| 435 |
+
|
| 436 |
+
h = h_abs * self.direction
|
| 437 |
+
t_new = t + h
|
| 438 |
+
|
| 439 |
+
if self.direction * (t_new - self.t_bound) > 0:
|
| 440 |
+
t_new = self.t_bound
|
| 441 |
+
|
| 442 |
+
h = t_new - t
|
| 443 |
+
h_abs = np.abs(h)
|
| 444 |
+
|
| 445 |
+
if self.sol is None:
|
| 446 |
+
Z0 = np.zeros((3, y.shape[0]))
|
| 447 |
+
else:
|
| 448 |
+
Z0 = self.sol(t + h * C).T - y
|
| 449 |
+
|
| 450 |
+
scale = atol + np.abs(y) * rtol
|
| 451 |
+
|
| 452 |
+
converged = False
|
| 453 |
+
while not converged:
|
| 454 |
+
if LU_real is None or LU_complex is None:
|
| 455 |
+
LU_real = self.lu(MU_REAL / h * self.I - J)
|
| 456 |
+
LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
|
| 457 |
+
|
| 458 |
+
converged, n_iter, Z, rate = solve_collocation_system(
|
| 459 |
+
self.fun, t, y, h, Z0, scale, self.newton_tol,
|
| 460 |
+
LU_real, LU_complex, self.solve_lu)
|
| 461 |
+
|
| 462 |
+
if not converged:
|
| 463 |
+
if current_jac:
|
| 464 |
+
break
|
| 465 |
+
|
| 466 |
+
J = self.jac(t, y, f)
|
| 467 |
+
current_jac = True
|
| 468 |
+
LU_real = None
|
| 469 |
+
LU_complex = None
|
| 470 |
+
|
| 471 |
+
if not converged:
|
| 472 |
+
h_abs *= 0.5
|
| 473 |
+
LU_real = None
|
| 474 |
+
LU_complex = None
|
| 475 |
+
continue
|
| 476 |
+
|
| 477 |
+
y_new = y + Z[-1]
|
| 478 |
+
ZE = Z.T.dot(E) / h
|
| 479 |
+
error = self.solve_lu(LU_real, f + ZE)
|
| 480 |
+
scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
|
| 481 |
+
error_norm = norm(error / scale)
|
| 482 |
+
safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
|
| 483 |
+
+ n_iter)
|
| 484 |
+
|
| 485 |
+
if rejected and error_norm > 1:
|
| 486 |
+
error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
|
| 487 |
+
error_norm = norm(error / scale)
|
| 488 |
+
|
| 489 |
+
if error_norm > 1:
|
| 490 |
+
factor = predict_factor(h_abs, h_abs_old,
|
| 491 |
+
error_norm, error_norm_old)
|
| 492 |
+
h_abs *= max(MIN_FACTOR, safety * factor)
|
| 493 |
+
|
| 494 |
+
LU_real = None
|
| 495 |
+
LU_complex = None
|
| 496 |
+
rejected = True
|
| 497 |
+
else:
|
| 498 |
+
step_accepted = True
|
| 499 |
+
|
| 500 |
+
recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
|
| 501 |
+
|
| 502 |
+
factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
|
| 503 |
+
factor = min(MAX_FACTOR, safety * factor)
|
| 504 |
+
|
| 505 |
+
if not recompute_jac and factor < 1.2:
|
| 506 |
+
factor = 1
|
| 507 |
+
else:
|
| 508 |
+
LU_real = None
|
| 509 |
+
LU_complex = None
|
| 510 |
+
|
| 511 |
+
f_new = self.fun(t_new, y_new)
|
| 512 |
+
if recompute_jac:
|
| 513 |
+
J = jac(t_new, y_new, f_new)
|
| 514 |
+
current_jac = True
|
| 515 |
+
elif jac is not None:
|
| 516 |
+
current_jac = False
|
| 517 |
+
|
| 518 |
+
self.h_abs_old = self.h_abs
|
| 519 |
+
self.error_norm_old = error_norm
|
| 520 |
+
|
| 521 |
+
self.h_abs = h_abs * factor
|
| 522 |
+
|
| 523 |
+
self.y_old = y
|
| 524 |
+
|
| 525 |
+
self.t = t_new
|
| 526 |
+
self.y = y_new
|
| 527 |
+
self.f = f_new
|
| 528 |
+
|
| 529 |
+
self.Z = Z
|
| 530 |
+
|
| 531 |
+
self.LU_real = LU_real
|
| 532 |
+
self.LU_complex = LU_complex
|
| 533 |
+
self.current_jac = current_jac
|
| 534 |
+
self.J = J
|
| 535 |
+
|
| 536 |
+
self.t_old = t
|
| 537 |
+
self.sol = self._compute_dense_output()
|
| 538 |
+
|
| 539 |
+
return step_accepted, message
|
| 540 |
+
|
| 541 |
+
def _compute_dense_output(self):
|
| 542 |
+
Q = np.dot(self.Z.T, P)
|
| 543 |
+
return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
|
| 544 |
+
|
| 545 |
+
def _dense_output_impl(self):
|
| 546 |
+
return self.sol
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
class RadauDenseOutput(DenseOutput):
|
| 550 |
+
def __init__(self, t_old, t, y_old, Q):
|
| 551 |
+
super().__init__(t_old, t)
|
| 552 |
+
self.h = t - t_old
|
| 553 |
+
self.Q = Q
|
| 554 |
+
self.order = Q.shape[1] - 1
|
| 555 |
+
self.y_old = y_old
|
| 556 |
+
|
| 557 |
+
def _call_impl(self, t):
|
| 558 |
+
x = (t - self.t_old) / self.h
|
| 559 |
+
if t.ndim == 0:
|
| 560 |
+
p = np.tile(x, self.order + 1)
|
| 561 |
+
p = np.cumprod(p)
|
| 562 |
+
else:
|
| 563 |
+
p = np.tile(x, (self.order + 1, 1))
|
| 564 |
+
p = np.cumprod(p, axis=0)
|
| 565 |
+
# Here we don't multiply by h, not a mistake.
|
| 566 |
+
y = np.dot(self.Q, p)
|
| 567 |
+
if y.ndim == 2:
|
| 568 |
+
y += self.y_old[:, None]
|
| 569 |
+
else:
|
| 570 |
+
y += self.y_old
|
| 571 |
+
|
| 572 |
+
return y
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_ivp/tests/__init__.py
ADDED
|
File without changes
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_lebedev.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
infer_4_30_0/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
|
infer_4_30_0/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)
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_odepack.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:405e393b7e8bb42de902c77d9affa7e88163141aeea18532f20bd77efc61076d
|
| 3 |
+
size 479121
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_odepack_py.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quad_vec.py
ADDED
|
@@ -0,0 +1,682 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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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
|
infer_4_30_0/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
|
infer_4_30_0/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:
|
| 1277 |
+
return value, self.abserr, self.out_dict
|
| 1278 |
+
else:
|
| 1279 |
+
return value, self.abserr
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_quadrature.py
ADDED
|
@@ -0,0 +1,1336 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import numpy.typing as npt
|
| 3 |
+
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)
|
infer_4_30_0/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('_')]
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (671 Bytes). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_base.cpython-310.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_kronrod.cpython-310.pyc
ADDED
|
Binary file (4.86 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_gauss_legendre.cpython-310.pyc
ADDED
|
Binary file (2.08 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/__pycache__/_genz_malik.cpython-310.pyc
ADDED
|
Binary file (5.08 kB). View file
|
|
|
infer_4_30_0/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
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_rules/_gauss_legendre.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from scipy._lib._array_api import array_namespace, np_compat
|
| 2 |
+
|
| 3 |
+
from functools import cached_property
|
| 4 |
+
|
| 5 |
+
from scipy.special import roots_legendre
|
| 6 |
+
|
| 7 |
+
from ._base import FixedRule
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class GaussLegendreQuadrature(FixedRule):
|
| 11 |
+
"""
|
| 12 |
+
Gauss-Legendre quadrature.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
----------
|
| 16 |
+
npoints : int
|
| 17 |
+
Number of nodes for the higher-order rule.
|
| 18 |
+
|
| 19 |
+
xp : array_namespace, optional
|
| 20 |
+
The namespace for the node and weight arrays. Default is None, where NumPy is
|
| 21 |
+
used.
|
| 22 |
+
|
| 23 |
+
Examples
|
| 24 |
+
--------
|
| 25 |
+
Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
|
| 26 |
+
estimates will also be arrays.
|
| 27 |
+
|
| 28 |
+
>>> import numpy as np
|
| 29 |
+
>>> from scipy.integrate import cubature
|
| 30 |
+
>>> from scipy.integrate._rules import GaussLegendreQuadrature
|
| 31 |
+
>>> def f(x):
|
| 32 |
+
... return np.cos(x)
|
| 33 |
+
>>> rule = GaussLegendreQuadrature(21) # Use 21-point GaussLegendre
|
| 34 |
+
>>> a, b = np.array([0]), np.array([1])
|
| 35 |
+
>>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
|
| 36 |
+
array([0.84147098])
|
| 37 |
+
>>> rule.estimate_error(f, a, b)
|
| 38 |
+
array([1.11022302e-16])
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, npoints, xp=None):
|
| 42 |
+
if npoints < 2:
|
| 43 |
+
raise ValueError(
|
| 44 |
+
"At least 2 nodes required for Gauss-Legendre cubature"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
self.npoints = npoints
|
| 48 |
+
|
| 49 |
+
if xp is None:
|
| 50 |
+
xp = np_compat
|
| 51 |
+
|
| 52 |
+
self.xp = array_namespace(xp.empty(0))
|
| 53 |
+
|
| 54 |
+
@cached_property
|
| 55 |
+
def nodes_and_weights(self):
|
| 56 |
+
# TODO: current converting to/from numpy
|
| 57 |
+
nodes, weights = roots_legendre(self.npoints)
|
| 58 |
+
|
| 59 |
+
return (
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import itertools
|
| 3 |
+
|
| 4 |
+
from functools import cached_property
|
| 5 |
+
|
| 6 |
+
from scipy._lib._array_api import array_namespace, np_compat
|
| 7 |
+
|
| 8 |
+
from scipy.integrate._rules import NestedFixedRule
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class GenzMalikCubature(NestedFixedRule):
|
| 12 |
+
"""
|
| 13 |
+
Genz-Malik cubature.
|
| 14 |
+
|
| 15 |
+
Genz-Malik is only defined for integrals of dimension >= 2.
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
ndim : int
|
| 20 |
+
The spatial dimension of the integrand.
|
| 21 |
+
|
| 22 |
+
xp : array_namespace, optional
|
| 23 |
+
The namespace for the node and weight arrays. Default is None, where NumPy is
|
| 24 |
+
used.
|
| 25 |
+
|
| 26 |
+
Attributes
|
| 27 |
+
----------
|
| 28 |
+
higher : Cubature
|
| 29 |
+
Higher-order rule.
|
| 30 |
+
|
| 31 |
+
lower : Cubature
|
| 32 |
+
Lower-order rule.
|
| 33 |
+
|
| 34 |
+
References
|
| 35 |
+
----------
|
| 36 |
+
.. [1] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
|
| 37 |
+
numerical integration over an N-dimensional rectangular region, Journal of
|
| 38 |
+
Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
|
| 39 |
+
ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
|
| 40 |
+
|
| 41 |
+
Examples
|
| 42 |
+
--------
|
| 43 |
+
Evaluate a 3D integral:
|
| 44 |
+
|
| 45 |
+
>>> import numpy as np
|
| 46 |
+
>>> from scipy.integrate import cubature
|
| 47 |
+
>>> from scipy.integrate._rules import GenzMalikCubature
|
| 48 |
+
>>> def f(x):
|
| 49 |
+
... # f(x) = cos(x_1) + cos(x_2) + cos(x_3)
|
| 50 |
+
... return np.sum(np.cos(x), axis=-1)
|
| 51 |
+
>>> rule = GenzMalikCubature(3) # Use 3D Genz-Malik
|
| 52 |
+
>>> a, b = np.array([0, 0, 0]), np.array([1, 1, 1])
|
| 53 |
+
>>> rule.estimate(f, a, b) # True value 3*sin(1), approximately 2.5244
|
| 54 |
+
np.float64(2.5244129547230862)
|
| 55 |
+
>>> rule.estimate_error(f, a, b)
|
| 56 |
+
np.float64(1.378269656626685e-06)
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, ndim, degree=7, lower_degree=5, xp=None):
|
| 60 |
+
if ndim < 2:
|
| 61 |
+
raise ValueError("Genz-Malik cubature is only defined for ndim >= 2")
|
| 62 |
+
|
| 63 |
+
if degree != 7 or lower_degree != 5:
|
| 64 |
+
raise NotImplementedError("Genz-Malik cubature is currently only supported"
|
| 65 |
+
"for degree=7, lower_degree=5")
|
| 66 |
+
|
| 67 |
+
self.ndim = ndim
|
| 68 |
+
self.degree = degree
|
| 69 |
+
self.lower_degree = lower_degree
|
| 70 |
+
|
| 71 |
+
if xp is None:
|
| 72 |
+
xp = np_compat
|
| 73 |
+
|
| 74 |
+
self.xp = array_namespace(xp.empty(0))
|
| 75 |
+
|
| 76 |
+
@cached_property
|
| 77 |
+
def nodes_and_weights(self):
|
| 78 |
+
# TODO: Currently only support for degree 7 Genz-Malik cubature, should aim to
|
| 79 |
+
# support arbitrary degree
|
| 80 |
+
l_2 = math.sqrt(9/70)
|
| 81 |
+
l_3 = math.sqrt(9/10)
|
| 82 |
+
l_4 = math.sqrt(9/10)
|
| 83 |
+
l_5 = math.sqrt(9/19)
|
| 84 |
+
|
| 85 |
+
its = itertools.chain(
|
| 86 |
+
[(0,) * self.ndim],
|
| 87 |
+
_distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
|
| 88 |
+
_distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
|
| 89 |
+
_distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
|
| 90 |
+
_distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
|
| 91 |
+
_distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
|
| 92 |
+
_distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
|
| 93 |
+
_distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
|
| 94 |
+
itertools.product((l_5, -l_5), repeat=self.ndim),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + 2**self.ndim
|
| 98 |
+
|
| 99 |
+
nodes = self.xp.asarray(
|
| 100 |
+
list(zip(*its)),
|
| 101 |
+
dtype=self.xp.float64,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
|
| 105 |
+
|
| 106 |
+
# It's convenient to generate the nodes as a sequence of evaluation points
|
| 107 |
+
# as an array of shape (npoints, ndim), but nodes needs to have shape
|
| 108 |
+
# (ndim, npoints)
|
| 109 |
+
nodes = nodes.T
|
| 110 |
+
|
| 111 |
+
w_1 = (
|
| 112 |
+
(2**self.ndim) * (12824 - 9120*self.ndim + (400 * self.ndim**2)) / 19683
|
| 113 |
+
)
|
| 114 |
+
w_2 = (2**self.ndim) * 980/6561
|
| 115 |
+
w_3 = (2**self.ndim) * (1820 - 400 * self.ndim) / 19683
|
| 116 |
+
w_4 = (2**self.ndim) * (200 / 19683)
|
| 117 |
+
w_5 = 6859 / 19683
|
| 118 |
+
|
| 119 |
+
weights = self.xp.concat([
|
| 120 |
+
self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
|
| 121 |
+
self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
|
| 122 |
+
self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
|
| 123 |
+
self.xp.asarray(
|
| 124 |
+
[w_4] * (2 * (self.ndim - 1) * self.ndim),
|
| 125 |
+
dtype=self.xp.float64,
|
| 126 |
+
),
|
| 127 |
+
self.xp.asarray([w_5] * (2**self.ndim), dtype=self.xp.float64),
|
| 128 |
+
])
|
| 129 |
+
|
| 130 |
+
return nodes, weights
|
| 131 |
+
|
| 132 |
+
@cached_property
|
| 133 |
+
def lower_nodes_and_weights(self):
|
| 134 |
+
# TODO: Currently only support for the degree 5 lower rule, in the future it
|
| 135 |
+
# would be worth supporting arbitrary degree
|
| 136 |
+
|
| 137 |
+
# Nodes are almost the same as the full rule, but there are no nodes
|
| 138 |
+
# corresponding to l_5.
|
| 139 |
+
l_2 = math.sqrt(9/70)
|
| 140 |
+
l_3 = math.sqrt(9/10)
|
| 141 |
+
l_4 = math.sqrt(9/10)
|
| 142 |
+
|
| 143 |
+
its = itertools.chain(
|
| 144 |
+
[(0,) * self.ndim],
|
| 145 |
+
_distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
|
| 146 |
+
_distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
|
| 147 |
+
_distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
|
| 148 |
+
_distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
|
| 149 |
+
_distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
|
| 150 |
+
_distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
|
| 151 |
+
_distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim)
|
| 155 |
+
|
| 156 |
+
nodes = self.xp.asarray(list(zip(*its)), dtype=self.xp.float64)
|
| 157 |
+
nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
|
| 158 |
+
nodes = nodes.T
|
| 159 |
+
|
| 160 |
+
# Weights are different from those in the full rule.
|
| 161 |
+
w_1 = (2**self.ndim) * (729 - 950*self.ndim + 50*self.ndim**2) / 729
|
| 162 |
+
w_2 = (2**self.ndim) * (245 / 486)
|
| 163 |
+
w_3 = (2**self.ndim) * (265 - 100*self.ndim) / 1458
|
| 164 |
+
w_4 = (2**self.ndim) * (25 / 729)
|
| 165 |
+
|
| 166 |
+
weights = self.xp.concat([
|
| 167 |
+
self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
|
| 168 |
+
self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
|
| 169 |
+
self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
|
| 170 |
+
self.xp.asarray(
|
| 171 |
+
[w_4] * (2 * (self.ndim - 1) * self.ndim),
|
| 172 |
+
dtype=self.xp.float64,
|
| 173 |
+
),
|
| 174 |
+
])
|
| 175 |
+
|
| 176 |
+
return nodes, weights
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def _distinct_permutations(iterable):
|
| 180 |
+
"""
|
| 181 |
+
Find the number of distinct permutations of elements of `iterable`.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
# Algorithm: https://w.wiki/Qai
|
| 185 |
+
|
| 186 |
+
items = sorted(iterable)
|
| 187 |
+
size = len(items)
|
| 188 |
+
|
| 189 |
+
while True:
|
| 190 |
+
# Yield the permutation we have
|
| 191 |
+
yield tuple(items)
|
| 192 |
+
|
| 193 |
+
# Find the largest index i such that A[i] < A[i + 1]
|
| 194 |
+
for i in range(size - 2, -1, -1):
|
| 195 |
+
if items[i] < items[i + 1]:
|
| 196 |
+
break
|
| 197 |
+
|
| 198 |
+
# If no such index exists, this permutation is the last one
|
| 199 |
+
else:
|
| 200 |
+
return
|
| 201 |
+
|
| 202 |
+
# Find the largest index j greater than j such that A[i] < A[j]
|
| 203 |
+
for j in range(size - 1, i, -1):
|
| 204 |
+
if items[i] < items[j]:
|
| 205 |
+
break
|
| 206 |
+
|
| 207 |
+
# Swap the value of A[i] with that of A[j], then reverse the
|
| 208 |
+
# sequence from A[i + 1] to form the new permutation
|
| 209 |
+
items[i], items[j] = items[j], items[i]
|
| 210 |
+
items[i+1:] = items[:i-size:-1] # A[i + 1:][::-1]
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_tanhsinh.py
ADDED
|
@@ -0,0 +1,1382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: disable-error-code="attr-defined"
|
| 2 |
+
import math
|
| 3 |
+
import numpy as np
|
| 4 |
+
from scipy import special
|
| 5 |
+
import scipy._lib._elementwise_iterative_method as eim
|
| 6 |
+
from scipy._lib._util import _RichResult
|
| 7 |
+
from scipy._lib._array_api import (array_namespace, xp_copy, xp_ravel,
|
| 8 |
+
xp_real, xp_take_along_axis)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = ['nsum']
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# todo:
|
| 15 |
+
# figure out warning situation
|
| 16 |
+
# address https://github.com/scipy/scipy/pull/18650#discussion_r1233032521
|
| 17 |
+
# without `minweight`, we are also suppressing infinities within the interval.
|
| 18 |
+
# Is that OK? If so, we can probably get rid of `status=3`.
|
| 19 |
+
# Add heuristic to stop when improvement is too slow / antithrashing
|
| 20 |
+
# support singularities? interval subdivision? this feature will be added
|
| 21 |
+
# eventually, but do we adjust the interface now?
|
| 22 |
+
# When doing log-integration, should the tolerances control the error of the
|
| 23 |
+
# log-integral or the error of the integral? The trouble is that `log`
|
| 24 |
+
# inherently looses some precision so it may not be possible to refine
|
| 25 |
+
# the integral further. Example: 7th moment of stats.f(15, 20)
|
| 26 |
+
# respect function evaluation limit?
|
| 27 |
+
# make public?
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def tanhsinh(f, a, b, *, args=(), log=False, maxlevel=None, minlevel=2,
|
| 31 |
+
atol=None, rtol=None, preserve_shape=False, callback=None):
|
| 32 |
+
"""Evaluate a convergent integral numerically using tanh-sinh quadrature.
|
| 33 |
+
|
| 34 |
+
In practice, tanh-sinh quadrature achieves quadratic convergence for
|
| 35 |
+
many integrands: the number of accurate *digits* scales roughly linearly
|
| 36 |
+
with the number of function evaluations [1]_.
|
| 37 |
+
|
| 38 |
+
Either or both of the limits of integration may be infinite, and
|
| 39 |
+
singularities at the endpoints are acceptable. Divergent integrals and
|
| 40 |
+
integrands with non-finite derivatives or singularities within an interval
|
| 41 |
+
are out of scope, but the latter may be evaluated be calling `tanhsinh` on
|
| 42 |
+
each sub-interval separately.
|
| 43 |
+
|
| 44 |
+
Parameters
|
| 45 |
+
----------
|
| 46 |
+
f : callable
|
| 47 |
+
The function to be integrated. The signature must be::
|
| 48 |
+
|
| 49 |
+
f(xi: ndarray, *argsi) -> ndarray
|
| 50 |
+
|
| 51 |
+
where each element of ``xi`` is a finite real number and ``argsi`` is a tuple,
|
| 52 |
+
which may contain an arbitrary number of arrays that are broadcastable
|
| 53 |
+
with ``xi``. `f` must be an elementwise function: see documentation of parameter
|
| 54 |
+
`preserve_shape` for details. It must not mutate the array ``xi`` or the arrays
|
| 55 |
+
in ``argsi``.
|
| 56 |
+
If ``f`` returns a value with complex dtype when evaluated at
|
| 57 |
+
either endpoint, subsequent arguments ``x`` will have complex dtype
|
| 58 |
+
(but zero imaginary part).
|
| 59 |
+
a, b : float array_like
|
| 60 |
+
Real lower and upper limits of integration. Must be broadcastable with one
|
| 61 |
+
another and with arrays in `args`. Elements may be infinite.
|
| 62 |
+
args : tuple of array_like, optional
|
| 63 |
+
Additional positional array arguments to be passed to `f`. Arrays
|
| 64 |
+
must be broadcastable with one another and the arrays of `a` and `b`.
|
| 65 |
+
If the callable for which the root is desired requires arguments that are
|
| 66 |
+
not broadcastable with `x`, wrap that callable with `f` such that `f`
|
| 67 |
+
accepts only `x` and broadcastable ``*args``.
|
| 68 |
+
log : bool, default: False
|
| 69 |
+
Setting to True indicates that `f` returns the log of the integrand
|
| 70 |
+
and that `atol` and `rtol` are expressed as the logs of the absolute
|
| 71 |
+
and relative errors. In this case, the result object will contain the
|
| 72 |
+
log of the integral and error. This is useful for integrands for which
|
| 73 |
+
numerical underflow or overflow would lead to inaccuracies.
|
| 74 |
+
When ``log=True``, the integrand (the exponential of `f`) must be real,
|
| 75 |
+
but it may be negative, in which case the log of the integrand is a
|
| 76 |
+
complex number with an imaginary part that is an odd multiple of π.
|
| 77 |
+
maxlevel : int, default: 10
|
| 78 |
+
The maximum refinement level of the algorithm.
|
| 79 |
+
|
| 80 |
+
At the zeroth level, `f` is called once, performing 16 function
|
| 81 |
+
evaluations. At each subsequent level, `f` is called once more,
|
| 82 |
+
approximately doubling the number of function evaluations that have
|
| 83 |
+
been performed. Accordingly, for many integrands, each successive level
|
| 84 |
+
will double the number of accurate digits in the result (up to the
|
| 85 |
+
limits of floating point precision).
|
| 86 |
+
|
| 87 |
+
The algorithm will terminate after completing level `maxlevel` or after
|
| 88 |
+
another termination condition is satisfied, whichever comes first.
|
| 89 |
+
minlevel : int, default: 2
|
| 90 |
+
The level at which to begin iteration (default: 2). This does not
|
| 91 |
+
change the total number of function evaluations or the abscissae at
|
| 92 |
+
which the function is evaluated; it changes only the *number of times*
|
| 93 |
+
`f` is called. If ``minlevel=k``, then the integrand is evaluated at
|
| 94 |
+
all abscissae from levels ``0`` through ``k`` in a single call.
|
| 95 |
+
Note that if `minlevel` exceeds `maxlevel`, the provided `minlevel` is
|
| 96 |
+
ignored, and `minlevel` is set equal to `maxlevel`.
|
| 97 |
+
atol, rtol : float, optional
|
| 98 |
+
Absolute termination tolerance (default: 0) and relative termination
|
| 99 |
+
tolerance (default: ``eps**0.75``, where ``eps`` is the precision of
|
| 100 |
+
the result dtype), respectively. Iteration will stop when
|
| 101 |
+
``res.error < atol + rtol * abs(res.df)``. The error estimate is as
|
| 102 |
+
described in [1]_ Section 5. While not theoretically rigorous or
|
| 103 |
+
conservative, it is said to work well in practice. Must be non-negative
|
| 104 |
+
and finite if `log` is False, and must be expressed as the log of a
|
| 105 |
+
non-negative and finite number if `log` is True.
|
| 106 |
+
preserve_shape : bool, default: False
|
| 107 |
+
In the following, "arguments of `f`" refers to the array ``xi`` and
|
| 108 |
+
any arrays within ``argsi``. Let ``shape`` be the broadcasted shape
|
| 109 |
+
of `a`, `b`, and all elements of `args` (which is conceptually
|
| 110 |
+
distinct from ``xi` and ``argsi`` passed into `f`).
|
| 111 |
+
|
| 112 |
+
- When ``preserve_shape=False`` (default), `f` must accept arguments
|
| 113 |
+
of *any* broadcastable shapes.
|
| 114 |
+
|
| 115 |
+
- When ``preserve_shape=True``, `f` must accept arguments of shape
|
| 116 |
+
``shape`` *or* ``shape + (n,)``, where ``(n,)`` is the number of
|
| 117 |
+
abscissae at which the function is being evaluated.
|
| 118 |
+
|
| 119 |
+
In either case, for each scalar element ``xi[j]`` within ``xi``, the array
|
| 120 |
+
returned by `f` must include the scalar ``f(xi[j])`` at the same index.
|
| 121 |
+
Consequently, the shape of the output is always the shape of the input
|
| 122 |
+
``xi``.
|
| 123 |
+
|
| 124 |
+
See Examples.
|
| 125 |
+
|
| 126 |
+
callback : callable, optional
|
| 127 |
+
An optional user-supplied function to be called before the first
|
| 128 |
+
iteration and after each iteration.
|
| 129 |
+
Called as ``callback(res)``, where ``res`` is a ``_RichResult``
|
| 130 |
+
similar to that returned by `_differentiate` (but containing the
|
| 131 |
+
current iterate's values of all variables). If `callback` raises a
|
| 132 |
+
``StopIteration``, the algorithm will terminate immediately and
|
| 133 |
+
`tanhsinh` will return a result object. `callback` must not mutate
|
| 134 |
+
`res` or its attributes.
|
| 135 |
+
|
| 136 |
+
Returns
|
| 137 |
+
-------
|
| 138 |
+
res : _RichResult
|
| 139 |
+
An object similar to an instance of `scipy.optimize.OptimizeResult` with the
|
| 140 |
+
following attributes. (The descriptions are written as though the values will
|
| 141 |
+
be scalars; however, if `f` returns an array, the outputs will be
|
| 142 |
+
arrays of the same shape.)
|
| 143 |
+
|
| 144 |
+
success : bool array
|
| 145 |
+
``True`` when the algorithm terminated successfully (status ``0``).
|
| 146 |
+
``False`` otherwise.
|
| 147 |
+
status : int array
|
| 148 |
+
An integer representing the exit status of the algorithm.
|
| 149 |
+
|
| 150 |
+
``0`` : The algorithm converged to the specified tolerances.
|
| 151 |
+
``-1`` : (unused)
|
| 152 |
+
``-2`` : The maximum number of iterations was reached.
|
| 153 |
+
``-3`` : A non-finite value was encountered.
|
| 154 |
+
``-4`` : Iteration was terminated by `callback`.
|
| 155 |
+
``1`` : The algorithm is proceeding normally (in `callback` only).
|
| 156 |
+
|
| 157 |
+
integral : float array
|
| 158 |
+
An estimate of the integral.
|
| 159 |
+
error : float array
|
| 160 |
+
An estimate of the error. Only available if level two or higher
|
| 161 |
+
has been completed; otherwise NaN.
|
| 162 |
+
maxlevel : int array
|
| 163 |
+
The maximum refinement level used.
|
| 164 |
+
nfev : int array
|
| 165 |
+
The number of points at which `f` was evaluated.
|
| 166 |
+
|
| 167 |
+
See Also
|
| 168 |
+
--------
|
| 169 |
+
quad
|
| 170 |
+
|
| 171 |
+
Notes
|
| 172 |
+
-----
|
| 173 |
+
Implements the algorithm as described in [1]_ with minor adaptations for
|
| 174 |
+
finite-precision arithmetic, including some described by [2]_ and [3]_. The
|
| 175 |
+
tanh-sinh scheme was originally introduced in [4]_.
|
| 176 |
+
|
| 177 |
+
Due to floating-point error in the abscissae, the function may be evaluated
|
| 178 |
+
at the endpoints of the interval during iterations, but the values returned by
|
| 179 |
+
the function at the endpoints will be ignored.
|
| 180 |
+
|
| 181 |
+
References
|
| 182 |
+
----------
|
| 183 |
+
.. [1] Bailey, David H., Karthik Jeyabalan, and Xiaoye S. Li. "A comparison of
|
| 184 |
+
three high-precision quadrature schemes." Experimental Mathematics 14.3
|
| 185 |
+
(2005): 317-329.
|
| 186 |
+
.. [2] Vanherck, Joren, Bart Sorée, and Wim Magnus. "Tanh-sinh quadrature for
|
| 187 |
+
single and multiple integration using floating-point arithmetic."
|
| 188 |
+
arXiv preprint arXiv:2007.15057 (2020).
|
| 189 |
+
.. [3] van Engelen, Robert A. "Improving the Double Exponential Quadrature
|
| 190 |
+
Tanh-Sinh, Sinh-Sinh and Exp-Sinh Formulas."
|
| 191 |
+
https://www.genivia.com/files/qthsh.pdf
|
| 192 |
+
.. [4] Takahasi, Hidetosi, and Masatake Mori. "Double exponential formulas for
|
| 193 |
+
numerical integration." Publications of the Research Institute for
|
| 194 |
+
Mathematical Sciences 9.3 (1974): 721-741.
|
| 195 |
+
|
| 196 |
+
Examples
|
| 197 |
+
--------
|
| 198 |
+
Evaluate the Gaussian integral:
|
| 199 |
+
|
| 200 |
+
>>> import numpy as np
|
| 201 |
+
>>> from scipy.integrate import tanhsinh
|
| 202 |
+
>>> def f(x):
|
| 203 |
+
... return np.exp(-x**2)
|
| 204 |
+
>>> res = tanhsinh(f, -np.inf, np.inf)
|
| 205 |
+
>>> res.integral # true value is np.sqrt(np.pi), 1.7724538509055159
|
| 206 |
+
1.7724538509055159
|
| 207 |
+
>>> res.error # actual error is 0
|
| 208 |
+
4.0007963937534104e-16
|
| 209 |
+
|
| 210 |
+
The value of the Gaussian function (bell curve) is nearly zero for
|
| 211 |
+
arguments sufficiently far from zero, so the value of the integral
|
| 212 |
+
over a finite interval is nearly the same.
|
| 213 |
+
|
| 214 |
+
>>> tanhsinh(f, -20, 20).integral
|
| 215 |
+
1.772453850905518
|
| 216 |
+
|
| 217 |
+
However, with unfavorable integration limits, the integration scheme
|
| 218 |
+
may not be able to find the important region.
|
| 219 |
+
|
| 220 |
+
>>> tanhsinh(f, -np.inf, 1000).integral
|
| 221 |
+
4.500490856616431
|
| 222 |
+
|
| 223 |
+
In such cases, or when there are singularities within the interval,
|
| 224 |
+
break the integral into parts with endpoints at the important points.
|
| 225 |
+
|
| 226 |
+
>>> tanhsinh(f, -np.inf, 0).integral + tanhsinh(f, 0, 1000).integral
|
| 227 |
+
1.772453850905404
|
| 228 |
+
|
| 229 |
+
For integration involving very large or very small magnitudes, use
|
| 230 |
+
log-integration. (For illustrative purposes, the following example shows a
|
| 231 |
+
case in which both regular and log-integration work, but for more extreme
|
| 232 |
+
limits of integration, log-integration would avoid the underflow
|
| 233 |
+
experienced when evaluating the integral normally.)
|
| 234 |
+
|
| 235 |
+
>>> res = tanhsinh(f, 20, 30, rtol=1e-10)
|
| 236 |
+
>>> res.integral, res.error
|
| 237 |
+
(4.7819613911309014e-176, 4.670364401645202e-187)
|
| 238 |
+
>>> def log_f(x):
|
| 239 |
+
... return -x**2
|
| 240 |
+
>>> res = tanhsinh(log_f, 20, 30, log=True, rtol=np.log(1e-10))
|
| 241 |
+
>>> np.exp(res.integral), np.exp(res.error)
|
| 242 |
+
(4.7819613911306924e-176, 4.670364401645093e-187)
|
| 243 |
+
|
| 244 |
+
The limits of integration and elements of `args` may be broadcastable
|
| 245 |
+
arrays, and integration is performed elementwise.
|
| 246 |
+
|
| 247 |
+
>>> from scipy import stats
|
| 248 |
+
>>> dist = stats.gausshyper(13.8, 3.12, 2.51, 5.18)
|
| 249 |
+
>>> a, b = dist.support()
|
| 250 |
+
>>> x = np.linspace(a, b, 100)
|
| 251 |
+
>>> res = tanhsinh(dist.pdf, a, x)
|
| 252 |
+
>>> ref = dist.cdf(x)
|
| 253 |
+
>>> np.allclose(res.integral, ref)
|
| 254 |
+
True
|
| 255 |
+
|
| 256 |
+
By default, `preserve_shape` is False, and therefore the callable
|
| 257 |
+
`f` may be called with arrays of any broadcastable shapes.
|
| 258 |
+
For example:
|
| 259 |
+
|
| 260 |
+
>>> shapes = []
|
| 261 |
+
>>> def f(x, c):
|
| 262 |
+
... shape = np.broadcast_shapes(x.shape, c.shape)
|
| 263 |
+
... shapes.append(shape)
|
| 264 |
+
... return np.sin(c*x)
|
| 265 |
+
>>>
|
| 266 |
+
>>> c = [1, 10, 30, 100]
|
| 267 |
+
>>> res = tanhsinh(f, 0, 1, args=(c,), minlevel=1)
|
| 268 |
+
>>> shapes
|
| 269 |
+
[(4,), (4, 34), (4, 32), (3, 64), (2, 128), (1, 256)]
|
| 270 |
+
|
| 271 |
+
To understand where these shapes are coming from - and to better
|
| 272 |
+
understand how `tanhsinh` computes accurate results - note that
|
| 273 |
+
higher values of ``c`` correspond with higher frequency sinusoids.
|
| 274 |
+
The higher frequency sinusoids make the integrand more complicated,
|
| 275 |
+
so more function evaluations are required to achieve the target
|
| 276 |
+
accuracy:
|
| 277 |
+
|
| 278 |
+
>>> res.nfev
|
| 279 |
+
array([ 67, 131, 259, 515], dtype=int32)
|
| 280 |
+
|
| 281 |
+
The initial ``shape``, ``(4,)``, corresponds with evaluating the
|
| 282 |
+
integrand at a single abscissa and all four frequencies; this is used
|
| 283 |
+
for input validation and to determine the size and dtype of the arrays
|
| 284 |
+
that store results. The next shape corresponds with evaluating the
|
| 285 |
+
integrand at an initial grid of abscissae and all four frequencies.
|
| 286 |
+
Successive calls to the function double the total number of abscissae at
|
| 287 |
+
which the function has been evaluated. However, in later function
|
| 288 |
+
evaluations, the integrand is evaluated at fewer frequencies because
|
| 289 |
+
the corresponding integral has already converged to the required
|
| 290 |
+
tolerance. This saves function evaluations to improve performance, but
|
| 291 |
+
it requires the function to accept arguments of any shape.
|
| 292 |
+
|
| 293 |
+
"Vector-valued" integrands, such as those written for use with
|
| 294 |
+
`scipy.integrate.quad_vec`, are unlikely to satisfy this requirement.
|
| 295 |
+
For example, consider
|
| 296 |
+
|
| 297 |
+
>>> def f(x):
|
| 298 |
+
... return [x, np.sin(10*x), np.cos(30*x), x*np.sin(100*x)**2]
|
| 299 |
+
|
| 300 |
+
This integrand is not compatible with `tanhsinh` as written; for instance,
|
| 301 |
+
the shape of the output will not be the same as the shape of ``x``. Such a
|
| 302 |
+
function *could* be converted to a compatible form with the introduction of
|
| 303 |
+
additional parameters, but this would be inconvenient. In such cases,
|
| 304 |
+
a simpler solution would be to use `preserve_shape`.
|
| 305 |
+
|
| 306 |
+
>>> shapes = []
|
| 307 |
+
>>> def f(x):
|
| 308 |
+
... shapes.append(x.shape)
|
| 309 |
+
... x0, x1, x2, x3 = x
|
| 310 |
+
... return [x0, np.sin(10*x1), np.cos(30*x2), x3*np.sin(100*x3)]
|
| 311 |
+
>>>
|
| 312 |
+
>>> a = np.zeros(4)
|
| 313 |
+
>>> res = tanhsinh(f, a, 1, preserve_shape=True)
|
| 314 |
+
>>> shapes
|
| 315 |
+
[(4,), (4, 66), (4, 64), (4, 128), (4, 256)]
|
| 316 |
+
|
| 317 |
+
Here, the broadcasted shape of `a` and `b` is ``(4,)``. With
|
| 318 |
+
``preserve_shape=True``, the function may be called with argument
|
| 319 |
+
``x`` of shape ``(4,)`` or ``(4, n)``, and this is what we observe.
|
| 320 |
+
|
| 321 |
+
"""
|
| 322 |
+
maxfun = None # unused right now
|
| 323 |
+
(f, a, b, log, maxfun, maxlevel, minlevel,
|
| 324 |
+
atol, rtol, args, preserve_shape, callback, xp) = _tanhsinh_iv(
|
| 325 |
+
f, a, b, log, maxfun, maxlevel, minlevel, atol,
|
| 326 |
+
rtol, args, preserve_shape, callback)
|
| 327 |
+
|
| 328 |
+
# Initialization
|
| 329 |
+
# `eim._initialize` does several important jobs, including
|
| 330 |
+
# ensuring that limits, each of the `args`, and the output of `f`
|
| 331 |
+
# broadcast correctly and are of consistent types. To save a function
|
| 332 |
+
# evaluation, I pass the midpoint of the integration interval. This comes
|
| 333 |
+
# at a cost of some gymnastics to ensure that the midpoint has the right
|
| 334 |
+
# shape and dtype. Did you know that 0d and >0d arrays follow different
|
| 335 |
+
# type promotion rules?
|
| 336 |
+
with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
|
| 337 |
+
c = xp.reshape((xp_ravel(a) + xp_ravel(b))/2, a.shape)
|
| 338 |
+
inf_a, inf_b = xp.isinf(a), xp.isinf(b)
|
| 339 |
+
c[inf_a] = b[inf_a] - 1. # takes care of infinite a
|
| 340 |
+
c[inf_b] = a[inf_b] + 1. # takes care of infinite b
|
| 341 |
+
c[inf_a & inf_b] = 0. # takes care of infinite a and b
|
| 342 |
+
temp = eim._initialize(f, (c,), args, complex_ok=True,
|
| 343 |
+
preserve_shape=preserve_shape, xp=xp)
|
| 344 |
+
f, xs, fs, args, shape, dtype, xp = temp
|
| 345 |
+
a = xp_ravel(xp.astype(xp.broadcast_to(a, shape), dtype))
|
| 346 |
+
b = xp_ravel(xp.astype(xp.broadcast_to(b, shape), dtype))
|
| 347 |
+
|
| 348 |
+
# Transform improper integrals
|
| 349 |
+
a, b, a0, negative, abinf, ainf, binf = _transform_integrals(a, b, xp)
|
| 350 |
+
|
| 351 |
+
# Define variables we'll need
|
| 352 |
+
nit, nfev = 0, 1 # one function evaluation performed above
|
| 353 |
+
zero = -xp.inf if log else 0
|
| 354 |
+
pi = xp.asarray(xp.pi, dtype=dtype)[()]
|
| 355 |
+
maxiter = maxlevel - minlevel + 1
|
| 356 |
+
eps = xp.finfo(dtype).eps
|
| 357 |
+
if rtol is None:
|
| 358 |
+
rtol = 0.75*math.log(eps) if log else eps**0.75
|
| 359 |
+
|
| 360 |
+
Sn = xp_ravel(xp.full(shape, zero, dtype=dtype)) # latest integral estimate
|
| 361 |
+
Sn[xp.isnan(a) | xp.isnan(b) | xp.isnan(fs[0])] = xp.nan
|
| 362 |
+
Sk = xp.reshape(xp.empty_like(Sn), (-1, 1))[:, 0:0] # all integral estimates
|
| 363 |
+
aerr = xp_ravel(xp.full(shape, xp.nan, dtype=dtype)) # absolute error
|
| 364 |
+
status = xp_ravel(xp.full(shape, eim._EINPROGRESS, dtype=xp.int32))
|
| 365 |
+
h0 = _get_base_step(dtype, xp)
|
| 366 |
+
h0 = xp_real(h0) # base step
|
| 367 |
+
|
| 368 |
+
# For term `d4` of error estimate ([1] Section 5), we need to keep the
|
| 369 |
+
# most extreme abscissae and corresponding `fj`s, `wj`s in Euler-Maclaurin
|
| 370 |
+
# sum. Here, we initialize these variables.
|
| 371 |
+
xr0 = xp_ravel(xp.full(shape, -xp.inf, dtype=dtype))
|
| 372 |
+
fr0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
|
| 373 |
+
wr0 = xp_ravel(xp.zeros(shape, dtype=dtype))
|
| 374 |
+
xl0 = xp_ravel(xp.full(shape, xp.inf, dtype=dtype))
|
| 375 |
+
fl0 = xp_ravel(xp.full(shape, xp.nan, dtype=dtype))
|
| 376 |
+
wl0 = xp_ravel(xp.zeros(shape, dtype=dtype))
|
| 377 |
+
d4 = xp_ravel(xp.zeros(shape, dtype=dtype))
|
| 378 |
+
|
| 379 |
+
work = _RichResult(
|
| 380 |
+
Sn=Sn, Sk=Sk, aerr=aerr, h=h0, log=log, dtype=dtype, pi=pi, eps=eps,
|
| 381 |
+
a=xp.reshape(a, (-1, 1)), b=xp.reshape(b, (-1, 1)), # integration limits
|
| 382 |
+
n=minlevel, nit=nit, nfev=nfev, status=status, # iter/eval counts
|
| 383 |
+
xr0=xr0, fr0=fr0, wr0=wr0, xl0=xl0, fl0=fl0, wl0=wl0, d4=d4, # err est
|
| 384 |
+
ainf=ainf, binf=binf, abinf=abinf, a0=xp.reshape(a0, (-1, 1)), # transforms
|
| 385 |
+
# Store the xjc/wj pair cache in an object so they can't get compressed
|
| 386 |
+
# Using RichResult to allow dot notation, but a dictionary would suffice
|
| 387 |
+
pair_cache=_RichResult(xjc=None, wj=None, indices=[0], h0=None)) # pair cache
|
| 388 |
+
|
| 389 |
+
# Constant scalars don't need to be put in `work` unless they need to be
|
| 390 |
+
# passed outside `tanhsinh`. Examples: atol, rtol, h0, minlevel.
|
| 391 |
+
|
| 392 |
+
# Correspondence between terms in the `work` object and the result
|
| 393 |
+
res_work_pairs = [('status', 'status'), ('integral', 'Sn'),
|
| 394 |
+
('error', 'aerr'), ('nit', 'nit'), ('nfev', 'nfev')]
|
| 395 |
+
|
| 396 |
+
def pre_func_eval(work):
|
| 397 |
+
# Determine abscissae at which to evaluate `f`
|
| 398 |
+
work.h = h0 / 2**work.n
|
| 399 |
+
xjc, wj = _get_pairs(work.n, h0, dtype=work.dtype,
|
| 400 |
+
inclusive=(work.n == minlevel), xp=xp, work=work)
|
| 401 |
+
work.xj, work.wj = _transform_to_limits(xjc, wj, work.a, work.b, xp)
|
| 402 |
+
|
| 403 |
+
# Perform abscissae substitutions for infinite limits of integration
|
| 404 |
+
xj = xp_copy(work.xj)
|
| 405 |
+
# use xp_real here to avoid cupy/cupy#8434
|
| 406 |
+
xj[work.abinf] = xj[work.abinf] / (1 - xp_real(xj[work.abinf])**2)
|
| 407 |
+
xj[work.binf] = 1/xj[work.binf] - 1 + work.a0[work.binf]
|
| 408 |
+
xj[work.ainf] *= -1
|
| 409 |
+
return xj
|
| 410 |
+
|
| 411 |
+
def post_func_eval(x, fj, work):
|
| 412 |
+
# Weight integrand as required by substitutions for infinite limits
|
| 413 |
+
if work.log:
|
| 414 |
+
fj[work.abinf] += (xp.log(1 + work.xj[work.abinf]**2)
|
| 415 |
+
- 2*xp.log(1 - work.xj[work.abinf]**2))
|
| 416 |
+
fj[work.binf] -= 2 * xp.log(work.xj[work.binf])
|
| 417 |
+
else:
|
| 418 |
+
fj[work.abinf] *= ((1 + work.xj[work.abinf]**2) /
|
| 419 |
+
(1 - work.xj[work.abinf]**2)**2)
|
| 420 |
+
fj[work.binf] *= work.xj[work.binf]**-2.
|
| 421 |
+
|
| 422 |
+
# Estimate integral with Euler-Maclaurin Sum
|
| 423 |
+
fjwj, Sn = _euler_maclaurin_sum(fj, work, xp)
|
| 424 |
+
if work.Sk.shape[-1]:
|
| 425 |
+
Snm1 = work.Sk[:, -1]
|
| 426 |
+
Sn = (special.logsumexp(xp.stack([Snm1 - math.log(2), Sn]), axis=0) if log
|
| 427 |
+
else Snm1 / 2 + Sn)
|
| 428 |
+
|
| 429 |
+
work.fjwj = fjwj
|
| 430 |
+
work.Sn = Sn
|
| 431 |
+
|
| 432 |
+
def check_termination(work):
|
| 433 |
+
"""Terminate due to convergence or encountering non-finite values"""
|
| 434 |
+
stop = xp.zeros(work.Sn.shape, dtype=bool)
|
| 435 |
+
|
| 436 |
+
# Terminate before first iteration if integration limits are equal
|
| 437 |
+
if work.nit == 0:
|
| 438 |
+
i = xp_ravel(work.a == work.b) # ravel singleton dimension
|
| 439 |
+
zero = xp.asarray(-xp.inf if log else 0.)
|
| 440 |
+
zero = xp.full(work.Sn.shape, zero, dtype=Sn.dtype)
|
| 441 |
+
zero[xp.isnan(Sn)] = xp.nan
|
| 442 |
+
work.Sn[i] = zero[i]
|
| 443 |
+
work.aerr[i] = zero[i]
|
| 444 |
+
work.status[i] = eim._ECONVERGED
|
| 445 |
+
stop[i] = True
|
| 446 |
+
else:
|
| 447 |
+
# Terminate if convergence criterion is met
|
| 448 |
+
work.rerr, work.aerr = _estimate_error(work, xp)
|
| 449 |
+
i = ((work.rerr < rtol) | (work.rerr + xp_real(work.Sn) < atol) if log
|
| 450 |
+
else (work.rerr < rtol) | (work.rerr * xp.abs(work.Sn) < atol))
|
| 451 |
+
work.status[i] = eim._ECONVERGED
|
| 452 |
+
stop[i] = True
|
| 453 |
+
|
| 454 |
+
# Terminate if integral estimate becomes invalid
|
| 455 |
+
if log:
|
| 456 |
+
Sn_real = xp_real(work.Sn)
|
| 457 |
+
Sn_pos_inf = xp.isinf(Sn_real) & (Sn_real > 0)
|
| 458 |
+
i = (Sn_pos_inf | xp.isnan(work.Sn)) & ~stop
|
| 459 |
+
else:
|
| 460 |
+
i = ~xp.isfinite(work.Sn) & ~stop
|
| 461 |
+
work.status[i] = eim._EVALUEERR
|
| 462 |
+
stop[i] = True
|
| 463 |
+
|
| 464 |
+
return stop
|
| 465 |
+
|
| 466 |
+
def post_termination_check(work):
|
| 467 |
+
work.n += 1
|
| 468 |
+
work.Sk = xp.concat((work.Sk, work.Sn[:, xp.newaxis]), axis=-1)
|
| 469 |
+
return
|
| 470 |
+
|
| 471 |
+
def customize_result(res, shape):
|
| 472 |
+
# If the integration limits were such that b < a, we reversed them
|
| 473 |
+
# to perform the calculation, and the final result needs to be negated.
|
| 474 |
+
if log and xp.any(negative):
|
| 475 |
+
dtype = res['integral'].dtype
|
| 476 |
+
pi = xp.asarray(xp.pi, dtype=dtype)[()]
|
| 477 |
+
j = xp.asarray(1j, dtype=xp.complex64)[()] # minimum complex type
|
| 478 |
+
res['integral'] = res['integral'] + negative*pi*j
|
| 479 |
+
else:
|
| 480 |
+
res['integral'][negative] *= -1
|
| 481 |
+
|
| 482 |
+
# For this algorithm, it seems more appropriate to report the maximum
|
| 483 |
+
# level rather than the number of iterations in which it was performed.
|
| 484 |
+
res['maxlevel'] = minlevel + res['nit'] - 1
|
| 485 |
+
res['maxlevel'][res['nit'] == 0] = -1
|
| 486 |
+
del res['nit']
|
| 487 |
+
return shape
|
| 488 |
+
|
| 489 |
+
# Suppress all warnings initially, since there are many places in the code
|
| 490 |
+
# for which this is expected behavior.
|
| 491 |
+
with np.errstate(over='ignore', invalid='ignore', divide='ignore'):
|
| 492 |
+
res = eim._loop(work, callback, shape, maxiter, f, args, dtype, pre_func_eval,
|
| 493 |
+
post_func_eval, check_termination, post_termination_check,
|
| 494 |
+
customize_result, res_work_pairs, xp, preserve_shape)
|
| 495 |
+
return res
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def _get_base_step(dtype, xp):
|
| 499 |
+
# Compute the base step length for the provided dtype. Theoretically, the
|
| 500 |
+
# Euler-Maclaurin sum is infinite, but it gets cut off when either the
|
| 501 |
+
# weights underflow or the abscissae cannot be distinguished from the
|
| 502 |
+
# limits of integration. The latter happens to occur first for float32 and
|
| 503 |
+
# float64, and it occurs when `xjc` (the abscissa complement)
|
| 504 |
+
# in `_compute_pair` underflows. We can solve for the argument `tmax` at
|
| 505 |
+
# which it will underflow using [2] Eq. 13.
|
| 506 |
+
fmin = 4*xp.finfo(dtype).smallest_normal # stay a little away from the limit
|
| 507 |
+
tmax = math.asinh(math.log(2/fmin - 1) / xp.pi)
|
| 508 |
+
|
| 509 |
+
# Based on this, we can choose a base step size `h` for level 0.
|
| 510 |
+
# The number of function evaluations will be `2 + m*2^(k+1)`, where `k` is
|
| 511 |
+
# the level and `m` is an integer we get to choose. I choose
|
| 512 |
+
# m = _N_BASE_STEPS = `8` somewhat arbitrarily, but a rationale is that a
|
| 513 |
+
# power of 2 makes floating point arithmetic more predictable. It also
|
| 514 |
+
# results in a base step size close to `1`, which is what [1] uses (and I
|
| 515 |
+
# used here until I found [2] and these ideas settled).
|
| 516 |
+
h0 = tmax / _N_BASE_STEPS
|
| 517 |
+
return xp.asarray(h0, dtype=dtype)[()]
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
_N_BASE_STEPS = 8
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def _compute_pair(k, h0, xp):
|
| 524 |
+
# Compute the abscissa-weight pairs for each level k. See [1] page 9.
|
| 525 |
+
|
| 526 |
+
# For now, we compute and store in 64-bit precision. If higher-precision
|
| 527 |
+
# data types become better supported, it would be good to compute these
|
| 528 |
+
# using the highest precision available. Or, once there is an Array API-
|
| 529 |
+
# compatible arbitrary precision array, we can compute at the required
|
| 530 |
+
# precision.
|
| 531 |
+
|
| 532 |
+
# "....each level k of abscissa-weight pairs uses h = 2 **-k"
|
| 533 |
+
# We adapt to floating point arithmetic using ideas of [2].
|
| 534 |
+
h = h0 / 2**k
|
| 535 |
+
max = _N_BASE_STEPS * 2**k
|
| 536 |
+
|
| 537 |
+
# For iterations after the first, "....the integrand function needs to be
|
| 538 |
+
# evaluated only at the odd-indexed abscissas at each level."
|
| 539 |
+
j = xp.arange(max+1) if k == 0 else xp.arange(1, max+1, 2)
|
| 540 |
+
jh = j * h
|
| 541 |
+
|
| 542 |
+
# "In this case... the weights wj = u1/cosh(u2)^2, where..."
|
| 543 |
+
pi_2 = xp.pi / 2
|
| 544 |
+
u1 = pi_2*xp.cosh(jh)
|
| 545 |
+
u2 = pi_2*xp.sinh(jh)
|
| 546 |
+
# Denominators get big here. Overflow then underflow doesn't need warning.
|
| 547 |
+
# with np.errstate(under='ignore', over='ignore'):
|
| 548 |
+
wj = u1 / xp.cosh(u2)**2
|
| 549 |
+
# "We actually store 1-xj = 1/(...)."
|
| 550 |
+
xjc = 1 / (xp.exp(u2) * xp.cosh(u2)) # complement of xj = xp.tanh(u2)
|
| 551 |
+
|
| 552 |
+
# When level k == 0, the zeroth xj corresponds with xj = 0. To simplify
|
| 553 |
+
# code, the function will be evaluated there twice; each gets half weight.
|
| 554 |
+
wj[0] = wj[0] / 2 if k == 0 else wj[0]
|
| 555 |
+
|
| 556 |
+
return xjc, wj # store at full precision
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _pair_cache(k, h0, xp, work):
|
| 560 |
+
# Cache the abscissa-weight pairs up to a specified level.
|
| 561 |
+
# Abscissae and weights of consecutive levels are concatenated.
|
| 562 |
+
# `index` records the indices that correspond with each level:
|
| 563 |
+
# `xjc[index[k]:index[k+1]` extracts the level `k` abscissae.
|
| 564 |
+
if not isinstance(h0, type(work.pair_cache.h0)) or h0 != work.pair_cache.h0:
|
| 565 |
+
work.pair_cache.xjc = xp.empty(0)
|
| 566 |
+
work.pair_cache.wj = xp.empty(0)
|
| 567 |
+
work.pair_cache.indices = [0]
|
| 568 |
+
|
| 569 |
+
xjcs = [work.pair_cache.xjc]
|
| 570 |
+
wjs = [work.pair_cache.wj]
|
| 571 |
+
|
| 572 |
+
for i in range(len(work.pair_cache.indices)-1, k + 1):
|
| 573 |
+
xjc, wj = _compute_pair(i, h0, xp)
|
| 574 |
+
xjcs.append(xjc)
|
| 575 |
+
wjs.append(wj)
|
| 576 |
+
work.pair_cache.indices.append(work.pair_cache.indices[-1] + xjc.shape[0])
|
| 577 |
+
|
| 578 |
+
work.pair_cache.xjc = xp.concat(xjcs)
|
| 579 |
+
work.pair_cache.wj = xp.concat(wjs)
|
| 580 |
+
work.pair_cache.h0 = h0
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _get_pairs(k, h0, inclusive, dtype, xp, work):
|
| 584 |
+
# Retrieve the specified abscissa-weight pairs from the cache
|
| 585 |
+
# If `inclusive`, return all up to and including the specified level
|
| 586 |
+
if (len(work.pair_cache.indices) <= k+2
|
| 587 |
+
or not isinstance (h0, type(work.pair_cache.h0))
|
| 588 |
+
or h0 != work.pair_cache.h0):
|
| 589 |
+
_pair_cache(k, h0, xp, work)
|
| 590 |
+
|
| 591 |
+
xjc = work.pair_cache.xjc
|
| 592 |
+
wj = work.pair_cache.wj
|
| 593 |
+
indices = work.pair_cache.indices
|
| 594 |
+
|
| 595 |
+
start = 0 if inclusive else indices[k]
|
| 596 |
+
end = indices[k+1]
|
| 597 |
+
|
| 598 |
+
return xp.astype(xjc[start:end], dtype), xp.astype(wj[start:end], dtype)
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
def _transform_to_limits(xjc, wj, a, b, xp):
|
| 602 |
+
# Transform integral according to user-specified limits. This is just
|
| 603 |
+
# math that follows from the fact that the standard limits are (-1, 1).
|
| 604 |
+
# Note: If we had stored xj instead of xjc, we would have
|
| 605 |
+
# xj = alpha * xj + beta, where beta = (a + b)/2
|
| 606 |
+
alpha = (b - a) / 2
|
| 607 |
+
xj = xp.concat((-alpha * xjc + b, alpha * xjc + a), axis=-1)
|
| 608 |
+
wj = wj*alpha # arguments get broadcasted, so we can't use *=
|
| 609 |
+
wj = xp.concat((wj, wj), axis=-1)
|
| 610 |
+
|
| 611 |
+
# Points at the boundaries can be generated due to finite precision
|
| 612 |
+
# arithmetic, but these function values aren't supposed to be included in
|
| 613 |
+
# the Euler-Maclaurin sum. Ideally we wouldn't evaluate the function at
|
| 614 |
+
# these points; however, we can't easily filter out points since this
|
| 615 |
+
# function is vectorized. Instead, zero the weights.
|
| 616 |
+
# Note: values may have complex dtype, but have zero imaginary part
|
| 617 |
+
xj_real, a_real, b_real = xp_real(xj), xp_real(a), xp_real(b)
|
| 618 |
+
invalid = (xj_real <= a_real) | (xj_real >= b_real)
|
| 619 |
+
wj[invalid] = 0
|
| 620 |
+
return xj, wj
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
def _euler_maclaurin_sum(fj, work, xp):
|
| 624 |
+
# Perform the Euler-Maclaurin Sum, [1] Section 4
|
| 625 |
+
|
| 626 |
+
# The error estimate needs to know the magnitude of the last term
|
| 627 |
+
# omitted from the Euler-Maclaurin sum. This is a bit involved because
|
| 628 |
+
# it may have been computed at a previous level. I sure hope it's worth
|
| 629 |
+
# all the trouble.
|
| 630 |
+
xr0, fr0, wr0 = work.xr0, work.fr0, work.wr0
|
| 631 |
+
xl0, fl0, wl0 = work.xl0, work.fl0, work.wl0
|
| 632 |
+
|
| 633 |
+
# It is much more convenient to work with the transposes of our work
|
| 634 |
+
# variables here.
|
| 635 |
+
xj, fj, wj = work.xj.T, fj.T, work.wj.T
|
| 636 |
+
n_x, n_active = xj.shape # number of abscissae, number of active elements
|
| 637 |
+
|
| 638 |
+
# We'll work with the left and right sides separately
|
| 639 |
+
xr, xl = xp_copy(xp.reshape(xj, (2, n_x // 2, n_active))) # this gets modified
|
| 640 |
+
fr, fl = xp.reshape(fj, (2, n_x // 2, n_active))
|
| 641 |
+
wr, wl = xp.reshape(wj, (2, n_x // 2, n_active))
|
| 642 |
+
|
| 643 |
+
invalid_r = ~xp.isfinite(fr) | (wr == 0)
|
| 644 |
+
invalid_l = ~xp.isfinite(fl) | (wl == 0)
|
| 645 |
+
|
| 646 |
+
# integer index of the maximum abscissa at this level
|
| 647 |
+
xr[invalid_r] = -xp.inf
|
| 648 |
+
ir = xp.argmax(xp_real(xr), axis=0, keepdims=True)
|
| 649 |
+
# abscissa, function value, and weight at this index
|
| 650 |
+
### Not Array API Compatible... yet ###
|
| 651 |
+
xr_max = xp_take_along_axis(xr, ir, axis=0)[0]
|
| 652 |
+
fr_max = xp_take_along_axis(fr, ir, axis=0)[0]
|
| 653 |
+
wr_max = xp_take_along_axis(wr, ir, axis=0)[0]
|
| 654 |
+
# boolean indices at which maximum abscissa at this level exceeds
|
| 655 |
+
# the incumbent maximum abscissa (from all previous levels)
|
| 656 |
+
# note: abscissa may have complex dtype, but will have zero imaginary part
|
| 657 |
+
j = xp_real(xr_max) > xp_real(xr0)
|
| 658 |
+
# Update record of the incumbent abscissa, function value, and weight
|
| 659 |
+
xr0[j] = xr_max[j]
|
| 660 |
+
fr0[j] = fr_max[j]
|
| 661 |
+
wr0[j] = wr_max[j]
|
| 662 |
+
|
| 663 |
+
# integer index of the minimum abscissa at this level
|
| 664 |
+
xl[invalid_l] = xp.inf
|
| 665 |
+
il = xp.argmin(xp_real(xl), axis=0, keepdims=True)
|
| 666 |
+
# abscissa, function value, and weight at this index
|
| 667 |
+
xl_min = xp_take_along_axis(xl, il, axis=0)[0]
|
| 668 |
+
fl_min = xp_take_along_axis(fl, il, axis=0)[0]
|
| 669 |
+
wl_min = xp_take_along_axis(wl, il, axis=0)[0]
|
| 670 |
+
# boolean indices at which minimum abscissa at this level is less than
|
| 671 |
+
# the incumbent minimum abscissa (from all previous levels)
|
| 672 |
+
# note: abscissa may have complex dtype, but will have zero imaginary part
|
| 673 |
+
j = xp_real(xl_min) < xp_real(xl0)
|
| 674 |
+
# Update record of the incumbent abscissa, function value, and weight
|
| 675 |
+
xl0[j] = xl_min[j]
|
| 676 |
+
fl0[j] = fl_min[j]
|
| 677 |
+
wl0[j] = wl_min[j]
|
| 678 |
+
fj = fj.T
|
| 679 |
+
|
| 680 |
+
# Compute the error estimate `d4` - the magnitude of the leftmost or
|
| 681 |
+
# rightmost term, whichever is greater.
|
| 682 |
+
flwl0 = fl0 + xp.log(wl0) if work.log else fl0 * wl0 # leftmost term
|
| 683 |
+
frwr0 = fr0 + xp.log(wr0) if work.log else fr0 * wr0 # rightmost term
|
| 684 |
+
magnitude = xp_real if work.log else xp.abs
|
| 685 |
+
work.d4 = xp.maximum(magnitude(flwl0), magnitude(frwr0))
|
| 686 |
+
|
| 687 |
+
# There are two approaches to dealing with function values that are
|
| 688 |
+
# numerically infinite due to approaching a singularity - zero them, or
|
| 689 |
+
# replace them with the function value at the nearest non-infinite point.
|
| 690 |
+
# [3] pg. 22 suggests the latter, so let's do that given that we have the
|
| 691 |
+
# information.
|
| 692 |
+
fr0b = xp.broadcast_to(fr0[xp.newaxis, :], fr.shape)
|
| 693 |
+
fl0b = xp.broadcast_to(fl0[xp.newaxis, :], fl.shape)
|
| 694 |
+
fr[invalid_r] = fr0b[invalid_r]
|
| 695 |
+
fl[invalid_l] = fl0b[invalid_l]
|
| 696 |
+
|
| 697 |
+
# When wj is zero, log emits a warning
|
| 698 |
+
# with np.errstate(divide='ignore'):
|
| 699 |
+
fjwj = fj + xp.log(work.wj) if work.log else fj * work.wj
|
| 700 |
+
|
| 701 |
+
# update integral estimate
|
| 702 |
+
Sn = (special.logsumexp(fjwj + xp.log(work.h), axis=-1) if work.log
|
| 703 |
+
else xp.sum(fjwj, axis=-1) * work.h)
|
| 704 |
+
|
| 705 |
+
work.xr0, work.fr0, work.wr0 = xr0, fr0, wr0
|
| 706 |
+
work.xl0, work.fl0, work.wl0 = xl0, fl0, wl0
|
| 707 |
+
|
| 708 |
+
return fjwj, Sn
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def _estimate_error(work, xp):
|
| 712 |
+
# Estimate the error according to [1] Section 5
|
| 713 |
+
|
| 714 |
+
if work.n == 0 or work.nit == 0:
|
| 715 |
+
# The paper says to use "one" as the error before it can be calculated.
|
| 716 |
+
# NaN seems to be more appropriate.
|
| 717 |
+
nan = xp.full_like(work.Sn, xp.nan)
|
| 718 |
+
return nan, nan
|
| 719 |
+
|
| 720 |
+
indices = work.pair_cache.indices
|
| 721 |
+
|
| 722 |
+
n_active = work.Sn.shape[0] # number of active elements
|
| 723 |
+
axis_kwargs = dict(axis=-1, keepdims=True)
|
| 724 |
+
|
| 725 |
+
# With a jump start (starting at level higher than 0), we haven't
|
| 726 |
+
# explicitly calculated the integral estimate at lower levels. But we have
|
| 727 |
+
# all the function value-weight products, so we can compute the
|
| 728 |
+
# lower-level estimates.
|
| 729 |
+
if work.Sk.shape[-1] == 0:
|
| 730 |
+
h = 2 * work.h # step size at this level
|
| 731 |
+
n_x = indices[work.n] # number of abscissa up to this level
|
| 732 |
+
# The right and left fjwj terms from all levels are concatenated along
|
| 733 |
+
# the last axis. Get out only the terms up to this level.
|
| 734 |
+
fjwj_rl = xp.reshape(work.fjwj, (n_active, 2, -1))
|
| 735 |
+
fjwj = xp.reshape(fjwj_rl[:, :, :n_x], (n_active, 2*n_x))
|
| 736 |
+
# Compute the Euler-Maclaurin sum at this level
|
| 737 |
+
Snm1 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
|
| 738 |
+
else xp.sum(fjwj, **axis_kwargs) * h)
|
| 739 |
+
work.Sk = xp.concat((Snm1, work.Sk), axis=-1)
|
| 740 |
+
|
| 741 |
+
if work.n == 1:
|
| 742 |
+
nan = xp.full_like(work.Sn, xp.nan)
|
| 743 |
+
return nan, nan
|
| 744 |
+
|
| 745 |
+
# The paper says not to calculate the error for n<=2, but it's not clear
|
| 746 |
+
# about whether it starts at level 0 or level 1. We start at level 0, so
|
| 747 |
+
# why not compute the error beginning in level 2?
|
| 748 |
+
if work.Sk.shape[-1] < 2:
|
| 749 |
+
h = 4 * work.h # step size at this level
|
| 750 |
+
n_x = indices[work.n-1] # number of abscissa up to this level
|
| 751 |
+
# The right and left fjwj terms from all levels are concatenated along
|
| 752 |
+
# the last axis. Get out only the terms up to this level.
|
| 753 |
+
fjwj_rl = xp.reshape(work.fjwj, (work.Sn.shape[0], 2, -1))
|
| 754 |
+
fjwj = xp.reshape(fjwj_rl[..., :n_x], (n_active, 2*n_x))
|
| 755 |
+
# Compute the Euler-Maclaurin sum at this level
|
| 756 |
+
Snm2 = (special.logsumexp(fjwj, **axis_kwargs) + xp.log(h) if work.log
|
| 757 |
+
else xp.sum(fjwj, **axis_kwargs) * h)
|
| 758 |
+
work.Sk = xp.concat((Snm2, work.Sk), axis=-1)
|
| 759 |
+
|
| 760 |
+
Snm2 = work.Sk[..., -2]
|
| 761 |
+
Snm1 = work.Sk[..., -1]
|
| 762 |
+
|
| 763 |
+
e1 = xp.asarray(work.eps)[()]
|
| 764 |
+
|
| 765 |
+
if work.log:
|
| 766 |
+
log_e1 = xp.log(e1)
|
| 767 |
+
# Currently, only real integrals are supported in log-scale. All
|
| 768 |
+
# complex values have imaginary part in increments of pi*j, which just
|
| 769 |
+
# carries sign information of the original integral, so use of
|
| 770 |
+
# `xp.real` here is equivalent to absolute value in real scale.
|
| 771 |
+
d1 = xp_real(special.logsumexp(xp.stack([work.Sn, Snm1 + work.pi*1j]), axis=0))
|
| 772 |
+
d2 = xp_real(special.logsumexp(xp.stack([work.Sn, Snm2 + work.pi*1j]), axis=0))
|
| 773 |
+
d3 = log_e1 + xp.max(xp_real(work.fjwj), axis=-1)
|
| 774 |
+
d4 = work.d4
|
| 775 |
+
ds = xp.stack([d1 ** 2 / d2, 2 * d1, d3, d4])
|
| 776 |
+
aerr = xp.max(ds, axis=0)
|
| 777 |
+
rerr = xp.maximum(log_e1, aerr - xp_real(work.Sn))
|
| 778 |
+
else:
|
| 779 |
+
# Note: explicit computation of log10 of each of these is unnecessary.
|
| 780 |
+
d1 = xp.abs(work.Sn - Snm1)
|
| 781 |
+
d2 = xp.abs(work.Sn - Snm2)
|
| 782 |
+
d3 = e1 * xp.max(xp.abs(work.fjwj), axis=-1)
|
| 783 |
+
d4 = work.d4
|
| 784 |
+
# If `d1` is 0, no need to warn. This does the right thing.
|
| 785 |
+
# with np.errstate(divide='ignore'):
|
| 786 |
+
ds = xp.stack([d1**(xp.log(d1)/xp.log(d2)), d1**2, d3, d4])
|
| 787 |
+
aerr = xp.max(ds, axis=0)
|
| 788 |
+
rerr = xp.maximum(e1, aerr/xp.abs(work.Sn))
|
| 789 |
+
|
| 790 |
+
aerr = xp.reshape(xp.astype(aerr, work.dtype), work.Sn.shape)
|
| 791 |
+
return rerr, aerr
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
def _transform_integrals(a, b, xp):
|
| 795 |
+
# Transform integrals to a form with finite a <= b
|
| 796 |
+
# For b == a (even infinite), we ensure that the limits remain equal
|
| 797 |
+
# For b < a, we reverse the limits and will multiply the final result by -1
|
| 798 |
+
# For infinite limit on the right, we use the substitution x = 1/t - 1 + a
|
| 799 |
+
# For infinite limit on the left, we substitute x = -x and treat as above
|
| 800 |
+
# For infinite limits, we substitute x = t / (1-t**2)
|
| 801 |
+
ab_same = (a == b)
|
| 802 |
+
a[ab_same], b[ab_same] = 1, 1
|
| 803 |
+
|
| 804 |
+
# `a, b` may have complex dtype but have zero imaginary part
|
| 805 |
+
negative = xp_real(b) < xp_real(a)
|
| 806 |
+
a[negative], b[negative] = b[negative], a[negative]
|
| 807 |
+
|
| 808 |
+
abinf = xp.isinf(a) & xp.isinf(b)
|
| 809 |
+
a[abinf], b[abinf] = -1, 1
|
| 810 |
+
|
| 811 |
+
ainf = xp.isinf(a)
|
| 812 |
+
a[ainf], b[ainf] = -b[ainf], -a[ainf]
|
| 813 |
+
|
| 814 |
+
binf = xp.isinf(b)
|
| 815 |
+
a0 = xp_copy(a)
|
| 816 |
+
a[binf], b[binf] = 0, 1
|
| 817 |
+
|
| 818 |
+
return a, b, a0, negative, abinf, ainf, binf
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def _tanhsinh_iv(f, a, b, log, maxfun, maxlevel, minlevel,
|
| 822 |
+
atol, rtol, args, preserve_shape, callback):
|
| 823 |
+
# Input validation and standardization
|
| 824 |
+
|
| 825 |
+
xp = array_namespace(a, b)
|
| 826 |
+
|
| 827 |
+
message = '`f` must be callable.'
|
| 828 |
+
if not callable(f):
|
| 829 |
+
raise ValueError(message)
|
| 830 |
+
|
| 831 |
+
message = 'All elements of `a` and `b` must be real numbers.'
|
| 832 |
+
a, b = xp.asarray(a), xp.asarray(b)
|
| 833 |
+
a, b = xp.broadcast_arrays(a, b)
|
| 834 |
+
if (xp.isdtype(a.dtype, 'complex floating')
|
| 835 |
+
or xp.isdtype(b.dtype, 'complex floating')):
|
| 836 |
+
raise ValueError(message)
|
| 837 |
+
|
| 838 |
+
message = '`log` must be True or False.'
|
| 839 |
+
if log not in {True, False}:
|
| 840 |
+
raise ValueError(message)
|
| 841 |
+
log = bool(log)
|
| 842 |
+
|
| 843 |
+
if atol is None:
|
| 844 |
+
atol = -xp.inf if log else 0
|
| 845 |
+
|
| 846 |
+
rtol_temp = rtol if rtol is not None else 0.
|
| 847 |
+
|
| 848 |
+
# using NumPy for convenience here; these are just floats, not arrays
|
| 849 |
+
params = np.asarray([atol, rtol_temp, 0.])
|
| 850 |
+
message = "`atol` and `rtol` must be real numbers."
|
| 851 |
+
if not np.issubdtype(params.dtype, np.floating):
|
| 852 |
+
raise ValueError(message)
|
| 853 |
+
|
| 854 |
+
if log:
|
| 855 |
+
message = '`atol` and `rtol` may not be positive infinity.'
|
| 856 |
+
if np.any(np.isposinf(params)):
|
| 857 |
+
raise ValueError(message)
|
| 858 |
+
else:
|
| 859 |
+
message = '`atol` and `rtol` must be non-negative and finite.'
|
| 860 |
+
if np.any(params < 0) or np.any(np.isinf(params)):
|
| 861 |
+
raise ValueError(message)
|
| 862 |
+
atol = params[0]
|
| 863 |
+
rtol = rtol if rtol is None else params[1]
|
| 864 |
+
|
| 865 |
+
BIGINT = float(2**62)
|
| 866 |
+
if maxfun is None and maxlevel is None:
|
| 867 |
+
maxlevel = 10
|
| 868 |
+
|
| 869 |
+
maxfun = BIGINT if maxfun is None else maxfun
|
| 870 |
+
maxlevel = BIGINT if maxlevel is None else maxlevel
|
| 871 |
+
|
| 872 |
+
message = '`maxfun`, `maxlevel`, and `minlevel` must be integers.'
|
| 873 |
+
params = np.asarray([maxfun, maxlevel, minlevel])
|
| 874 |
+
if not (np.issubdtype(params.dtype, np.number)
|
| 875 |
+
and np.all(np.isreal(params))
|
| 876 |
+
and np.all(params.astype(np.int64) == params)):
|
| 877 |
+
raise ValueError(message)
|
| 878 |
+
message = '`maxfun`, `maxlevel`, and `minlevel` must be non-negative.'
|
| 879 |
+
if np.any(params < 0):
|
| 880 |
+
raise ValueError(message)
|
| 881 |
+
maxfun, maxlevel, minlevel = params.astype(np.int64)
|
| 882 |
+
minlevel = min(minlevel, maxlevel)
|
| 883 |
+
|
| 884 |
+
if not np.iterable(args):
|
| 885 |
+
args = (args,)
|
| 886 |
+
args = (xp.asarray(arg) for arg in args)
|
| 887 |
+
|
| 888 |
+
message = '`preserve_shape` must be True or False.'
|
| 889 |
+
if preserve_shape not in {True, False}:
|
| 890 |
+
raise ValueError(message)
|
| 891 |
+
|
| 892 |
+
if callback is not None and not callable(callback):
|
| 893 |
+
raise ValueError('`callback` must be callable.')
|
| 894 |
+
|
| 895 |
+
return (f, a, b, log, maxfun, maxlevel, minlevel,
|
| 896 |
+
atol, rtol, args, preserve_shape, callback, xp)
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def _nsum_iv(f, a, b, step, args, log, maxterms, tolerances):
|
| 900 |
+
# Input validation and standardization
|
| 901 |
+
|
| 902 |
+
xp = array_namespace(a, b)
|
| 903 |
+
|
| 904 |
+
message = '`f` must be callable.'
|
| 905 |
+
if not callable(f):
|
| 906 |
+
raise ValueError(message)
|
| 907 |
+
|
| 908 |
+
message = 'All elements of `a`, `b`, and `step` must be real numbers.'
|
| 909 |
+
a, b, step = xp.broadcast_arrays(xp.asarray(a), xp.asarray(b), xp.asarray(step))
|
| 910 |
+
dtype = xp.result_type(a.dtype, b.dtype, step.dtype)
|
| 911 |
+
if not xp.isdtype(dtype, 'numeric') or xp.isdtype(dtype, 'complex floating'):
|
| 912 |
+
raise ValueError(message)
|
| 913 |
+
|
| 914 |
+
valid_b = b >= a # NaNs will be False
|
| 915 |
+
valid_step = xp.isfinite(step) & (step > 0)
|
| 916 |
+
valid_abstep = valid_b & valid_step
|
| 917 |
+
|
| 918 |
+
message = '`log` must be True or False.'
|
| 919 |
+
if log not in {True, False}:
|
| 920 |
+
raise ValueError(message)
|
| 921 |
+
|
| 922 |
+
tolerances = {} if tolerances is None else tolerances
|
| 923 |
+
|
| 924 |
+
atol = tolerances.get('atol', None)
|
| 925 |
+
if atol is None:
|
| 926 |
+
atol = -xp.inf if log else 0
|
| 927 |
+
|
| 928 |
+
rtol = tolerances.get('rtol', None)
|
| 929 |
+
rtol_temp = rtol if rtol is not None else 0.
|
| 930 |
+
|
| 931 |
+
# using NumPy for convenience here; these are just floats, not arrays
|
| 932 |
+
params = np.asarray([atol, rtol_temp, 0.])
|
| 933 |
+
message = "`atol` and `rtol` must be real numbers."
|
| 934 |
+
if not np.issubdtype(params.dtype, np.floating):
|
| 935 |
+
raise ValueError(message)
|
| 936 |
+
|
| 937 |
+
if log:
|
| 938 |
+
message = '`atol`, `rtol` may not be positive infinity or NaN.'
|
| 939 |
+
if np.any(np.isposinf(params) | np.isnan(params)):
|
| 940 |
+
raise ValueError(message)
|
| 941 |
+
else:
|
| 942 |
+
message = '`atol`, and `rtol` must be non-negative and finite.'
|
| 943 |
+
if np.any((params < 0) | (~np.isfinite(params))):
|
| 944 |
+
raise ValueError(message)
|
| 945 |
+
atol = params[0]
|
| 946 |
+
rtol = rtol if rtol is None else params[1]
|
| 947 |
+
|
| 948 |
+
maxterms_int = int(maxterms)
|
| 949 |
+
if maxterms_int != maxterms or maxterms < 0:
|
| 950 |
+
message = "`maxterms` must be a non-negative integer."
|
| 951 |
+
raise ValueError(message)
|
| 952 |
+
|
| 953 |
+
if not np.iterable(args):
|
| 954 |
+
args = (args,)
|
| 955 |
+
|
| 956 |
+
return f, a, b, step, valid_abstep, args, log, maxterms_int, atol, rtol, xp
|
| 957 |
+
|
| 958 |
+
|
| 959 |
+
def nsum(f, a, b, *, step=1, args=(), log=False, maxterms=int(2**20), tolerances=None):
|
| 960 |
+
r"""Evaluate a convergent finite or infinite series.
|
| 961 |
+
|
| 962 |
+
For finite `a` and `b`, this evaluates::
|
| 963 |
+
|
| 964 |
+
f(a + np.arange(n)*step).sum()
|
| 965 |
+
|
| 966 |
+
where ``n = int((b - a) / step) + 1``, where `f` is smooth, positive, and
|
| 967 |
+
unimodal. The number of terms in the sum may be very large or infinite,
|
| 968 |
+
in which case a partial sum is evaluated directly and the remainder is
|
| 969 |
+
approximated using integration.
|
| 970 |
+
|
| 971 |
+
Parameters
|
| 972 |
+
----------
|
| 973 |
+
f : callable
|
| 974 |
+
The function that evaluates terms to be summed. The signature must be::
|
| 975 |
+
|
| 976 |
+
f(x: ndarray, *args) -> ndarray
|
| 977 |
+
|
| 978 |
+
where each element of ``x`` is a finite real and ``args`` is a tuple,
|
| 979 |
+
which may contain an arbitrary number of arrays that are broadcastable
|
| 980 |
+
with ``x``.
|
| 981 |
+
|
| 982 |
+
`f` must be an elementwise function: each element ``f(x)[i]``
|
| 983 |
+
must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
|
| 984 |
+
array ``x`` or the arrays in ``args``, and it must return NaN where
|
| 985 |
+
the argument is NaN.
|
| 986 |
+
|
| 987 |
+
`f` must represent a smooth, positive, unimodal function of `x` defined at
|
| 988 |
+
*all reals* between `a` and `b`.
|
| 989 |
+
a, b : float array_like
|
| 990 |
+
Real lower and upper limits of summed terms. Must be broadcastable.
|
| 991 |
+
Each element of `a` must be less than the corresponding element in `b`.
|
| 992 |
+
step : float array_like
|
| 993 |
+
Finite, positive, real step between summed terms. Must be broadcastable
|
| 994 |
+
with `a` and `b`. Note that the number of terms included in the sum will
|
| 995 |
+
be ``floor((b - a) / step)`` + 1; adjust `b` accordingly to ensure
|
| 996 |
+
that ``f(b)`` is included if intended.
|
| 997 |
+
args : tuple of array_like, optional
|
| 998 |
+
Additional positional arguments to be passed to `f`. Must be arrays
|
| 999 |
+
broadcastable with `a`, `b`, and `step`. If the callable to be summed
|
| 1000 |
+
requires arguments that are not broadcastable with `a`, `b`, and `step`,
|
| 1001 |
+
wrap that callable with `f` such that `f` accepts only `x` and
|
| 1002 |
+
broadcastable ``*args``. See Examples.
|
| 1003 |
+
log : bool, default: False
|
| 1004 |
+
Setting to True indicates that `f` returns the log of the terms
|
| 1005 |
+
and that `atol` and `rtol` are expressed as the logs of the absolute
|
| 1006 |
+
and relative errors. In this case, the result object will contain the
|
| 1007 |
+
log of the sum and error. This is useful for summands for which
|
| 1008 |
+
numerical underflow or overflow would lead to inaccuracies.
|
| 1009 |
+
maxterms : int, default: 2**20
|
| 1010 |
+
The maximum number of terms to evaluate for direct summation.
|
| 1011 |
+
Additional function evaluations may be performed for input
|
| 1012 |
+
validation and integral evaluation.
|
| 1013 |
+
atol, rtol : float, optional
|
| 1014 |
+
Absolute termination tolerance (default: 0) and relative termination
|
| 1015 |
+
tolerance (default: ``eps**0.5``, where ``eps`` is the precision of
|
| 1016 |
+
the result dtype), respectively. Must be non-negative
|
| 1017 |
+
and finite if `log` is False, and must be expressed as the log of a
|
| 1018 |
+
non-negative and finite number if `log` is True.
|
| 1019 |
+
|
| 1020 |
+
Returns
|
| 1021 |
+
-------
|
| 1022 |
+
res : _RichResult
|
| 1023 |
+
An object similar to an instance of `scipy.optimize.OptimizeResult` with the
|
| 1024 |
+
following attributes. (The descriptions are written as though the values will
|
| 1025 |
+
be scalars; however, if `f` returns an array, the outputs will be
|
| 1026 |
+
arrays of the same shape.)
|
| 1027 |
+
|
| 1028 |
+
success : bool
|
| 1029 |
+
``True`` when the algorithm terminated successfully (status ``0``);
|
| 1030 |
+
``False`` otherwise.
|
| 1031 |
+
status : int array
|
| 1032 |
+
An integer representing the exit status of the algorithm.
|
| 1033 |
+
|
| 1034 |
+
- ``0`` : The algorithm converged to the specified tolerances.
|
| 1035 |
+
- ``-1`` : Element(s) of `a`, `b`, or `step` are invalid
|
| 1036 |
+
- ``-2`` : Numerical integration reached its iteration limit;
|
| 1037 |
+
the sum may be divergent.
|
| 1038 |
+
- ``-3`` : A non-finite value was encountered.
|
| 1039 |
+
- ``-4`` : The magnitude of the last term of the partial sum exceeds
|
| 1040 |
+
the tolerances, so the error estimate exceeds the tolerances.
|
| 1041 |
+
Consider increasing `maxterms` or loosening `tolerances`.
|
| 1042 |
+
Alternatively, the callable may not be unimodal, or the limits of
|
| 1043 |
+
summation may be too far from the function maximum. Consider
|
| 1044 |
+
increasing `maxterms` or breaking the sum into pieces.
|
| 1045 |
+
|
| 1046 |
+
sum : float array
|
| 1047 |
+
An estimate of the sum.
|
| 1048 |
+
error : float array
|
| 1049 |
+
An estimate of the absolute error, assuming all terms are non-negative,
|
| 1050 |
+
the function is computed exactly, and direct summation is accurate to
|
| 1051 |
+
the precision of the result dtype.
|
| 1052 |
+
nfev : int array
|
| 1053 |
+
The number of points at which `f` was evaluated.
|
| 1054 |
+
|
| 1055 |
+
See Also
|
| 1056 |
+
--------
|
| 1057 |
+
mpmath.nsum
|
| 1058 |
+
|
| 1059 |
+
Notes
|
| 1060 |
+
-----
|
| 1061 |
+
The method implemented for infinite summation is related to the integral
|
| 1062 |
+
test for convergence of an infinite series: assuming `step` size 1 for
|
| 1063 |
+
simplicity of exposition, the sum of a monotone decreasing function is bounded by
|
| 1064 |
+
|
| 1065 |
+
.. math::
|
| 1066 |
+
|
| 1067 |
+
\int_u^\infty f(x) dx \leq \sum_{k=u}^\infty f(k) \leq \int_u^\infty f(x) dx + f(u)
|
| 1068 |
+
|
| 1069 |
+
Let :math:`a` represent `a`, :math:`n` represent `maxterms`, :math:`\epsilon_a`
|
| 1070 |
+
represent `atol`, and :math:`\epsilon_r` represent `rtol`.
|
| 1071 |
+
The implementation first evaluates the integral :math:`S_l=\int_a^\infty f(x) dx`
|
| 1072 |
+
as a lower bound of the infinite sum. Then, it seeks a value :math:`c > a` such
|
| 1073 |
+
that :math:`f(c) < \epsilon_a + S_l \epsilon_r`, if it exists; otherwise,
|
| 1074 |
+
let :math:`c = a + n`. Then the infinite sum is approximated as
|
| 1075 |
+
|
| 1076 |
+
.. math::
|
| 1077 |
+
|
| 1078 |
+
\sum_{k=a}^{c-1} f(k) + \int_c^\infty f(x) dx + f(c)/2
|
| 1079 |
+
|
| 1080 |
+
and the reported error is :math:`f(c)/2` plus the error estimate of
|
| 1081 |
+
numerical integration. Note that the integral approximations may require
|
| 1082 |
+
evaluation of the function at points besides those that appear in the sum,
|
| 1083 |
+
so `f` must be a continuous and monotonically decreasing function defined
|
| 1084 |
+
for all reals within the integration interval. However, due to the nature
|
| 1085 |
+
of the integral approximation, the shape of the function between points
|
| 1086 |
+
that appear in the sum has little effect. If there is not a natural
|
| 1087 |
+
extension of the function to all reals, consider using linear interpolation,
|
| 1088 |
+
which is easy to evaluate and preserves monotonicity.
|
| 1089 |
+
|
| 1090 |
+
The approach described above is generalized for non-unit
|
| 1091 |
+
`step` and finite `b` that is too large for direct evaluation of the sum,
|
| 1092 |
+
i.e. ``b - a + 1 > maxterms``. It is further generalized to unimodal
|
| 1093 |
+
functions by directly summing terms surrounding the maximum.
|
| 1094 |
+
This strategy may fail:
|
| 1095 |
+
|
| 1096 |
+
- If the left limit is finite and the maximum is far from it.
|
| 1097 |
+
- If the right limit is finite and the maximum is far from it.
|
| 1098 |
+
- If both limits are finite and the maximum is far from the origin.
|
| 1099 |
+
|
| 1100 |
+
In these cases, accuracy may be poor, and `nsum` may return status code ``4``.
|
| 1101 |
+
|
| 1102 |
+
Although the callable `f` must be non-negative and unimodal,
|
| 1103 |
+
`nsum` can be used to evaluate more general forms of series. For instance, to
|
| 1104 |
+
evaluate an alternating series, pass a callable that returns the difference
|
| 1105 |
+
between pairs of adjacent terms, and adjust `step` accordingly. See Examples.
|
| 1106 |
+
|
| 1107 |
+
References
|
| 1108 |
+
----------
|
| 1109 |
+
.. [1] Wikipedia. "Integral test for convergence."
|
| 1110 |
+
https://en.wikipedia.org/wiki/Integral_test_for_convergence
|
| 1111 |
+
|
| 1112 |
+
Examples
|
| 1113 |
+
--------
|
| 1114 |
+
Compute the infinite sum of the reciprocals of squared integers.
|
| 1115 |
+
|
| 1116 |
+
>>> import numpy as np
|
| 1117 |
+
>>> from scipy.integrate import nsum
|
| 1118 |
+
>>> res = nsum(lambda k: 1/k**2, 1, np.inf)
|
| 1119 |
+
>>> ref = np.pi**2/6 # true value
|
| 1120 |
+
>>> res.error # estimated error
|
| 1121 |
+
np.float64(7.448762306416137e-09)
|
| 1122 |
+
>>> (res.sum - ref)/ref # true error
|
| 1123 |
+
np.float64(-1.839871898894426e-13)
|
| 1124 |
+
>>> res.nfev # number of points at which callable was evaluated
|
| 1125 |
+
np.int32(8561)
|
| 1126 |
+
|
| 1127 |
+
Compute the infinite sums of the reciprocals of integers raised to powers ``p``,
|
| 1128 |
+
where ``p`` is an array.
|
| 1129 |
+
|
| 1130 |
+
>>> from scipy import special
|
| 1131 |
+
>>> p = np.arange(3, 10)
|
| 1132 |
+
>>> res = nsum(lambda k, p: 1/k**p, 1, np.inf, maxterms=1e3, args=(p,))
|
| 1133 |
+
>>> ref = special.zeta(p, 1)
|
| 1134 |
+
>>> np.allclose(res.sum, ref)
|
| 1135 |
+
True
|
| 1136 |
+
|
| 1137 |
+
Evaluate the alternating harmonic series.
|
| 1138 |
+
|
| 1139 |
+
>>> res = nsum(lambda x: 1/x - 1/(x+1), 1, np.inf, step=2)
|
| 1140 |
+
>>> res.sum, res.sum - np.log(2) # result, difference vs analytical sum
|
| 1141 |
+
(np.float64(0.6931471805598691), np.float64(-7.616129948928574e-14))
|
| 1142 |
+
|
| 1143 |
+
""" # noqa: E501
|
| 1144 |
+
# Potential future work:
|
| 1145 |
+
# - improve error estimate of `_direct` sum
|
| 1146 |
+
# - add other methods for convergence acceleration (Richardson, epsilon)
|
| 1147 |
+
# - support negative monotone increasing functions?
|
| 1148 |
+
# - b < a / negative step?
|
| 1149 |
+
# - complex-valued function?
|
| 1150 |
+
# - check for violations of monotonicity?
|
| 1151 |
+
|
| 1152 |
+
# Function-specific input validation / standardization
|
| 1153 |
+
tmp = _nsum_iv(f, a, b, step, args, log, maxterms, tolerances)
|
| 1154 |
+
f, a, b, step, valid_abstep, args, log, maxterms, atol, rtol, xp = tmp
|
| 1155 |
+
|
| 1156 |
+
# Additional elementwise algorithm input validation / standardization
|
| 1157 |
+
tmp = eim._initialize(f, (a,), args, complex_ok=False, xp=xp)
|
| 1158 |
+
f, xs, fs, args, shape, dtype, xp = tmp
|
| 1159 |
+
|
| 1160 |
+
# Finish preparing `a`, `b`, and `step` arrays
|
| 1161 |
+
a = xs[0]
|
| 1162 |
+
b = xp.astype(xp_ravel(xp.broadcast_to(b, shape)), dtype)
|
| 1163 |
+
step = xp.astype(xp_ravel(xp.broadcast_to(step, shape)), dtype)
|
| 1164 |
+
valid_abstep = xp_ravel(xp.broadcast_to(valid_abstep, shape))
|
| 1165 |
+
nterms = xp.floor((b - a) / step)
|
| 1166 |
+
finite_terms = xp.isfinite(nterms)
|
| 1167 |
+
b[finite_terms] = a[finite_terms] + nterms[finite_terms]*step[finite_terms]
|
| 1168 |
+
|
| 1169 |
+
# Define constants
|
| 1170 |
+
eps = xp.finfo(dtype).eps
|
| 1171 |
+
zero = xp.asarray(-xp.inf if log else 0, dtype=dtype)[()]
|
| 1172 |
+
if rtol is None:
|
| 1173 |
+
rtol = 0.5*math.log(eps) if log else eps**0.5
|
| 1174 |
+
constants = (dtype, log, eps, zero, rtol, atol, maxterms)
|
| 1175 |
+
|
| 1176 |
+
# Prepare result arrays
|
| 1177 |
+
S = xp.empty_like(a)
|
| 1178 |
+
E = xp.empty_like(a)
|
| 1179 |
+
status = xp.zeros(len(a), dtype=xp.int32)
|
| 1180 |
+
nfev = xp.ones(len(a), dtype=xp.int32) # one function evaluation above
|
| 1181 |
+
|
| 1182 |
+
# Branch for direct sum evaluation / integral approximation / invalid input
|
| 1183 |
+
i0 = ~valid_abstep # invalid
|
| 1184 |
+
i1 = (nterms + 1 <= maxterms) & ~i0 # direct sum evaluation
|
| 1185 |
+
i2 = xp.isfinite(a) & ~i1 & ~i0 # infinite sum to the right
|
| 1186 |
+
i3 = xp.isfinite(b) & ~i2 & ~i1 & ~i0 # infinite sum to the left
|
| 1187 |
+
i4 = ~i3 & ~i2 & ~i1 & ~i0 # infinite sum on both sides
|
| 1188 |
+
|
| 1189 |
+
if xp.any(i0):
|
| 1190 |
+
S[i0], E[i0] = xp.nan, xp.nan
|
| 1191 |
+
status[i0] = -1
|
| 1192 |
+
|
| 1193 |
+
if xp.any(i1):
|
| 1194 |
+
args_direct = [arg[i1] for arg in args]
|
| 1195 |
+
tmp = _direct(f, a[i1], b[i1], step[i1], args_direct, constants, xp)
|
| 1196 |
+
S[i1], E[i1] = tmp[:-1]
|
| 1197 |
+
nfev[i1] += tmp[-1]
|
| 1198 |
+
status[i1] = -3 * xp.asarray(~xp.isfinite(S[i1]), dtype=xp.int32)
|
| 1199 |
+
|
| 1200 |
+
if xp.any(i2):
|
| 1201 |
+
args_indirect = [arg[i2] for arg in args]
|
| 1202 |
+
tmp = _integral_bound(f, a[i2], b[i2], step[i2],
|
| 1203 |
+
args_indirect, constants, xp)
|
| 1204 |
+
S[i2], E[i2], status[i2] = tmp[:-1]
|
| 1205 |
+
nfev[i2] += tmp[-1]
|
| 1206 |
+
|
| 1207 |
+
if xp.any(i3):
|
| 1208 |
+
args_indirect = [arg[i3] for arg in args]
|
| 1209 |
+
def _f(x, *args): return f(-x, *args)
|
| 1210 |
+
tmp = _integral_bound(_f, -b[i3], -a[i3], step[i3],
|
| 1211 |
+
args_indirect, constants, xp)
|
| 1212 |
+
S[i3], E[i3], status[i3] = tmp[:-1]
|
| 1213 |
+
nfev[i3] += tmp[-1]
|
| 1214 |
+
|
| 1215 |
+
if xp.any(i4):
|
| 1216 |
+
args_indirect = [arg[i4] for arg in args]
|
| 1217 |
+
|
| 1218 |
+
# There are two obvious high-level strategies:
|
| 1219 |
+
# - Do two separate half-infinite sums (e.g. from -inf to 0 and 1 to inf)
|
| 1220 |
+
# - Make a callable that returns f(x) + f(-x) and do a single half-infinite sum
|
| 1221 |
+
# I thought the latter would have about half the overhead, so I went that way.
|
| 1222 |
+
# Then there are two ways of ensuring that f(0) doesn't get counted twice.
|
| 1223 |
+
# - Evaluate the sum from 1 to inf and add f(0)
|
| 1224 |
+
# - Evaluate the sum from 0 to inf and subtract f(0)
|
| 1225 |
+
# - Evaluate the sum from 0 to inf, but apply a weight of 0.5 when `x = 0`
|
| 1226 |
+
# The last option has more overhead, but is simpler to implement correctly
|
| 1227 |
+
# (especially getting the status message right)
|
| 1228 |
+
if log:
|
| 1229 |
+
def _f(x, *args):
|
| 1230 |
+
log_factor = xp.where(x==0, math.log(0.5), 0)
|
| 1231 |
+
out = xp.stack([f(x, *args), f(-x, *args)], axis=0)
|
| 1232 |
+
return special.logsumexp(out, axis=0) + log_factor
|
| 1233 |
+
|
| 1234 |
+
else:
|
| 1235 |
+
def _f(x, *args):
|
| 1236 |
+
factor = xp.where(x==0, 0.5, 1)
|
| 1237 |
+
return (f(x, *args) + f(-x, *args)) * factor
|
| 1238 |
+
|
| 1239 |
+
zero = xp.zeros_like(a[i4])
|
| 1240 |
+
tmp = _integral_bound(_f, zero, b[i4], step[i4], args_indirect, constants, xp)
|
| 1241 |
+
S[i4], E[i4], status[i4] = tmp[:-1]
|
| 1242 |
+
nfev[i4] += 2*tmp[-1]
|
| 1243 |
+
|
| 1244 |
+
# Return results
|
| 1245 |
+
S, E = S.reshape(shape)[()], E.reshape(shape)[()]
|
| 1246 |
+
status, nfev = status.reshape(shape)[()], nfev.reshape(shape)[()]
|
| 1247 |
+
return _RichResult(sum=S, error=E, status=status, success=status == 0,
|
| 1248 |
+
nfev=nfev)
|
| 1249 |
+
|
| 1250 |
+
|
| 1251 |
+
def _direct(f, a, b, step, args, constants, xp, inclusive=True):
|
| 1252 |
+
# Directly evaluate the sum.
|
| 1253 |
+
|
| 1254 |
+
# When used in the context of distributions, `args` would contain the
|
| 1255 |
+
# distribution parameters. We have broadcasted for simplicity, but we could
|
| 1256 |
+
# reduce function evaluations when distribution parameters are the same but
|
| 1257 |
+
# sum limits differ. Roughly:
|
| 1258 |
+
# - compute the function at all points between min(a) and max(b),
|
| 1259 |
+
# - compute the cumulative sum,
|
| 1260 |
+
# - take the difference between elements of the cumulative sum
|
| 1261 |
+
# corresponding with b and a.
|
| 1262 |
+
# This is left to future enhancement
|
| 1263 |
+
|
| 1264 |
+
dtype, log, eps, zero, _, _, _ = constants
|
| 1265 |
+
|
| 1266 |
+
# To allow computation in a single vectorized call, find the maximum number
|
| 1267 |
+
# of points (over all slices) at which the function needs to be evaluated.
|
| 1268 |
+
# Note: if `inclusive` is `True`, then we want `1` more term in the sum.
|
| 1269 |
+
# I didn't think it was great style to use `True` as `1` in Python, so I
|
| 1270 |
+
# explicitly converted it to an `int` before using it.
|
| 1271 |
+
inclusive_adjustment = int(inclusive)
|
| 1272 |
+
steps = xp.round((b - a) / step) + inclusive_adjustment
|
| 1273 |
+
# Equivalently, steps = xp.round((b - a) / step) + inclusive
|
| 1274 |
+
max_steps = int(xp.max(steps))
|
| 1275 |
+
|
| 1276 |
+
# In each slice, the function will be evaluated at the same number of points,
|
| 1277 |
+
# but excessive points (those beyond the right sum limit `b`) are replaced
|
| 1278 |
+
# with NaN to (potentially) reduce the time of these unnecessary calculations.
|
| 1279 |
+
# Use a new last axis for these calculations for consistency with other
|
| 1280 |
+
# elementwise algorithms.
|
| 1281 |
+
a2, b2, step2 = a[:, xp.newaxis], b[:, xp.newaxis], step[:, xp.newaxis]
|
| 1282 |
+
args2 = [arg[:, xp.newaxis] for arg in args]
|
| 1283 |
+
ks = a2 + xp.arange(max_steps, dtype=dtype) * step2
|
| 1284 |
+
i_nan = ks >= (b2 + inclusive_adjustment*step2/2)
|
| 1285 |
+
ks[i_nan] = xp.nan
|
| 1286 |
+
fs = f(ks, *args2)
|
| 1287 |
+
|
| 1288 |
+
# The function evaluated at NaN is NaN, and NaNs are zeroed in the sum.
|
| 1289 |
+
# In some cases it may be faster to loop over slices than to vectorize
|
| 1290 |
+
# like this. This is an optimization that can be added later.
|
| 1291 |
+
fs[i_nan] = zero
|
| 1292 |
+
nfev = max_steps - i_nan.sum(axis=-1)
|
| 1293 |
+
S = special.logsumexp(fs, axis=-1) if log else xp.sum(fs, axis=-1)
|
| 1294 |
+
# Rough, non-conservative error estimate. See gh-19667 for improvement ideas.
|
| 1295 |
+
E = xp_real(S) + math.log(eps) if log else eps * abs(S)
|
| 1296 |
+
return S, E, nfev
|
| 1297 |
+
|
| 1298 |
+
|
| 1299 |
+
def _integral_bound(f, a, b, step, args, constants, xp):
|
| 1300 |
+
# Estimate the sum with integral approximation
|
| 1301 |
+
dtype, log, _, _, rtol, atol, maxterms = constants
|
| 1302 |
+
log2 = xp.asarray(math.log(2), dtype=dtype)
|
| 1303 |
+
|
| 1304 |
+
# Get a lower bound on the sum and compute effective absolute tolerance
|
| 1305 |
+
lb = tanhsinh(f, a, b, args=args, atol=atol, rtol=rtol, log=log)
|
| 1306 |
+
tol = xp.broadcast_to(xp.asarray(atol), lb.integral.shape)
|
| 1307 |
+
if log:
|
| 1308 |
+
tol = special.logsumexp(xp.stack((tol, rtol + lb.integral)), axis=0)
|
| 1309 |
+
else:
|
| 1310 |
+
tol = tol + rtol*lb.integral
|
| 1311 |
+
i_skip = lb.status < 0 # avoid unnecessary f_evals if integral is divergent
|
| 1312 |
+
tol[i_skip] = xp.nan
|
| 1313 |
+
status = lb.status
|
| 1314 |
+
|
| 1315 |
+
# As in `_direct`, we'll need a temporary new axis for points
|
| 1316 |
+
# at which to evaluate the function. Append axis at the end for
|
| 1317 |
+
# consistency with other elementwise algorithms.
|
| 1318 |
+
a2 = a[..., xp.newaxis]
|
| 1319 |
+
step2 = step[..., xp.newaxis]
|
| 1320 |
+
args2 = [arg[..., xp.newaxis] for arg in args]
|
| 1321 |
+
|
| 1322 |
+
# Find the location of a term that is less than the tolerance (if possible)
|
| 1323 |
+
log2maxterms = math.floor(math.log2(maxterms)) if maxterms else 0
|
| 1324 |
+
n_steps = xp.concat((2**xp.arange(0, log2maxterms), xp.asarray([maxterms])))
|
| 1325 |
+
n_steps = xp.astype(n_steps, dtype)
|
| 1326 |
+
nfev = len(n_steps) * 2
|
| 1327 |
+
ks = a2 + n_steps * step2
|
| 1328 |
+
fks = f(ks, *args2)
|
| 1329 |
+
fksp1 = f(ks + step2, *args2) # check that the function is decreasing
|
| 1330 |
+
fk_insufficient = (fks > tol[:, xp.newaxis]) | (fksp1 > fks)
|
| 1331 |
+
n_fk_insufficient = xp.sum(fk_insufficient, axis=-1)
|
| 1332 |
+
nt = xp.minimum(n_fk_insufficient, xp.asarray(n_steps.shape[-1]-1))
|
| 1333 |
+
n_steps = n_steps[nt]
|
| 1334 |
+
|
| 1335 |
+
# If `maxterms` is insufficient (i.e. either the magnitude of the last term of the
|
| 1336 |
+
# partial sum exceeds the tolerance or the function is not decreasing), finish the
|
| 1337 |
+
# calculation, but report nonzero status. (Improvement: separate the status codes
|
| 1338 |
+
# for these two cases.)
|
| 1339 |
+
i_fk_insufficient = (n_fk_insufficient == nfev//2)
|
| 1340 |
+
|
| 1341 |
+
# Directly evaluate the sum up to this term
|
| 1342 |
+
k = a + n_steps * step
|
| 1343 |
+
left, left_error, left_nfev = _direct(f, a, k, step, args,
|
| 1344 |
+
constants, xp, inclusive=False)
|
| 1345 |
+
left_is_pos_inf = xp.isinf(left) & (left > 0)
|
| 1346 |
+
i_skip |= left_is_pos_inf # if sum is infinite, no sense in continuing
|
| 1347 |
+
status[left_is_pos_inf] = -3
|
| 1348 |
+
k[i_skip] = xp.nan
|
| 1349 |
+
|
| 1350 |
+
# Use integration to estimate the remaining sum
|
| 1351 |
+
# Possible optimization for future work: if there were no terms less than
|
| 1352 |
+
# the tolerance, there is no need to compute the integral to better accuracy.
|
| 1353 |
+
# Something like:
|
| 1354 |
+
# atol = xp.maximum(atol, xp.minimum(fk/2 - fb/2))
|
| 1355 |
+
# rtol = xp.maximum(rtol, xp.minimum((fk/2 - fb/2)/left))
|
| 1356 |
+
# where `fk`/`fb` are currently calculated below.
|
| 1357 |
+
right = tanhsinh(f, k, b, args=args, atol=atol, rtol=rtol, log=log)
|
| 1358 |
+
|
| 1359 |
+
# Calculate the full estimate and error from the pieces
|
| 1360 |
+
fk = fks[xp.arange(len(fks)), nt]
|
| 1361 |
+
|
| 1362 |
+
# fb = f(b, *args), but some functions return NaN at infinity.
|
| 1363 |
+
# instead of 0 like they must (for the sum to be convergent).
|
| 1364 |
+
fb = xp.full_like(fk, -xp.inf) if log else xp.zeros_like(fk)
|
| 1365 |
+
i = xp.isfinite(b)
|
| 1366 |
+
if xp.any(i): # better not call `f` with empty arrays
|
| 1367 |
+
fb[i] = f(b[i], *[arg[i] for arg in args])
|
| 1368 |
+
nfev = nfev + xp.asarray(i, dtype=left_nfev.dtype)
|
| 1369 |
+
|
| 1370 |
+
if log:
|
| 1371 |
+
log_step = xp.log(step)
|
| 1372 |
+
S_terms = (left, right.integral - log_step, fk - log2, fb - log2)
|
| 1373 |
+
S = special.logsumexp(xp.stack(S_terms), axis=0)
|
| 1374 |
+
E_terms = (left_error, right.error - log_step, fk-log2, fb-log2+xp.pi*1j)
|
| 1375 |
+
E = xp_real(special.logsumexp(xp.stack(E_terms), axis=0))
|
| 1376 |
+
else:
|
| 1377 |
+
S = left + right.integral/step + fk/2 + fb/2
|
| 1378 |
+
E = left_error + right.error/step + fk/2 - fb/2
|
| 1379 |
+
status[~i_skip] = right.status[~i_skip]
|
| 1380 |
+
|
| 1381 |
+
status[(status == 0) & i_fk_insufficient] = -4
|
| 1382 |
+
return S, E, status, left_nfev + right.nfev + nfev + lb.nfev
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_test_multivariate.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (16.9 kB). View file
|
|
|
infer_4_30_0/lib/python3.10/site-packages/scipy/integrate/_test_odeint_banded.cpython-310-x86_64-linux-gnu.so
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:71ffdbfaa16726aa2246c2ce5c98caea7d35847d89e13b2c4a30ee36fc19e2fd
|
| 3 |
+
size 516577
|