Debian Codegraph @

man/lsoda.Rd

raw
1 \name{lsoda}
2 \alias{lsoda}
3 \title{
4 Solver for Ordinary Differential Equations (ODE),
5 Switching Automatically Between Stiff and Non-stiff Methods
6 }
7 \description{
8
9 Solving initial value problems for stiff or non-stiff systems of
10 first-order ordinary differential equations (ODEs).
11
12 The \R function \code{lsoda} provides an interface to the FORTRAN ODE
13 solver of the same name, written by Linda R. Petzold and Alan
14 C. Hindmarsh.
15
16 The system of ODE's is written as an \R function (which may, of
17 course, use \code{\link{.C}}, \code{\link{.Fortran}},
18 \code{\link{.Call}}, etc., to call foreign code) or be defined in
19 compiled code that has been dynamically loaded. A vector of
20 parameters is passed to the ODEs, so the solver may be used as part of
21 a modeling package for ODEs, or for parameter estimation using any
22 appropriate modeling tool for non-linear models in \R such as
23 \code{\link{optim}}, \code{\link{nls}}, \code{\link{nlm}} or
24 \code{\link[nlme]{nlme}}
25
26 \code{lsoda} differs from the other integrators (except \code{lsodar})
27 in that it switches automatically between stiff and nonstiff methods.
28 This means that the user does not have to determine whether the
29 problem is stiff or not, and the solver will automatically choose the
30 appropriate method. It always starts with the nonstiff method.
31 }
32 \usage{
33 lsoda(y, times, func, parms, rtol = 1e-6, atol = 1e-6,
34 jacfunc = NULL, jactype = "fullint", rootfunc = NULL,
35 verbose = FALSE, nroot = 0, tcrit = NULL,
36 hmin = 0, hmax = NULL, hini = 0, ynames = TRUE,
37 maxordn = 12, maxords = 5, bandup = NULL, banddown = NULL,
38 maxsteps = 5000, dllname = NULL, initfunc = dllname,
39 initpar = parms, rpar = NULL, ipar = NULL, nout = 0,
40 outnames = NULL, forcings = NULL, initforc = NULL,
41 fcontrol = NULL, events = NULL, lags = NULL,...)
42 }
43 \arguments{
44 \item{y }{the initial (state) values for the ODE system. If \code{y}
45 has a name attribute, the names will be used to label the output
46 matrix.
47 }
48 \item{times }{times at which explicit estimates for \code{y} are
49 desired. The first value in \code{times} must be the initial time.
50 }
51 \item{func }{either an \R-function that computes the values of the
52 derivatives in the ODE system (the \emph{model definition}) at time
53 t, or a character string giving the name of a compiled function in a
54 dynamically loaded shared library, or a list of symbols returned by
55 \code{\link{checkDLL}}.
56
57 If \code{func} is an \R-function, it must be defined as:
58 \code{func <- function(t, y, parms,...)}. \code{t} is the current
59 time point in the integration, \code{y} is the current estimate of
60 the variables in the ODE system. If the initial values \code{y} has
61 a \code{names} attribute, the names will be available inside \code{func}.
62 \code{parms} is a vector or list of parameters; ... (optional) are
63 any other arguments passed to the function.
64
65 The return value of \code{func} should be a list, whose first
66 element is a vector containing the derivatives of \code{y} with
67 respect to \code{time}, and whose next elements are global values
68 that are required at each point in \code{times}. The derivatives
69 must be specified in the \bold{same order} as the state variables \code{y}.
70
71 If \code{func} is a string, then \code{dllname} must give the name
72 of the shared library (without extension) which must be loaded
73 before \code{lsoda()} is called. See package vignette
74 \code{"compiledCode"} for more
75 details.
76
77 \code{func} can also be a list of symbols returned by \code{\link{checkDLL}}
78 to avoid overhead from repeated internal calls to this function. It
79 is an experimental feature for special situations, when a small compiled
80 model with a low number of integration steps is repeatedly called. It is
81 currently only available for the \code{lsoda} solver, see
82 \href{../doc/dynload-fastlsoda}{example}.
83 }
84 \item{parms }{vector or list of parameters used in \code{func} or
85 \code{jacfunc}.
86 }
87 \item{rtol }{relative error tolerance, either a scalar or an array as
88 long as \code{y}. See details.
89 }
90 \item{atol }{absolute error tolerance, either a scalar or an array as
91 long as \code{y}. See details.
92 }
93 \item{jacfunc }{if not \code{NULL}, an \R function, that computes the
94 Jacobian of the system of differential equations
95 \eqn{\partial\dot{y}_i/\partial y_j}{dydot(i)/dy(j)}, or
96 a string giving the name of a function or subroutine in
97 \file{dllname} that computes the Jacobian (see vignette
98 \code{"compiledCode"} for more about this option).
99
100 In some circumstances, supplying
101 \code{jacfunc} can speed up the computations, if the system is
102 stiff. The \R calling sequence for \code{jacfunc} is identical to
103 that of \code{func}.
104
105 If the Jacobian is a full matrix, \code{jacfunc} should return a
106 matrix \eqn{\partial\dot{y}/\partial y}{dydot/dy}, where the ith row contains the derivative of
107 \eqn{dy_i/dt} with respect to \eqn{y_j}, or a vector containing the
108 matrix elements by columns (the way \R and FORTRAN store matrices).
109
110 If the Jacobian is banded, \code{jacfunc} should return a matrix
111 containing only the nonzero bands of the Jacobian, rotated
112 row-wise. See first example of \link{lsode}.
113 }
114 \item{jactype }{the structure of the Jacobian, one of \code{"fullint"},
115 \code{"fullusr"}, \code{"bandusr"} or \code{"bandint"} - either
116 full or banded and estimated internally or by user.
117 }
118 \item{rootfunc }{if not \code{NULL}, an \R function that computes the
119 function whose root has to be estimated or a string giving the name
120 of a function or subroutine in \file{dllname} that computes the root
121 function. The \R calling sequence for \code{rootfunc} is identical
122 to that of \code{func}. \code{rootfunc} should return a vector with
123 the function values whose root is sought. When \code{rootfunc} is
124 provided, then \code{lsodar} will be called.
125 }
126 \item{verbose }{if \code{TRUE}: full output to the screen, e.g. will
127 print the \code{diagnostiscs} of the integration - see details.
128 }
129 \item{nroot }{only used if \file{dllname} is specified: the number of
130 constraint functions whose roots are desired during the integration;
131 if \code{rootfunc} is an R-function, the solver estimates the number
132 of roots.
133 }
134 \item{tcrit }{if not \code{NULL}, then \code{lsoda} cannot integrate
135 past \code{tcrit}. The FORTRAN routine \code{lsoda} overshoots its
136 targets (times points in the vector \code{times}), and interpolates
137 values for the desired time points. If there is a time beyond which
138 integration should not proceed (perhaps because of a singularity),
139 that should be provided in \code{tcrit}.
140 }
141 \item{hmin }{an optional minimum value of the integration stepsize. In
142 special situations this parameter may speed up computations with the
143 cost of precision. Don't use \code{hmin} if you don't know why!
144 }
145 \item{hmax }{an optional maximum value of the integration stepsize. If
146 not specified, \code{hmax} is set to the largest difference in
147 \code{times}, to avoid that the simulation possibly ignores
148 short-term events. If 0, no maximal size is specified.
149 }
150 \item{hini }{initial step size to be attempted; if 0, the initial step
151 size is determined by the solver.
152 }
153 \item{ynames }{logical, if \code{FALSE}: names of state variables are not
154 passed to function \code{func}; this may speed up the simulation especially
155 for large models.
156 }
157 \item{maxordn }{the maximum order to be allowed in case the method is
158 non-stiff. Should be <= 12. Reduce \code{maxord} to save storage space.
159 }
160 \item{maxords }{the maximum order to be allowed in case the method is
161 stiff. Should be <= 5. Reduce maxord to save storage space.
162 }
163 \item{bandup }{number of non-zero bands above the diagonal, in case
164 the Jacobian is banded.
165 }
166 \item{banddown }{number of non-zero bands below the diagonal, in case
167 the Jacobian is banded.
168 }
169 \item{maxsteps }{maximal number of steps per output interval taken by the
170 solver.
171 }
172 \item{dllname }{a string giving the name of the shared library
173 (without extension) that contains all the compiled function or
174 subroutine definitions refered to in \code{func} and
175 \code{jacfunc}. See package vignette \code{"compiledCode"}.
176 }
177 \item{initfunc }{if not \code{NULL}, the name of the initialisation function
178 (which initialises values of parameters), as provided in
179 \file{dllname}. See package vignette \code{"compiledCode"}.
180 }
181 \item{initpar }{only when \file{dllname} is specified and an
182 initialisation function \code{initfunc} is in the dll: the
183 parameters passed to the initialiser, to initialise the common
184 blocks (FORTRAN) or global variables (C, C++).
185 }
186 \item{rpar }{only when \file{dllname} is specified: a vector with
187 double precision values passed to the dll-functions whose names are
188 specified by \code{func} and \code{jacfunc}.
189 }
190 \item{ipar }{only when \file{dllname} is specified: a vector with
191 integer values passed to the dll-functions whose names are specified
192 by \code{func} and \code{jacfunc}.
193 }
194 \item{nout }{only used if \code{dllname} is specified and the model is
195 defined in compiled code: the number of output variables calculated
196 in the compiled function \code{func}, present in the shared
197 library. Note: it is not automatically checked whether this is
198 indeed the number of output variables calculated in the dll - you have
199 to perform this check in the code. See package vignette
200 \code{"compiledCode"}.
201 }
202 \item{outnames }{only used if \file{dllname} is specified and
203 \code{nout} > 0: the names of output variables calculated in the
204 compiled function \code{func}, present in the shared library.
205 These names will be used to label the output matrix.
206 }
207 \item{forcings }{only used if \file{dllname} is specified: a list with
208 the forcing function data sets, each present as a two-columned matrix,
209 with (time,value); interpolation outside the interval
210 [min(\code{times}), max(\code{times})] is done by taking the value at
211 the closest data extreme.
212
213 See \link{forcings} or package vignette \code{"compiledCode"}.
214 }
215 \item{initforc }{if not \code{NULL}, the name of the forcing function
216 initialisation function, as provided in
217 \file{dllname}. It MUST be present if \code{forcings} has been given a
218 value.
219 See \link{forcings} or package vignette \code{"compiledCode"}.
220 }
221 \item{fcontrol }{A list of control parameters for the forcing functions.
222 See \link{forcings} or vignette \code{compiledCode}.
223 }
224 \item{events }{A matrix or data frame that specifies events, i.e. when the value of a
225 state variable is suddenly changed. See \link{events} for more information.
226 }
227 \item{lags }{A list that specifies timelags, i.e. the number of steps
228 that has to be kept. To be used for delay differential equations.
229 See \link{timelags}, \link{dede} for more information.
230 }
231 \item{... }{additional arguments passed to \code{func} and
232 \code{jacfunc} allowing this to be a generic function.
233 }
234 }
235 \value{
236 A matrix of class \code{deSolve} with up to as many rows as elements
237 in \code{times} and as many columns as elements in \code{y} plus the number of "global"
238 values returned in the next elements of the return from \code{func},
239 plus and additional column for the time value. There will be a row
240 for each element in \code{times} unless the FORTRAN routine `lsoda'
241 returns with an unrecoverable error. If \code{y} has a names
242 attribute, it will be used to label the columns of the output value.
243
244 }
245 \author{R. Woodrow Setzer <[email protected]>}
246 \examples{
247 ## =======================================================================
248 ## Example 1:
249 ## A simple resource limited Lotka-Volterra-Model
250 ##
251 ## Note:
252 ## 1. parameter and state variable names made
253 ## accessible via "with" function
254 ## 2. function sigimp accessible through lexical scoping
255 ## (see also ode and rk examples)
256 ## =======================================================================
257
258 SPCmod <- function(t, x, parms) {
259 with(as.list(c(parms, x)), {
260 import <- sigimp(t)
261 dS <- import - b*S*P + g*C #substrate
262 dP <- c*S*P - d*C*P #producer
263 dC <- e*P*C - f*C #consumer
264 res <- c(dS, dP, dC)
265 list(res)
266 })
267 }
268
269 ## Parameters
270 parms <- c(b = 0.0, c = 0.1, d = 0.1, e = 0.1, f = 0.1, g = 0.0)
271
272 ## vector of timesteps
273 times <- seq(0, 100, length = 101)
274
275 ## external signal with rectangle impulse
276 signal <- as.data.frame(list(times = times,
277 import = rep(0,length(times))))
278
279 signal$import[signal$times >= 10 & signal$times <= 11] <- 0.2
280
281 sigimp <- approxfun(signal$times, signal$import, rule = 2)
282
283
284 ## Start values for steady state
285 y <- xstart <- c(S = 1, P = 1, C = 1)
286
287 ## Solving
288 out <- lsoda(xstart, times, SPCmod, parms)
289
290 ## Plotting
291 mf <- par("mfrow")
292 plot(out, main = c("substrate", "producer", "consumer"))
293 plot(out[,"P"], out[,"C"], type = "l", xlab = "producer", ylab = "consumer")
294 par(mfrow = mf)
295
296 ## =======================================================================
297 ## Example 2:
298 ## from lsoda source code
299 ## =======================================================================
300
301 ## names makes this easier to read, but may slow down execution.
302 parms <- c(k1 = 0.04, k2 = 1e4, k3 = 3e7)
303 my.atol <- c(1e-6, 1e-10, 1e-6)
304 times <- c(0,4 * 10^(-1:10))
305
306 lsexamp <- function(t, y, p) {
307 yd1 <- -p["k1"] * y[1] + p["k2"] * y[2]*y[3]
308 yd3 <- p["k3"] * y[2]^2
309 list(c(yd1, -yd1-yd3, yd3), c(massbalance = sum(y)))
310 }
311
312 exampjac <- function(t, y, p) {
313 matrix(c(-p["k1"], p["k1"], 0,
314
315 p["k2"]*y[3],
316 - p["k2"]*y[3] - 2*p["k3"]*y[2],
317 2*p["k3"]*y[2],
318
319 p["k2"]*y[2], -p["k2"]*y[2], 0
320 ), 3, 3)
321 }
322
323
324 ## measure speed (here and below)
325 system.time(
326 out <- lsoda(c(1, 0, 0), times, lsexamp, parms, rtol = 1e-4,
327 atol = my.atol, hmax = Inf)
328 )
329 out
330
331 ## This is what the authors of lsoda got for the example:
332
333 ## the output of this program (on a cdc-7600 in single precision)
334 ## is as follows..
335 ##
336 ## at t = 4.0000e-01 y = 9.851712e-01 3.386380e-05 1.479493e-02
337 ## at t = 4.0000e+00 y = 9.055333e-01 2.240655e-05 9.444430e-02
338 ## at t = 4.0000e+01 y = 7.158403e-01 9.186334e-06 2.841505e-01
339 ## at t = 4.0000e+02 y = 4.505250e-01 3.222964e-06 5.494717e-01
340 ## at t = 4.0000e+03 y = 1.831975e-01 8.941774e-07 8.168016e-01
341 ## at t = 4.0000e+04 y = 3.898730e-02 1.621940e-07 9.610125e-01
342 ## at t = 4.0000e+05 y = 4.936363e-03 1.984221e-08 9.950636e-01
343 ## at t = 4.0000e+06 y = 5.161831e-04 2.065786e-09 9.994838e-01
344 ## at t = 4.0000e+07 y = 5.179817e-05 2.072032e-10 9.999482e-01
345 ## at t = 4.0000e+08 y = 5.283401e-06 2.113371e-11 9.999947e-01
346 ## at t = 4.0000e+09 y = 4.659031e-07 1.863613e-12 9.999995e-01
347 ## at t = 4.0000e+10 y = 1.404280e-08 5.617126e-14 1.000000e+00
348
349 ## Using the analytic Jacobian speeds up execution a little :
350
351 system.time(
352 outJ <- lsoda(c(1, 0, 0), times, lsexamp, parms, rtol = 1e-4,
353 atol = my.atol, jacfunc = exampjac, jactype = "fullusr", hmax = Inf)
354 )
355
356 all.equal(as.data.frame(out), as.data.frame(outJ)) # TRUE
357 diagnostics(out)
358 diagnostics(outJ) # shows what lsoda did internally
359
360 }
361 \references{
362
363 Hindmarsh, Alan C. (1983) ODEPACK, A Systematized Collection of ODE
364 Solvers; in p.55--64 of Stepleman, R.W. et al.[ed.] (1983)
365 \emph{Scientific Computing}, North-Holland, Amsterdam.
366
367 Petzold, Linda R. (1983) Automatic Selection of Methods for Solving
368 Stiff and Nonstiff Systems of Ordinary Differential Equations.
369 \emph{Siam J. Sci. Stat. Comput.} \bold{4}, 136--148.
370 \doi{10.1137/0904010}
371
372 Netlib: \url{https://netlib.org}
373 }
374 \details{
375 All the hard work is done by the FORTRAN subroutine \code{lsoda},
376 whose documentation should be consulted for details (it is included as
377 comments in the source file \file{src/opkdmain.f}). The implementation
378 is based on the 12 November 2003 version of lsoda, from Netlib.
379
380 \code{lsoda} switches automatically between stiff and nonstiff
381 methods. This means that the user does not have to determine whether
382 the problem is stiff or not, and the solver will automatically choose
383 the appropriate method. It always starts with the nonstiff method.
384
385
386 The form of the \bold{Jacobian} can be specified by \code{jactype} which can
387 take the following values:
388 \describe{
389 \item{"fullint"}{a full Jacobian, calculated internally by lsoda, the default,}
390 \item{"fullusr"}{a full Jacobian, specified by user function \code{jacfunc},}
391 \item{"bandusr"}{a banded Jacobian, specified by user function \code{jacfunc}
392 the size of the bands specified by \code{bandup} and \code{banddown},}
393 \item{"bandint"}{banded Jacobian, calculated by lsoda; the size of the bands
394 specified by \code{bandup} and \code{banddown}.}
395 }
396 If \code{jactype} = "fullusr" or "bandusr" then the user must supply a
397 subroutine \code{jacfunc}.
398
399 The following description of \bold{error control} is adapted from the
400 documentation of the lsoda source code
401 (input arguments \code{rtol} and \code{atol}, above):
402
403 The input parameters \code{rtol}, and \code{atol} determine the error
404 control performed by the solver. The solver will control the vector
405 \bold{e} of estimated local errors in \bold{y}, according to an
406 inequality of the form max-norm of ( \bold{e}/\bold{ewt} ) \eqn{\leq}{
407 <= } 1, where \bold{ewt} is a vector of positive error weights. The
408 values of \code{rtol} and \code{atol} should all be non-negative. The
409 form of \bold{ewt} is:
410
411 \deqn{\mathbf{rtol} \times \mathrm{abs}(\mathbf{y}) +
412 \mathbf{atol}}{\bold{rtol} * abs(\bold{y}) + \bold{atol}}
413
414 where multiplication of two vectors is element-by-element.
415
416 If the request for precision exceeds the capabilities of the machine,
417 the FORTRAN subroutine lsoda will return an error code; under some
418 circumstances, the \R function \code{lsoda} will attempt a reasonable
419 reduction of precision in order to get an answer. It will write a
420 warning if it does so.
421
422 The diagnostics of the integration can be printed to screen
423 by calling \code{\link{diagnostics}}. If \code{verbose} = \code{TRUE},
424 the diagnostics will written to the screen at the end of the integration.
425
426 See vignette("deSolve") for an explanation of each element in the vectors
427 containing the diagnostic properties and how to directly access them.
428
429 \bold{Models} may be defined in compiled C or FORTRAN code, as well as
430 in an R-function. See package vignette \code{"compiledCode"} for details.
431
432 More information about models defined in compiled code is in the package
433 vignette ("compiledCode"); information about linking forcing functions
434 to compiled code is in \link{forcings}.
435
436 Examples in both C and FORTRAN are in the \file{dynload} subdirectory
437 of the \code{deSolve} package directory.
438
439
440 }
441 \seealso{
442 \itemize{
443 \item \code{\link{rk}}, \code{\link{rkMethod}}, \code{\link{rk4}} and \code{\link{euler}} for
444 Runge-Kutta integrators.
445 \item \code{\link{lsode}}, which can also find a root
446 \item \code{\link{lsodes}}, \code{\link{lsodar}}, \code{\link{vode}},
447 \code{\link{daspk}} for other solvers of the Livermore family,
448 \item \code{\link{ode}} for a general interface to most of the ODE solvers,
449 \item \code{\link{ode.band}} for solving models with a banded
450 Jacobian,
451 \item \code{\link{ode.1D}} for integrating 1-D models,
452 \item \code{\link{ode.2D}} for integrating 2-D models,
453 \item \code{\link{ode.3D}} for integrating 3-D models,
454 }
455
456 \code{\link{diagnostics}} to print diagnostic messages.
457 }
458 \note{
459 The \file{demo} directory contains some examples of using
460 \code{\link[nlme]{gnls}} to estimate parameters in a
461 dynamic model.
462 }
463 \keyword{math}
464