_odepack_py.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # Author: Travis Oliphant
  2. __all__ = ['odeint']
  3. import numpy as np
  4. from . import _odepack
  5. from copy import copy
  6. import warnings
  7. class ODEintWarning(Warning):
  8. pass
  9. _msgs = {2: "Integration successful.",
  10. 1: "Nothing was done; the integration time was 0.",
  11. -1: "Excess work done on this call (perhaps wrong Dfun type).",
  12. -2: "Excess accuracy requested (tolerances too small).",
  13. -3: "Illegal input detected (internal error).",
  14. -4: "Repeated error test failures (internal error).",
  15. -5: "Repeated convergence failures (perhaps bad Jacobian or tolerances).",
  16. -6: "Error weight became zero during problem.",
  17. -7: "Internal workspace insufficient to finish (internal error).",
  18. -8: "Run terminated (internal error)."
  19. }
  20. def odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0,
  21. ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0,
  22. hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12,
  23. mxords=5, printmessg=0, tfirst=False):
  24. """
  25. Integrate a system of ordinary differential equations.
  26. .. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
  27. differential equation.
  28. Solve a system of ordinary differential equations using lsoda from the
  29. FORTRAN library odepack.
  30. Solves the initial value problem for stiff or non-stiff systems
  31. of first order ode-s::
  32. dy/dt = func(y, t, ...) [or func(t, y, ...)]
  33. where y can be a vector.
  34. .. note:: By default, the required order of the first two arguments of
  35. `func` are in the opposite order of the arguments in the system
  36. definition function used by the `scipy.integrate.ode` class and
  37. the function `scipy.integrate.solve_ivp`. To use a function with
  38. the signature ``func(t, y, ...)``, the argument `tfirst` must be
  39. set to ``True``.
  40. Parameters
  41. ----------
  42. func : callable(y, t, ...) or callable(t, y, ...)
  43. Computes the derivative of y at t.
  44. If the signature is ``callable(t, y, ...)``, then the argument
  45. `tfirst` must be set ``True``.
  46. y0 : array
  47. Initial condition on y (can be a vector).
  48. t : array
  49. A sequence of time points for which to solve for y. The initial
  50. value point should be the first element of this sequence.
  51. This sequence must be monotonically increasing or monotonically
  52. decreasing; repeated values are allowed.
  53. args : tuple, optional
  54. Extra arguments to pass to function.
  55. Dfun : callable(y, t, ...) or callable(t, y, ...)
  56. Gradient (Jacobian) of `func`.
  57. If the signature is ``callable(t, y, ...)``, then the argument
  58. `tfirst` must be set ``True``.
  59. col_deriv : bool, optional
  60. True if `Dfun` defines derivatives down columns (faster),
  61. otherwise `Dfun` should define derivatives across rows.
  62. full_output : bool, optional
  63. True if to return a dictionary of optional outputs as the second output
  64. printmessg : bool, optional
  65. Whether to print the convergence message
  66. tfirst : bool, optional
  67. If True, the first two arguments of `func` (and `Dfun`, if given)
  68. must ``t, y`` instead of the default ``y, t``.
  69. .. versionadded:: 1.1.0
  70. Returns
  71. -------
  72. y : array, shape (len(t), len(y0))
  73. Array containing the value of y for each desired time in t,
  74. with the initial value `y0` in the first row.
  75. infodict : dict, only returned if full_output == True
  76. Dictionary containing additional output information
  77. ======= ============================================================
  78. key meaning
  79. ======= ============================================================
  80. 'hu' vector of step sizes successfully used for each time step
  81. 'tcur' vector with the value of t reached for each time step
  82. (will always be at least as large as the input times)
  83. 'tolsf' vector of tolerance scale factors, greater than 1.0,
  84. computed when a request for too much accuracy was detected
  85. 'tsw' value of t at the time of the last method switch
  86. (given for each time step)
  87. 'nst' cumulative number of time steps
  88. 'nfe' cumulative number of function evaluations for each time step
  89. 'nje' cumulative number of jacobian evaluations for each time step
  90. 'nqu' a vector of method orders for each successful step
  91. 'imxer' index of the component of largest magnitude in the
  92. weighted local error vector (e / ewt) on an error return, -1
  93. otherwise
  94. 'lenrw' the length of the double work array required
  95. 'leniw' the length of integer work array required
  96. 'mused' a vector of method indicators for each successful time step:
  97. 1: adams (nonstiff), 2: bdf (stiff)
  98. ======= ============================================================
  99. Other Parameters
  100. ----------------
  101. ml, mu : int, optional
  102. If either of these are not None or non-negative, then the
  103. Jacobian is assumed to be banded. These give the number of
  104. lower and upper non-zero diagonals in this banded matrix.
  105. For the banded case, `Dfun` should return a matrix whose
  106. rows contain the non-zero bands (starting with the lowest diagonal).
  107. Thus, the return matrix `jac` from `Dfun` should have shape
  108. ``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
  109. The data in `jac` must be stored such that ``jac[i - j + mu, j]``
  110. holds the derivative of the `i`th equation with respect to the `j`th
  111. state variable. If `col_deriv` is True, the transpose of this
  112. `jac` must be returned.
  113. rtol, atol : float, optional
  114. The input parameters `rtol` and `atol` determine the error
  115. control performed by the solver. The solver will control the
  116. vector, e, of estimated local errors in y, according to an
  117. inequality of the form ``max-norm of (e / ewt) <= 1``,
  118. where ewt is a vector of positive error weights computed as
  119. ``ewt = rtol * abs(y) + atol``.
  120. rtol and atol can be either vectors the same length as y or scalars.
  121. Defaults to 1.49012e-8.
  122. tcrit : ndarray, optional
  123. Vector of critical points (e.g., singularities) where integration
  124. care should be taken.
  125. h0 : float, (0: solver-determined), optional
  126. The step size to be attempted on the first step.
  127. hmax : float, (0: solver-determined), optional
  128. The maximum absolute step size allowed.
  129. hmin : float, (0: solver-determined), optional
  130. The minimum absolute step size allowed.
  131. ixpr : bool, optional
  132. Whether to generate extra printing at method switches.
  133. mxstep : int, (0: solver-determined), optional
  134. Maximum number of (internally defined) steps allowed for each
  135. integration point in t.
  136. mxhnil : int, (0: solver-determined), optional
  137. Maximum number of messages printed.
  138. mxordn : int, (0: solver-determined), optional
  139. Maximum order to be allowed for the non-stiff (Adams) method.
  140. mxords : int, (0: solver-determined), optional
  141. Maximum order to be allowed for the stiff (BDF) method.
  142. See Also
  143. --------
  144. solve_ivp : solve an initial value problem for a system of ODEs
  145. ode : a more object-oriented integrator based on VODE
  146. quad : for finding the area under a curve
  147. Examples
  148. --------
  149. The second order differential equation for the angle `theta` of a
  150. pendulum acted on by gravity with friction can be written::
  151. theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
  152. where `b` and `c` are positive constants, and a prime (') denotes a
  153. derivative. To solve this equation with `odeint`, we must first convert
  154. it to a system of first order equations. By defining the angular
  155. velocity ``omega(t) = theta'(t)``, we obtain the system::
  156. theta'(t) = omega(t)
  157. omega'(t) = -b*omega(t) - c*sin(theta(t))
  158. Let `y` be the vector [`theta`, `omega`]. We implement this system
  159. in Python as:
  160. >>> import numpy as np
  161. >>> def pend(y, t, b, c):
  162. ... theta, omega = y
  163. ... dydt = [omega, -b*omega - c*np.sin(theta)]
  164. ... return dydt
  165. ...
  166. We assume the constants are `b` = 0.25 and `c` = 5.0:
  167. >>> b = 0.25
  168. >>> c = 5.0
  169. For initial conditions, we assume the pendulum is nearly vertical
  170. with `theta(0)` = `pi` - 0.1, and is initially at rest, so
  171. `omega(0)` = 0. Then the vector of initial conditions is
  172. >>> y0 = [np.pi - 0.1, 0.0]
  173. We will generate a solution at 101 evenly spaced samples in the interval
  174. 0 <= `t` <= 10. So our array of times is:
  175. >>> t = np.linspace(0, 10, 101)
  176. Call `odeint` to generate the solution. To pass the parameters
  177. `b` and `c` to `pend`, we give them to `odeint` using the `args`
  178. argument.
  179. >>> from scipy.integrate import odeint
  180. >>> sol = odeint(pend, y0, t, args=(b, c))
  181. The solution is an array with shape (101, 2). The first column
  182. is `theta(t)`, and the second is `omega(t)`. The following code
  183. plots both components.
  184. >>> import matplotlib.pyplot as plt
  185. >>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
  186. >>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
  187. >>> plt.legend(loc='best')
  188. >>> plt.xlabel('t')
  189. >>> plt.grid()
  190. >>> plt.show()
  191. """
  192. if ml is None:
  193. ml = -1 # changed to zero inside function call
  194. if mu is None:
  195. mu = -1 # changed to zero inside function call
  196. dt = np.diff(t)
  197. if not ((dt >= 0).all() or (dt <= 0).all()):
  198. raise ValueError("The values in t must be monotonically increasing "
  199. "or monotonically decreasing; repeated values are "
  200. "allowed.")
  201. t = copy(t)
  202. y0 = copy(y0)
  203. output = _odepack.odeint(func, y0, t, args, Dfun, col_deriv, ml, mu,
  204. full_output, rtol, atol, tcrit, h0, hmax, hmin,
  205. ixpr, mxstep, mxhnil, mxordn, mxords,
  206. int(bool(tfirst)))
  207. if output[-1] < 0:
  208. warning_msg = _msgs[output[-1]] + " Run with full_output = 1 to get quantitative information."
  209. warnings.warn(warning_msg, ODEintWarning)
  210. elif printmessg:
  211. warning_msg = _msgs[output[-1]]
  212. warnings.warn(warning_msg, ODEintWarning)
  213. if full_output:
  214. output[1]['message'] = _msgs[output[-1]]
  215. output = output[:-1]
  216. if len(output) == 1:
  217. return output[0]
  218. else:
  219. return output