You are on page 1of 139

Package ‘deSolve’

September 19, 2011
Version 1.10-3 Title General solvers for initial value problems of ordinary differential equations (ODE), partial differential equations (PDE), differential algebraic equations (DAE), and delay differential equations (DDE). Author Karline Soetaert <k.soetaert@nioo.knaw.nl>, Thomas Petzoldt <thomas.petzoldt@tu-dresden.de>, R. Woodrow Setzer <setzer.woodrow@epa.gov> Maintainer Thomas Petzoldt <thomas.petzoldt@tu-dresden.de> Depends R (>= 2.6.0) Description Functions that solve initial value problems of a system of first-order ordinary differential equations (ODE), of partial differential equations (PDE), of differential algebraic equations (DAE), and of delay differential equations. The functions provide an interface to the FORTRAN functions lsoda,lsodar, lsode, lsodes of the ODEPACK collection, to the FORTRAN functions dvode and daspk and a C-implementation of solvers of the Runge-Kutta family with fixed or variable time steps. The package contains routines designed for solving ODEs resulting from 1-D, 2-D and 3-D partial differential equations (PDE) that have been converted to ODEs by numerical differencing. License GPL (>= 2) URL http://desolve.r-forge.r-project.org/ LazyData yes Repository CRAN Date/Publication 2011-08-10 10:13:15 1

2

deSolve-package

R topics documented:
deSolve-package . aquaphy . . . . . . ccl4data . . . . . . ccl4model . . . . . cleanEventTimes . daspk . . . . . . . dede . . . . . . . . diagnostics . . . . diagnostics.deSolve DLLfunc . . . . . DLLres . . . . . . events . . . . . . . forcings . . . . . . lsoda . . . . . . . . lsodar . . . . . . . lsode . . . . . . . . lsodes . . . . . . . ode . . . . . . . . . ode.1D . . . . . . . ode.2D . . . . . . . ode.3D . . . . . . . ode.band . . . . . . plot.deSolve . . . . radau . . . . . . . rk . . . . . . . . . rk4 . . . . . . . . . rkMethod . . . . . SCOC . . . . . . . timelags . . . . . . vode . . . . . . . . zvode . . . . . . . Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 5 8 9 12 13 22 26 27 28 30 33 38 41 48 54 62 70 75 81 86 90 93 99 106 111 115 120 121 125 132 138

deSolve-package

General Solvers for Initial Value Problems of Ordinary Differential Equations (ODE), Partial Differential Equations (PDE), Differential Algebraic Equations (DAE) and delay differential equations (DDE).

Description Functions that solve initial value problems of a system of first-order ordinary differential equations (ODE), of partial differential equations (PDE), of differential algebraic equations (DAE) and delay differential equations.

deSolve-package

3

The functions provide an interface to the FORTRAN functions lsoda, lsodar, lsode, lsodes of the ODEPACK collection, to the FORTRAN functions dvode and daspk and a C-implementation of solvers of the Runge-Kutta family with fixed or variable time steps. The package contains routines designed for solving ODEs resulting from 1-D, 2-D and 3-D partial differential equations (PDE) that have been converted to ODEs by numerical differencing. It includes root-finding (or event location) and provides access to lagged variables and derivatives. Details Package: Type: Version: Date: License: deSolve Package 1.10-3 2011-08-06 GNU Public License 2 or above

The system of differential equations is written as an R function or defined in compiled code that has been dynamically loaded, see package vignette (vignette(compiledCode)) for details. The solvers may be used as part of a modeling package for differential equations, or for parameter estimation using any appropriate modeling tool for non-linear models in R such as optim, nls, nlm or nlme. Author(s) Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer References Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer (2010). Solving Differential Equations in R: Package deSolve Journal of Statistical Software, 33(9), 1–25. http://www.jstatsoft.org/ v33/i 9/ Karline Soetaert, Thomas Petzoldt, R Woodrow Setzer, (2010): Solving differential equations in R. The R Journal 2(2), 5-15. http://journal.r-project.org/archive/2 1 -2/RJournal_ 2 1 -2_Soetaert~et~al.pdf Alan C. Hindmarsh, 1983. ODEPACK, A Systematized Collection of ODE Solvers, in Scientific Computing, R. S. Stepleman et al. (Eds.), North-Holland, Amsterdam, pp. 55-64. L. R. Petzold, 1983. A Description of DASSL: A Differential/Algebraic System Solver, in Scientific Computing, R. S. Stepleman et al. (Eds.), North-Holland, Amsterdam, pp. 65-68. P. N. Brown, G. D. Byrne, and A. C. Hindmarsh, 1989. VODE: A Variable Coefficient ODE Solver, SIAM J. Sci. Stat. Comput., 10, pp. 1038-1051. See also the references given on the specific help pages of the different methods.

lagvalue. rkMethod. ode. for integrating 1-D.band) example(ode. rk. for how to get access to lagged values of state variables and derivatives.4 See Also ode for a general interface to most of the ODE solvers. DLLfunc. dede for a general interface to the delay differential equation solvers. daspk. radau for integrating DAEs up to index 3 using an implicit Runge-Kutta. lsoda. of the Livermore family. "/doc/examples". vode. "/demo". for a DAE solver up to index 1. for how to implement forcing functions (external variables) and events (sudden changes in state variables).3D) example(dede) ## run demos demo("odedim") # partial differential equations demo("CCL4model") # a model fitting example (this will take some time) ## open the directory with source code of demos browseURL(paste(system.3D. euler for Runge-Kutta solvers.file(package = "deSolve").file(package = "deSolve"). for testing model implementations in compiled code. ode. lagderiv. events. DLLres. ode. for ODE solvers of the Livermore family. sep = "")) ## open the directory with C and FORTRAN sourcecode examples browseURL(paste(system.2D) example(ode. lsodar. rk4. lsodes. sep = "")) ## show package vignette with how to use deSolve ## + source code of the vignette vignette("deSolve") edit(vignette("deSolve")) ## show package vignette with tutorial about how to use compiled models ## + source code of the vignette ## + directory with C and FORTRAN sources vignette("compiledCode") edit(vignette("compiledCode")) .file(package = "deSolve"). lsode.1D) example(ode.1D. "/doc/examples/dynload". ode.band for solving models with a banded Jacobian.2D. sep = "")) ## open the directory with R sourcecode examples browseURL(paste(system. 2-D and 3-D models. Examples ## Not run: ## show examples (see respective help pages for details) example(aquaphy) example(lsoda) example(ode. deSolve-package forcings.

vector or list with the aquaphy model parameters. • storage molecules (RESERVE) and • the biosynthetic and photosynthetic apparatus (PROTEINS). the light is switched on and off at fixed times (where the sum of illuminated + dark period = 24 hours). • In the default model. "LMW"). . a data set of the photosynthetically active radiation (light intensity). on-off PAR is used.. time sequence for which output is wanted.e. see the example for the order in which these have to be defined. . • In another version. An additional state variable. "PROTEIN".. with a fixed stoichiometric ratio. "RESERVE".. there is a day-night illumination regime. PAR = NULL. "/doc". the light is imposed as a forcing function data set.aquaphy browseURL(paste(system. in that order. As the relative amount of proteins changes in the algae. the product of photosynthesis. any other parameters passed to the integrator ode (which solves the model).. the initial (state) values ("DIN". All algal state variables are expressed in mmol C m−3 . dissolved inorganic nitrogen (DIN) has units of mmol N m−3 . The algae grow in a dilution culture (chemostat): there is constant inflow of DIN and outflow of culture water. so does the N:C and the Chl:C ratio. Usage aquaphy(times. the first value of times must be the initial time. sep = "")) ## End(Not run) 5 aquaphy A Physiological Model of Unbalanced Algal Growth Description A phytoplankton model with uncoupled carbon and nitrogen assimilation as a function of light and Dissolved Inorganic Nitrogen (DIN) concentration. parms. including DIN and algae. This model is written in FORTRAN. Two versions of the model are included. i.file(package = "deSolve"). if NULL. Algal biomass is described via 3 different state variables: • low molecular weight carbohydrates (LMW). Only proteins contain nitrogen and chlorophyll. at the same rate.) Arguments times y parms PAR . y.

The source can be found in the ‘doc/examples/dynload’ subdirectory of the package.soetaert@nioo. # /h .c(maxPhotoSynt = rMortPHY = alpha = pExudation = maxProteinSynt = ksDIN = minpLMW = maxpLMW = minQuotum = maxStorage = respirationRate= pResp = catabolismRate = dilutionRate = rNCProtein = inputDIN = rChlN = parMean = . A practical guide to ecological modelling.. # mol C/mol C . 5.15. 333–346.23. # /h . C. # mmol N/m3 1. # /hr . See Also ccl4model. and Herman. # uEinst/m2/s/hr . Springer.125/15 . # mol C/mol C/hr .125.136. 1. P. # g Chl/mol N 25 .6 Details aquaphy The model is implemented primarily to demonstrate the linking of FORTRAN with R-code. Soetaert.2. # mol C/mol C/hr 1. S. # mol C/mol C . Using R as a simulation platform. 1. Author(s) Karline Soetaert <k. 1. Journal of Marine Systems 2. C. # mol N/mol C 1 . # mmol N/m3 . Examples ## ====================================================== ## ## Example 1. # . 6.. and Mathot.knaw. 75. # /h . the CCl4 inhalation model. # . Modelling ice-edge phytoplankton bloom in the Scotia-Weddel sea sector of the Southern Ocean during spring 1988. . Veth. . . PAR an on-off function ## ## ====================================================== ## ----------------------------## the model parameters: ## ----------------------------parameters <.nl> References Lancelot. # umol Phot/m2/s .4. # /h .. # mol C/mol C . K. (2008). (1991).

xlab = "time. out$Chlorophyll[ii]. side = 3. type = "n".c(DIN PROTEIN RESERVE LMW = = = = 6. xlab = "time. out$DIN[ii]. 3.aquaphy dayLength ) = 15. xlab = "time. lwd = 2 ) mtext(outer = TRUE. type = "l". out$DIN[ii]. state. 1. out$PAR[ii]-1 . out$PhotoSynthesis[ii]. out$Chlorophyll[ii]. lwd = 2 ) plot (times[ii]. parameters)) ## ----------------------------## Plotting model output ## ----------------------------par(mfrow = c(2. 24*2 . # hours 7 ## ----------------------------## The initial conditions ## ----------------------------state <. box() lines(times[ii]. lwd = 2 ) plot (times[ii]. border = NA). PAR= on-off".9) ii <. xlab = "time. col = col. main = "NCratio". . hours". out$PAR[ii]-1 ..5) . main = "DIN". col = col. out$PhotoSynthesis[ii]. out$PAR[ii]-1 . hours". border = NA). ) # # # # mmol mmol mmol mmol N/m3 C/m3 C/m3 C/m3 ## ----------------------------## Running the model ## ----------------------------times <.1:length(out$PAR) . main = "Chlorophyll". col = col. out$NCratio[ii].grey( . hours".ylab = "ug/l") polygon(times[ii]. border = NA). . border = NA). 1) out <. col = col. "AQUAPHY.frame(aquaphy(times. oma = c( . col <.seq( . ylab = "molN/molC") polygon(times[ii]. box() lines(times[ii].type = "l". 2 . cex = 1. main = "PhotoSynthesis". ylab = "mmolC/m3/hr") polygon(times[ii].as.data. box() lines(times[ii]. out$PAR[ii]-1 .ylab = "mmolN/m3") polygon(times[ii]. type = "l". hours". )) plot(times[ii]. 2). lwd = 2 ) plot (times[ii]. out$NCratio[ii]. 5. box() lines(times[ii].

8

ccl4data

## ----------------------------## Summary model output ## ----------------------------t(summary(out)) ## ====================================================== ## ## Example 2. PAR a forcing function data set ## ## ====================================================== times <- seq( , 24*2 , 1) ## ----------------------------## create the forcing functions ## ----------------------------ftime <- seq( ,5 ,by= .5) parval <- pmax( ,25 + 35 *sin(ftime*2*pi/24)+ (runif(length(ftime))- .5)*25 ) Par <- matrix(nc=2,c(ftime,parval))

state <- c(DIN PROTEIN RESERVE LMW

= = = =

6., 2 . , 5. , 1. )

# # # #

mmol mmol mmol mmol

N/m3 C/m3 C/m3 C/m3

out <- aquaphy(times, state, parameters, Par) plot(out, which = c("PAR", "Chlorophyll", "DIN", "NCratio"), xlab = "time, hours", ylab = c("uEinst/m2/s", "ug/l", "mmolN/m3", "molN/molC")) mtext(outer = TRUE, side = 3, "AQUAPHY, PAR=forcing", cex = 1.5) # Now all variables plotted in one figure... plot(out, which = 1:9, type = "l") par(mfrow = c(1, 1))

ccl4data

Closed Chamber Study of CCl4 Metabolism by Rats.

Description The results of a closed chamber experiment to determine metabolic parameters for CCl4 (carbon tetrachloride) in rats.

ccl4model Usage data(ccl4data) Format This data frame contains the following columns: time the time (in hours after starting the experiment). initconc initial chamber concentration (ppm).

9

animal this is a repeated measures design; this variable indicates which animal the observation pertains to. ChamberConc chamber concentration at time, in ppm. Source Evans, et al. 1994 Applications of sensitivity analysis to a physiologically based pharmacokinetic model for carbon tetrachloride in rats. Toxicology and Applied Pharmacology 128: 36 – 44. Examples
plot(ChamberConc ~ time, data = ccl4data, xlab = "Time (hours)", xlim = range(c( , ccl4data$time)), ylab = "Chamber Concentration (ppm)", log = "y") ccl4data.avg <- aggregate(ccl4data$ChamberConc, by = ccl4data[c("time", "initconc")], mean) points(x ~ time, data = ccl4data.avg, pch = 16)

ccl4model

The CCl4 Inhalation Model

Description The CCl4 inhalation model implemented in .Fortran Usage ccl4model(times, y, parms, ...) Arguments times y parms ... time sequence for which the model has to be integrated. the initial values for the state variables ("AI", "AAM", "AT", "AF", "AL", "CLT" and "AM"), in that order. vector or list holding the ccl4 model parameters; see the example for the order in which these have to be defined. any other parameters passed to the integrator ode (which solves the model).

10 Details

ccl4model

The model is implemented primarily to demonstrate the linking of FORTRAN with R-code. The source can be found in the ‘/doc/examples/dynload’ subdirectory of the package. Author(s) R. Woodrow Setzer <setzer.woodrow@epa.gov> See Also Try demo(CCL4model) for how this model has been fitted to the dataset ccl4data, aquaphy, another FORTRAN model, describing growth in aquatic phytoplankton. Examples
## ================= ## Parameter values ## ================= Pm <- c( ## Physiological parameters BW = .182, # Body weight (kg) QP = 4. , # Alveolar ventilation rate (hr^-1) QC = 4. , # Cardiac output (hr^-1) VFC = . 8, # Fraction fat tissue (kg/(kg/BW)) VLC = . 4, # Fraction liver tissue (kg/(kg/BW)) VMC = .74, # Fraction of muscle tissue (kg/(kg/BW)) QFC = . 5, # Fractional blood flow to fat ((hr^-1)/QC QLC = .15, # Fractional blood flow to liver ((hr^-1)/QC) QMC = .32, # Fractional blood flow to muscle ((hr^-1)/QC) ## Chemical specific parameters for chemical PLA = 16.17, # Liver/air partition coefficient PFA = 281.48, # Fat/air partition coefficient PMA = 13.3, # Muscle/air partition coefficient PTA = 16.17, # Viscera/air partition coefficient PB = 5.487, # Blood/air partition coefficient MW = 153.8, # Molecular weight (g/mol) VMAX = . 4321671, # Max. velocity of metabolism (mg/hr) -calibrated KM = .4 27255, # Michaelis-Menten constant (mg/l) -calibrated ## Parameters CONC = 1 , KL = . 2, RATS = 1. , VCHC = 3.8 ) ## ================ ## State variables ## ================ for simulated experiment # Inhaled concentration # Loss rate from empty chamber /hr # Number of rats enclosed in chamber # Volume of closed chamber (l)

implemented as a data. ylab = "Chamber Concentration (ppm)". Pm)) lines(out$time.197. log = "y".seq( . 6)) eventdat print(system. 6. data = ccl4data. y.Pm[["RATS"]] * Pm[["BW"]] AI <.-time curve in the liver AM = # the amount metabolized (AM) ) ## ================== ## Model application ## ================== times <. out$CP.data.time( out <-ccl4model(times. mg AAM = . 1). 6). ## 1.frame(ccl4model(times.15. by = .frame eventdat <. xlab = "Time (hours)". pch = c(1. NA).46) plot(ChamberConc ~ time.ccl4model y <.AI ## run the model: out <. legend = c("data". time = 1:6 . ccl4data$time)). AL = . 245. method = rep("add".frame(var = rep("AI".496. xlim = range(c( . events = list(data = eventdat)) )) . AT = . # area under the conc.Pm[["VCHC"]] . 2). CLT = . 951. AF = .c( AI = 21. lwd = c(NA. 9 . a conc of 2 is added to AI.VCH * Pm[["CONC"]] * Pm[["MW"]]/2445 y["AI"] <. "model")) ## ================================== ## An example with tracer injection ## ================================== ## every day. main = "ccl4model") for (cc in conc) { Pm["CONC"] <.data. lty = c(NA. 6). Pm. value = rep(1.cc VCH <.1) 11 ## initial inhaled concentration-calibrated conc <.c(26. lwd = 2) } legend("topright".as. # total mass . y.

y. Pm. but without including times that are very close to an event. a vector with the event times. eps = . lwd = 2) cleanEventTimes # 2. 4). mfrow = c(3. They are normally called internally within the solvers. . time = 1:6)) )) plot(out2. events = list(func = "eventfun". type = "l". mfrow=c(3. relative tolerance value below which two numbers are assumed to be numerically equal. Usage nearestEvent(times. lwd = 2) cleanEventTimes Find Nearest Event for Each Time Step and Clean Time Steps to Avoid Doubles Description These functions can be used for checking time steps and events used by ode solver functions. Details In floating point arithmetics.Machine$double. This means that all values of eventtimes are contained but only the subset of times that have no close neighbors in eventtimes. problems can occur if values have to be compared for ’equality’ but are only close to each other and not exactly the same.eps * 1 ) Arguments times eventtimes eps the vector of output times. implemented as a function in a DLL! print(system. type = "l".time( out2 <-ccl4model(times. These checks are normally performed internally by the integration solvers. The utility functions can be used to add all eventtimes to the output times vector. Value nearestEvent returns a vector with the closest events for each time step and cleanEventTimes returns a vector with the output times without all those that are ’very close’ to an event.12 plot(out. eventtimes) cleanEventTimes(times. 4). eventtimes.

nearest = nearest) ## typical usage: include all events in times after removing values that ## are numerically close together.5. 4. . Hindmarsh and Clement W. 25. 24. 1e3 )) times <. y) using a combination of backward differentiation formula (BDF) and a direct linear system solution method (dense or banded). 1 1.) or • a system of differential algebraic equations (DAE) of the form F (t.5. etc. use .. Peter N.daspk Author(s) Thomas Petzoldt See Also events Examples events <. 7. to call foreign code) or be defined in compiled code that has been dynamically loaded. . events)) newtimes 13 +5)) daspk Solver for Differential Algebraic Equations (DAE) Description Solves either: • a system of ordinary differential equations (ODE) of the form y = f (t. . 8 . y. 6. events have priority times unique_times <. 879.cleanEventTimes(times.C. 1:7.1e-1 .2. events) newtimes <. The R function daspk provides an interface to the FORTRAN DAE solver of the same name. of course. 1. 4 + 1e-1 .9999. 9.75.sort(c(unique_times.sort(c( . 25.. Brown. y ) = 0 or • a system of linearly implicit DAES in the form M y = f (t. 1e3.. 7 + 6e-15. 9.Call.sort(c( . 7 . 9. y.nearestEvent(times. 7. . 2.frame(times=times. The system of DE’s is written as an R function (which may. Ulrich. 1e3 nearest <. Petzold. events) data. written by Linda R. 5.Fortran.5. 3. Alan C.

hmax = NULL. Here t is the current time point in the integration. the names will be used to label the output matrix. the names will be available inside func. y)). parms dy res . If the initial values y has a names attribute.function(t. tcrit = NULL. times. time sequence for which output is wanted. it must be defined as: res <. fcontrol=NULL. if only one step is to be taken. forcings=NULL..). ipar = NULL. unless ynames is FALSE.function(t. initforc = NULL. rtol = 1e-6. func = NULL. to be used if the model is an ODE. Note that it is not possible to define func as a compiled function in a dynamically loaded shared library. . or a DAE written in linearly implicit form (M y’ = f(t. dy are the corresponding derivatives.. dy. maxsteps = 5 . estini = NULL. The return value of func should be a list. vector or list of parameters used in func. y ) of the DAE system (the model defininition) at time t. and whose next elements are global values that are required at each point in times. hini = . parms. lags = NULL. y is the current estimate of the variables in the ODE system. y. or a character string giving the name of a compiled function in a dynamically loaded shared library. res = NULL. . jacfunc = NULL. Ignored if an ODE. If res is a user-supplied R-function.... func must be defined as: func <. initfunc = dllname. ynames = TRUE. y. set times = NULL. hmin = . t is the current time point in the integration. bandup = NULL. y. The derivatives should be specified in the same order as the specification of the state variables y. nalg = .. rpar = NULL.. events = NULL. func should be an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. jacres = NULL. unless ynames is FALSE.. If the initial y or dy have a names attribute. the first value of times must be the initial time. whose first element is a vector containing the derivatives of y with respect to time. parms is a vector of parameters. maxord = 5. jacfunc.14 Usage daspk(y. (optional) are any other arguments passed to the function. outnames = NULL. nout = . the names will be available inside res. or res the initial derivatives of the state variables of the DE system. . dy = NULL. verbose = FALSE. parms. parms. mass = NULL. atol = 1e-8. parms is a vector or list of parameters. jactype = "fullint". if a DAE system: either an R-function that computes the residual function F (t.. y is the current estimate of the variables in the ODE system. banddown = NULL.) Arguments y times func daspk the initial (state) values for the DE system. initpar = parms. If y has a name attribute. Use res instead.). dllname = NULL.

dy) = 0). If the Jacobian is banded.e. y)). Only used in case the system is an ODE (y = f (t. i. setting estini = 1 or 2.e. will solve for them. If not NULL. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. an R function that computes the Jacobian of the system of differential equations. the names will be available inside jacres. "fullusr".e. See first example of lsode. The mass-matrix M should be of dimension n ∗ n where n is the number of y-values.. in this case. the problem is a linearly implicit DAE and defined as M dy/dt = f (t. If the initial y or dy have a names attribute. one value for each y. y is the current estimate of the variables in the ODE system. the calling sequence for jacres is identical to that of res. cj. the mass matrix. preceeded by the differential equations. unless ynames is FALSE. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices). then dllname must give the name of the shared library (without extension) which must be loaded before daspk() is called (see package vignette "compiledCode" for more information). y are the corresponding derivatives and cj is a scalar. y). jacfunc should return a matrix ∂ y/∂y. one of "fullint". y. one value for each y. specified by func. i. y. which is normally proportional to the inverse of the stepsize. the structure of the Jacobian. If the Jacobian is a full matrix.either full or banded and estimated internally or by the user. The R calling sequence for jacfunc is identical to that of func. F (t. y ). jacres and not jacfunc should be used if the system is specified by the residual function F (t. and if initial values of y and dy are not consistent (i. parms is a vector of parameters (which may have a names attribute). y.. jacres should return only the nonzero bands of the Jacobian. whose first element is a vector containing the residuals of the DAE system. If estini = 1: dy and the algebraic variables are estimated from y. If the Jacobian is banded. absolute error tolerance. "bandusr" or "bandint" . and whose next elements contain output variables that are required at each point in times. jacres should return the matrix dG/dy + cj · dG/dy . Here t is the current time point in the integration. Algebraic equations should always be the last. relative error tolerance.). if not NULL. where the ˙ ith row contains the derivative of dyi /dt with respect to yj . If mass=NULL then the model is either an ODE or a DAE. either a scalar or a vector. Thus it should be called as: jacres = func(t. specified with res only if a DAE system. If jacres is an R-function. If the Jacobian is a full matrix.e. Only used if estini = 1. parms. If res is a string. See details for the calling sequence when jacres is a string. where the ith row is the sum of the derivatives of Gi with respect to yj and the scaled derivatives of Gi with respect to dyj . y ). i. y. rotated row-wise. either a scalar or a vector.daspk 15 The return value of res should be a list. dy. the number of rtol atol jacfunc jacres jactype mass estini . but with extra parameter cj. nalg if a DAE system: the number of algebraic equations (equations not involving derivatives). rotated rowwise. jacres is used in conjunction with res. . δ = F (t.

Reduce maxord to save storage space ( <= 5) number of non-zero bands above the diagonal. present in the shared library. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll . if not NULL. If there is a time beyond which integration should not proceed (perhaps because of a singularity). an optional minimum value of the integration stepsize. hmax is set to the largest difference in times. the initial step size is determined by the solver logical.16 daspk algebraic equations must be given (nalg). names of state variables are not passed to function func. In special situations this parameter may speed up computations with the cost of precision. "bandusr") maximal number of steps per output interval taken by the solver.you have to perform this check in the code . as provided in ‘dllname’. See package vignette "compiledCode". will print the diagnostiscs of the integration . if FALSE. the FORTRAN routine daspk overshoots its targets (times points in the vector times). only used if ‘dllname’ is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function res. a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions referred to in res and jacres. C++). "bandusr") number of non-zero bands below the diagonal. only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by res and jacres.g. verbose tcrit if TRUE: full output to the screen. only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by res and jacres. initial step size to be attempted. the name of the initialisation function (which initialises values of parameters). to initialise the common blocks (FORTRAN) or global variables (C. e. will be recalculated to be at least 500 and a multiple of 500.see details. Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. the maximum order to be allowed. that should be provided in tcrit. if 0. If 0. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. in case the Jacobian is banded (and jactype one of "bandint". If not specified.See package vignette "compiledCode". no maximal size is specified. If estini = 2: y will be estimated from dy. and interpolates values for the desired time points. the solver will give a warning if more than 500 steps are taken. to avoid that the simulation possibly ignores short-term events. See package vignette "compiledCode". in case the Jacobian is banded (and jactype one of "bandint". but it will continue till maxsteps steps. hmin hmax hini ynames maxord bandup banddown maxsteps dllname initfunc initpar rpar ipar nout . this may speed up the simulation especially for large models.

as provided in ‘dllname’. they should satisfy F(T.e. forcings initforc fcontrol events lags . jactype = "bandusr": a banded Jacobian.value). y. additional arguments passed to func. This is one of: jactype = "fullint": a full Jacobian. It MUST be present if forcings has been given a value. jactype = "fullusr": a full Jacobian.. Y. res and jacres. . with (time. specified by user function jacfunc or jacres. Details The daspk solver uses the backward differentiation formulas of orders one through five (specified with maxord) to solve either: • an ODE system of the form y = f (t. See forcings or package vignette "compiledCode". if T. See forcings or package vignette "compiledCode". . The form of the Jacobian can be specified by jactype. See events for more information. the default. calculated internally by daspk. See timelags. y ) = 0 for y = Y and y’ = YPRIME. y will be estimated. YPRIME are the given initial values. if not NULL. If a DAE system..YPRIME) = 0. if consistent values are not known. jacfunc. max(times)] is done by taking the value at the closest data extreme. Values for Y and YPRIME at the initial time must be given as input. when estini = 2. or • a DAE system of the form F (t. A list that specifies events. To be used for delay differential equations. the number of steps that has to be kept..daspk outnames 17 only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function res. ODEs are specified in func. DAEs are specified in res. in many cases daspk can solve for them: when estini = 1. y’ and algebraic variables (their number specified with nalg) will be estimated.these values should be consistent. present in the shared library. interpolation outside the interval [min(times).Y. only used if ‘dllname’ is specified: a list with the forcing function data sets.. allowing this to be a generic function. when the value of a state variable is suddenly changed. These names will be used to label the output matrix. However. dede for more information. i.e. i. specified by user function jacfunc or jacres. The index of the DAE should be <=1. y.) for y = Y. See forcings or vignette compiledCode. Ideally. the name of the forcing function initialisation function. that is. the size of the bands specified by bandup and banddown. A list of control parameters for the forcing functions. A list that specifies timelags. each present as a two-columned matrix.

Author(s) Karline Soetaert <k. res and jacres may be defined in compiled C or FORTRAN code. and atol determine the error control performed by the solver. R. Hindmarsh. and L. Campbell. as well as in an R-function. S. There will be one row for each element in times unless the FORTRAN routine ‘daspk’ returns with an unrecoverable error. R. 40-91. If the request for precision exceeds the capabilities of the machine. pp. pp. Petzold.soetaert@nioo. E. S. More information about models defined in compiled code is in the package vignette ("compiledCode"). it will be used to label the columns of the output value. daspk will return an error code. the Krylov method is not (yet) supported. the diagnostics will written to the screen at the end of the integration. L. If verbose = TRUE. New York. Examples in both C and FORTRAN are in the ‘dynload’ subdirectory of the deSolve package directory. J. Models may be defined in compiled C or FORTRAN code. 1983. See package vignette "compiledCode" for details. Applied Mathematics and Computation. calculated by daspk. R. Brown and A. If y has a names attribute. A Description of DASSL: A Differential/Algebraic System Solver.). If jactype = "fullusr" or "bandusr" then the user must supply a subroutine jacfunc or jacres.18 daspk jactype = "bandint": a banded Jacobian. See lsoda for details. 1989. Stepleman et al. 31 (1989). Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func or res. Petzold. North-Holland.knaw. information about linking forcing functions to compiled code is in forcings. Elsevier. See package vignette "compiledCode" for details. P. 65-68. plus an additional column (the first) for the time value.nl> References L. as well as in an R-function. Amsterdam. the size of the bands specified by bandup and banddown. . Examples in FORTRAN are in the ‘dynload’ subdirectory of the deSolve package directory. See vignette("deSolve") for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. N. Brenan. C. (Eds. The input parameters rtol. If jactype = "fullusr" or "bandusr" then the user must supply a subroutine jacfunc. in Scientific Computing. K. The diagnostics of the integration can be printed to screen by calling diagnostics. Numerical Solution of Initial-Value Problems in Differential-Algebraic Equations. Reduced Storage Matrix Methods in Stiff ODE Systems. Note In this version.

Hindmarsh. diagnostics to print diagnostic messages. and L. • ode. • ode. and L. y. • ode. { ra <. Brown.org See Also • radau for integrating DAEs up to index 3. lsode. N. 15 (1994). for other solvers of the Livermore family. Petzold. pp. Netlib: http://www.function (t.D: subjected to equilibrium reaction D <. N. C. prod B is consumed at 1s-t order rate. vode. r Chemical problem formulation 1: ODE ======================================================================= ## Dissociation constant K <. A. pars) { with (as.ka/K *A*B # backward rate . SIAM J.1 ## parameters pars <. Using Krylov Methods in the Solution of LargeScale Differential-Algebraic Systems. lsodes. pars)). Consistent Initial Condition Calculation for Differential-Algebraic Systems. Comp.3D for integrating 3-D models. Brown.1D for integrating 1-D models. A.> A + B D is produced at a constant rate. C.netlib.daspk 19 P.list(c(y. • lsoda. Sci.ka*D # forward rate rb <.2D for integrating 2-D models. • rk. R. R. Examples ## ## ## ## ## ## ## ## ## ## ======================================================================= Coupled chemical reactions including an equilibrium modeled as (1) an ODE and (2) as a DAE The model describes three chemical species A. Petzold. August 1995.B. • ode.c( ka = 1e6. Hindmarsh. Comp. 1467-1488. P. prod = . lsodar. Sci.band for solving models with a banded Jacobian. submitted to SIAM J.. r = 1. LLNL Report UCRL-JC-122175.1) # forward rate Fun_ODE <. • ode for a general interface to most of the ODE solvers. • rk4 and euler for Runge-Kutta integrators.

f3). res2. pars)).-dD . In addition. pars) { with (as. pars) { with (as.list(c(y.r*B return(list(dy = c(dA.function (t.20 daspk ## rates of changes dD <.r*B ## and the equilibrium equation f3 <.dA + prod res2 <. y. yprime. pars)).r*B ## and the equilibrium equation eq <.ra . dB.K*D .A*B return(list(c(f1.ra . CONC = A+B+D)) }) } ## ## ## ## ## ## ## ## ======================================================================= Chemical problem formulation 2: DAE 1. CONC = A+B+D)) }) . CONC = A+B+D)) }) } ## ## ## ## ======================================================================= Chemical problem formulation 3: Mass * Func Based on the DAE formulation ======================================================================= Mass_FUN <.-dB + dA . yprime.rb . the equilibrium condition (eq) reads: as ra = rb : ka*D = ka/K*A*B = > K*D = A*B ======================================================================= Res_DAE <.function (t.prod f2 <.A*B return(list(c(res1. y. eq). get rid of the fast reactions ra and rb by taking linear combinations : dD+dA = prod (res1) and dB-dA = -r*B (res2) 2.-ra + rb + prod dA <.. f2. dD). { ## residuals of lumped rates of changes res1 <.rb dB <.list(c(y. but without the f1 <. { ## as above.K*D .

1.matrix(nrow = 3. parms = pars. atol = 1e-1 . B = 3. . NA).1] <. res = Res_DAE. ylab = "conc".2] <. parms = pars. pch = c(NA.-1*cj # d(res1)/d(D)-cj*d(res1)/d(dD) ## res2 = -dB + dA . 1)) legend("bottomright". times = times. rtol = 1e-1 ) MASS<.daspk(y = y. pars. legend = c("ODE". ncol = 3. dB = .A*B PD[3.3] <## eq = K*D . by = 2) 21 ## Initial conc. "p").B y <. byrow = TRUE.1] <. D is in equilibrium with A. # -dA + dB + .c(dA = . pars)). rtol = 1e-1 ) ## Initial rate of change dy <.function (t. 1. times=times. # dA + + dB -1. type = c("l". pch = c(NA. cj) { with (as. y. )) # algebraic times <. 1). yprime. D = 2*3/K) ## ODE model solved with daspk ODE <. dy = dy. col = c("black". dD = ) ## DAE model solved with daspk DAE <. lty = c(1.-1*cj # d(res1)/d(A)-cj*d(res1)/d(dA) PD[1.-B . .seq( . yprime.list(c(y.r*B PD[2. func = Fun_ODE.-r -1*cj PD[2.daspk } Mass <.1*cj PD[2.3] <. "red"). "DAE")) # difference between both implementations: max(abs(ODE-DAE)) ## ======================================================================= ## same DAE model. atol = 1e-1 . { ## res1 = -dD .c(A = 2. DAE. data=c(1. . times = times. xlab = "time". now with the Jacobian ## ======================================================================= jacres_DAE <.2] <# d(res1)/d(B)-cj*d(res1)/d(dB) PD[1.1] <. func = Mass_FUN. mass = Mass) ## ================ ## plotting output ## ================ plot(ODE.daspk(y = y. 1 .dA + prod PD[1.daspk(y=y. parms = pars.

seq( . ."Prod")) plot(ODE_dll. initfunc = "initparms".c(dA = . with production a forcing function ## ======================================================================= times <. nout = 2. ka = 1e6.e.K return(PD) }) } PD <. xlab = "time". . forcings = prod.daspk(y = y. nrow = 3. initforc = "initforcs". times = times.B y <."D")) dede General Solver for Delay Differential Equations.matrix(ncol = 2. times = times.-A PD[3. parms = pars. outnames = c("CONC".daspk(y = y. 1 . atol = 1e-1 . "conc"). dB = . dy = dy. rtol = 1e-1 . i. 1 . "D"). main = c("production rate". res = Res_DAE. jactype = "fullusr".3] <. D = as. atol = 1e-1 . dllname = "deSolve". r = 1) ## Initial conc. D is in equilibrium with A. ylab = c("/day". Description Function dede is a general solver for delay differential equations.c(A = 2.matrix(ncol = 3. equations where the derivative depends on past values of the state variables or their derivatives.double(2*3/pars["K"])) ## Initial rate of change dy <. by = 2) pars <. B = 3. which = c("Prod".22 PD[3. dy = dy. data = c(seq( .c(K = 1. by = 1 ).1*(1+runif(11)*1))) ODE_dll <. jacres = jacres_DAE. parms = pars. rtol = 1e-1 ) max(abs(DAE-DAE2)) ## See \dynload subdirectory for a FORTRAN implementation of this model ## ======================================================================= ## The chemical model as a DLL. ) dede DAE2 <. res = "chemres".2] <. dD = ) # production increases with time prod <.

. whose first element is a vector containing the derivatives of y with respect to time. the default is 1e4 and (2) how to interpolate. but relies on the integrator to control the stepsize in the region of a discontinuity. "lsodar". method = c( "lsoda". parms method control ..). "impAdams".. If y has a name attribute. and whose next elements are global values that are required at each point in times. "lsodes". a list that can supply (1) the size of the history array. Details Functions lagvalue and lagderiv are to be used with dede as they provide access to past (lagged) values of state variables and derivatives. t is the current time point in the integration. the first value of times must be the initial time. a vector. "radau"). . then func can be NULL. .) Arguments y times func 23 the initial (state) values for the DE system. control = NULL.The derivatives should be specified in the same order as the state variables y. a more accurate interpolation method can be triggered by setting control$interpol = 2. as control$interpol. y is the current estimate of the variables in the DE system. "daspk". "radau") or a function that performs the integration. "lsode".dede Usage dede(y. The default integrator used is lsoda. "vode". the names will be available inside func. func must be defined as: func <. using the Nordsieck history array. 2 is variable order interpolation. where 1 is hermitian interpolation. .. parameters passed to func. "impAdams". The default value (if unspecified) is 1e4.. as control$mxhist. either a string ("lsoda". "adams". "bdf". For methods adams. can be specified in control$mxhist. y. times. the names will be used to label the output matrix. Only for the two Adams methods is the second option recommended. func=NULL. "lsode". additional arguments passed to the integrator. parms. The number of past values that are to be stored in a history matrix.. "adams".function(t.. impAdams. time sequence for which output is wanted. parms. The return value of func should be a list. "lsodar". "vode". "daspk". an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. . If method "daspk" is used. If the initial values y has a names attribute.. Cubic Hermite interpolation is used by default to obtain an accurate interpolant at the requested lagged time. (optional) are any other arguments passed to the function. parms is a vector or list of parameters. the integrator to use. dede does not deal explicitly with propagated derivative discontinuities. "bdf". in which case res should be used. "lsodes".

. lagderiv. or lsode.seq( . dde can simultaneously locate a root.-1 else dy <. parms) { if (t < 1) dy <. See last example.1) ##----------------------------## solve the model ##----------------------------yout <. although in some cases it may be possible to solve such models. Examples ## ## ## ## ============================================================================= A simple delay differential equation dy(t) = -y(t-1) . plus an additional column (the first) for the time value. If y has a names attribute. y.soetaert@nioo. func = derivs. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the second element of the return from func.for how to specify lagged variables and derivatives. Author(s) Karline Soetaert <k.function(t. it will be used to label the columns of the output value.1 times <.lagvalue(t . There will be one row for each element in times unless the integrator returns with an unrecoverable error. and trigger an event. parms = NULL) . For these reasons.. 3 .knaw. it can only solve rather simple delay differential equations.1) list(c(dy)) } ##----------------------------## initial values and times ##----------------------------yinit <.dede(y = yinit.nl> See Also lagvalue. When used together with integrator lsodar. y(t< )=1 ============================================================================= ##----------------------------## the derivative function ##----------------------------derivs <.24 dede dede does not include methods to deal with delays that are smaller than the stepsize. times = times.

type = "l". lty = 1. times = times. dy2.1. example 4 from Shampine and Thompson.dede(y = yinit.-y[1] * lag1 + lag1 dy2 <.dede ##----------------------------## display.function(t.1 else lag1 <.2) dy1 <.1.-1].y[2] dy3 <.lag1 list(c(dy1. 4 . plot results ##----------------------------matplot(yout[. by = . lwd = 2.c(5.1 .. main = "Infectuous disease . yout[.lagvalue(t .Hairer") ## ## ## ## ============================================================================= time lags + EVENTS triggered by a root function The two-wheeled suitcase model example 8 from Shampine and Thompson.1].time( yout <. 2 .lagvalue(t . . 1) times <. lwd = 2. type = "l". two lags. parms = NULL) ) ##----------------------------## display.1 else lag1 <.. dy3)) } ##----------------------------## initial values and times ##----------------------------yinit <.seq( .y. main = "dy/dt = -y(t-1)") ## ## ## ## ## ============================================================================= The infectuous disease model of Hairer.y[2] . 2 solving delay differential equations with dde23 ============================================================================= 25 ##----------------------------## the derivative function ##----------------------------derivs <. plot results ##----------------------------plot(yout.2) if (t < 1 ) lag1 <.y[1] * lag1 . func = derivs.parms) { if (t < 1) lag1 <.1) ##----------------------------## solve the model ##----------------------------system.

bet = 1.function(t.y[2] dy2 <. func = derivs. ## e.1.c(y = . method = "lsodar". return(y).y. mu = asin(gam/A) ##----------------------------## initial values and times ##----------------------------yinit <. y[2]* . main = "suitcase model".tau) dy1 <. mfrow = c(1.2)) plot(yout[. ylab = "dy". plot results ##----------------------------plot(yout. len = 1 ) ##----------------------------## solve the model ##----------------------------## Note: use a solver that supports both root finding and events.dede(y = yinit. times = times.seq( .26 diagnostics ## solving delay differential equations with dde23 ## ============================================================================= ##----------------------------## the derivative function ##----------------------------derivs <.bet * lag[1] + A * sin(omega * t + mu) list(c(dy1. 12.-sign(y[1]) * gam * cos(y[1]) + sin(y[1]) .75 diagnostics Print Diagnostic Characteristics of Solvers . lsodar.parms) ifelse(t> . lwd = 2. parms = NULL.function(t. rootfun = root. lsode. bdf yout <. lsoda. dy2)) } ## root and event function root <. A = omega = 1.248.2]. y.37. adams.931)) gam = .y.function(t. yout[. lwd = 2) .3]. return(1)) event <. xlab = "y". parms) { if (t < tau) lag <else lag <. type = "l". which = 1.parms) return(c(y[1].lagvalue(t . type = "l". root = TRUE)) ##----------------------------## display.g. dy = ) times <. events = list(func = event. tau = .

Full = FALSE. including the ones that are not relevant for the solver. Details Detailed information obout the success of a simulation is printed.. Usage ## S3 method for class ’deSolve’ diagnostics(obj.. If FALSE. Usage diagnostics(obj.diagnostics. the last step size.. optional arguments allowing to extend diagnostics as a generic function. A warning is printed. . if a diagnostics function exists for a specific solver routine.) Arguments obj Full ..... See Also diagnostics. when TRUE then all messages will be printed. number of steps taken. . the last step size. then only the relevant messages will be printed. e.) ## Default S3 method: diagnostics(obj.. . is the output matrix as produced by one of the integration routines... Please consult the class-specific help page for details. . . .. diagnostics.deSolve Print Diagnostic Characteristics of ODE and DAE Solvers Description Prints several diagnostics of the simulation to the screen..deSolve for diagnostics of differential equaton solvers.. number of steps taken.deSolve Description 27 Prints several diagnostics of the simulation to the screen. e.g..g. is an output data structure produced by one of the solver routines.) Arguments obj . optional arguments allowing to extend diagnostics as a generic function. if no class-specific diagnostics exists.

{ dx dy dz <.z) <.-x * y + 28 * y . ipar = NULL. parameters) { with(as. chaos <. forcings = NULL.") diagnostics(out) ) DLLfunc Evaluates a Derivative Function Represented in a DLL Description Calls a function.28 Details DLLfunc When the integration output is saved as a data. z = 1) times <.z list(c(dx. 5 . Examples ## The famous Lorenz equations: chaos in the earth’s atmosphere ## Lorenz 1963. Note: the number of function evaluations are *without* the extra calls performed to generate the ordinary output variables (if present). state. nout = . times. Value The integer and real vector with diagnostic values. chaos.frame. dz)) }) } state <. y. See tables 2 and 3 in vignette("deSolve") for what these vectors contain. dllname. 1) out <. times. 13 -141. dy.seq( . initforc = NULL. Sci. Atmos. fcontrol = NULL) . J.-1 * (y . 2 . then the required attributes are lost and method diagnostics will not work anymore. . defined in a compiled language as a DLL Usage DLLfunc(func. outnames = NULL.c(x = 1.function(t. y = 1. pch = ". pairs(out. parms.list(c(state)). rpar = NULL.vode(state.-8/3 * x + y * z <. for function lsodar also the root information. initfunc = dllname.

the parameters that are passed to the initialiser function. See details. See package vignette "compiledCode". A list of control parameters for the forcing functions.soetaert@nioo. max(times)] is done by taking the value at the closest data extreme. initforc fcontrol Details This function is meant to help developing FORTRAN or C models that are to be used to solve ordinary differential equations (ODE) in packages deSolve and/or rootSolve. only used if ‘dllname’ is specified: a list with the forcing function data sets.knaw. the name of the forcing function initialisation function. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. via function argument ipar. See package vignette "compiledCode". . first value = the time at which the function needs to be evaluated. value). a string giving the name of the shared library (without extension) that contains the compiled function or subroutine definitions referred to in func. if not NULL.DLLfunc Arguments func times y parms dllname initfunc rpar ipar nout outnames forcings the name of the function in the dynamically loaded shared library. a vector with integer values passed to the dll-function func and jacfunc present in the DLL. It MUST be present if forcings has been given a value. with (time. See package vignette "compiledCode". the number of output variables. the ordinary output variables of the function. as provided in ‘dllname’. each present as a two-columned matrix. present in the shared library. if not NULL. via argument rpar.nl> the rate of change estimated by the function. the name of the initialisation function (which initialises values of parameters). a vector with double precision values passed to the DLL-function func and jacfunc present in the DLL. Value a list containing: dy var Author(s) Karline Soetaert <k. 29 the values of the dependent variables for which the function needs to be evaluated. as provided in ‘dllname’. interpolation outside the interval [min(times).

AAM = . outnames = c("Mineralisation". 5. . 1 * 6 DLLres Evaluates a Residual Derivative Function Represented in a DLL . 3. . times=1. 2. CLT = . 1. 4321671. 13. func = "scocder".654. . 16.3. AT = . dllname = "deSolve". nout = 2. 5. 281. byrow = TRUE. data = c(1. . .182. initfunc = "initccl4". AL = .matrix(ncol = 2. 153. AF = . .c( . parms = parms.4 27255. .74. . .167)) . parms = Parms. 2. outnames = c("Mineralisation".to see the FORTRAN code: ========================================================================== ## Forcing function "data" Flux <. "Depo")) . AM = ) ## the rate of change DLLfunc(y = yini. outnames = c("DOSE". func = "scocder".8.654 DLLfunc(y = Yini. 4. 2 SCOC model. 8. parms <.c(k = . "CP") ) ## ## ## ## ========================================================================== ex. in fortran . "MASS". forcings = Flux. 1 ccl4model ========================================================================== Parameter values and initial conditions see example(ccl4model) for a more comprehensive implementation DLLres Parms <.48. 1) Yini <.15. 16. 4.k * y = .17."Depo")) ## correct value = dy = flux . initfunc = "scocpar". 4. nout = 2. initforc = "scocforc". forcings = Flux. . initfunc = "scocpar". parms = parms. times = 2.6 DLLfunc(y=Yini. initforc = "scocforc". dllname = "deSolve". dllname = "deSolve". .c(AI = 21.487. .30 See Also ode for a general interface to most of the ODE solvers Examples ## ## ## ## ## ## ========================================================================== ex. times = 1. func = "derivsccl4". . nout = 3.32.8) yini <.17. 1 .

y ) of a DAE system (differential algebraic equations) defined in a compiled language as a DLL. See package vignette "compiledCode". the derivative of the values of the dependent variables for which the function needs to be evaluated. times. y. if not NULL. the name of the initialisation function (which initialises values of parameters). outnames = NULL.DLLres Description 31 Calls a residual function. interpolation outside the interval [min(times). if not NULL. the number of output variables. A list of control parameters for the forcing functions. parms. as provided in ‘dllname’. To be used for testing the implementation of DAE problems in compiled code Usage DLLres(res. See package vignette "compiledCode". forcings = NULL. present in the shared library. nout = . only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. fcontrol = NULL) Arguments res times y dy parms dllname initfunc rpar ipar nout outnames forcings the name of the function in the dynamically loaded shared library. y. each present as a two-columned matrix. F (t. It MUST be present if forcings has been given a value. a string giving the name of the shared library (without extension) that contains the compiled function or subroutine definitions referred to in func. as provided in ‘dllname’. initfunc = dllname. the name of the forcing function initialisation function.value). dllname. via function argument ipar. initforc = NULL. dy. a vector with integer values passed to the DLL-function func and jacfunc present in the DLL. with (time. ipar = NULL. only used if ‘dllname’ is specified: a list with the forcing function data sets. See details. the values of the dependent variables for which the function needs to be evaluated. initforc fcontrol . max(times)] is done by taking the value at the closest data extreme. See package vignette "compiledCode". via argument rpar. the parameters that are passed to the initialiser function. a vector with double precision values passed to the DLL-function func and jacfunc present in the DLL. rpar = NULL. first value = the time at which the function needs to be evaluated.

data = c(seq( .32 Details DLLres This function is meant to help developing FORTRAN or C models that are to be used to solve differential algebraic equations (DAE) in package deSolve. dllname = "deSolve". len = 11))) DLLres(y = y. ka = 1e6.c(dA = .c(K = 1.1. parms = pars. "Prod")) . nout = 2. dy = dy. by = 1 ).nl> See Also daspk to solve DAE problems Examples ## ## ## ## ## ========================================================================= Residuals from the daspk chemical model. initfunc = "initparms". production a forcing function ========================================================================= Parameter values and initial conditions see example(daspk) for a more comprehensive implementation pars <.soetaert@nioo. dD = ) ## production increases with time prod <.matrix(ncol = 2. B = 3. initforc = "initforcs". r = 1) ## Initial conc.c(A = 2.5. res = "chemres". . 1 . outnames = c("CONC". Value a list containing: res var the residual of derivative estimated by the function the ordinary output variables of the function Author(s) Karline Soetaert <k.B y <. dB = . times = 5. forcings = prod. D is in equilibrium with A.knaw. seq( . D = 2 * 3/pars["K"]) ## Initial rate of change dy <.

(optional) . time: when events are specified by an event function: the times at which the events take place.frame are "ordered".. 6.frame that specifies the state variables. times. as specified by a data. In terminalroot. e. the default is "notordered". events can be imposed by means of an input data. By default when a root is found.g. maxroot: when root = TRUE. . data: a data. func: an R-function or the name of a function in compiled code that specifies the event. In case the events are specified by means of an R function (argument events$func).). this logical should be set equal to TRUE 5. As from version 1. the default is that the simulation continues after the event is executed. set to "ordered". subtracted. Note that these event times must also be part of the integration output times exactly. . parms is a vector or list of parameters. because a value is added.9. terminalroot when events are triggered by a root.1 this is checked by the solver. defaults to 100. 7.9. y is the current estimate of the variables in the ODE system. Typically these events occur only at specific times.. else the event will not take place. The integration routines cannot deal easily with such state variable changes. Roots occur when a root function becomes zero. it must be defined as: function(t.1.. and a warning message is produced if event times are missing in times. If the initial values y has a names attribute. root: when events are specified by a function and triggered by a root. t is the current time point in the integration. parms. the names will be available inside events$func. ties: if events. the maximal number of times at with a root is found and that are kept.frame. this is checked by the solver. As from version 1.. This will save some computational time. Note that the event times must also be part of the integration output times. or triggers an event. values and types of the events. Details The events are specified by means of argument events passed to the integration routines. we can specify which roots should terminate the simulation. Description An event occurs when the value of a state variable is suddenly changed. or via an event function. 2. or multiplied. In deSolve. else the event would not take place. and an error message produced if event times are missing in times. 3. y. the simulation either stops (no event). see also cleanEventTimes for utility functions to check and solve such issues.events 33 events Implementing Events and Roots in Differential Equation Models. that specifies at which time and how a certain state variable is altered. 4. then only the first maxroot will be outputted. see also cleanEventTimes for utility functions to check and solve such issues. If the number of roots > maxroot. events should be a list that contains one of the following: 1.

For the first 3 integration methods. the root finding algorithm is based on the algorithm in solver LSODAR. e. the solvers will check if the time is embraced by the simulation time 3. See package vignette "compiledCode" for more details.34 events are any other arguments passed to the function via the call to the integration method. then the output will have attribute troot which will contain the times at which a root was found (and the event trigerred). and roots are found. and it works slightly different. also allowed is to specify the number (1 = replace. and radau.9. the model must be solved with an integration routine with root-finding capability The root function itself should be specified with argument rootfunc. If this is not desirable. the time. magnitude of the event 4. for more examples of roots . lsode. also see example of ccl4model. a vector as defined in events$time OR the specification of a root function. because we want to record the position of many roots. and the state variable vector. while other problems are more efficiently solved with radau. "multiply"). or lsodes. The default is 100. the root solving algorithm is written in C-code. this should contain the following columns (and in that order): 1. some problems involving roots may be more efficiently solved with either lsoda. Author(s) Karline Soetaert. called "v1" at time = 1 . method which event is to take place. 2 = add. The event function should return the y-values (some of which modified). var the state variable name or number that is affected by the event 2. There will be at most events$maxroot such values. and is implemented in FORTRAN. then a dummy "event" function can be defined which returns the values of the state variables . this requires either: input of the time of the events. In this case. lsodar. In case events are specified by an R-function. If roots and events are combined. "add". This function has as arguments. for how to implement forcing functions.1 the following routines have root-finding capability: lsoda. time the time at which the event is to take place. lsodes. the following line "v1" 1 2 "add" will cause the value 2 to be added to a state variable. If events$func is a string.unaltered. From deSolve version 1. Thus.g. If a root function is defined. See two last examples. lsode. this indicates that the events are specified by a function in compiled code. the integrator is informed that the simulation it to be continued after a root is found by setting events$root equal to TRUE. In the latter case. See Also forcings. then by default the solver will stop at a root. value the value. should be one of ("replace". as a vector. For radau. If the evenst are specified by a data frame (argument events$data). but not an event function. 3 = multiply) For instance. the number of state variables.

y = yini.ode(func = derivs. "v2".v1 + 1 v2 <.frame(var = c("v1". 1.data. "mult". "add")) eventdat out <. EVENTS in a function ## ============================================================================= ## derivative function: rate of change v1 = derivs <. var. v2 reduced at first-order rate 35 # events: add 1 to v1. 2 )) eventdat out <.5 * var[2])) } . by = . y = yini.{ v1 <. parms){ with (as.function(t. 1:1 ). times = times. events = list(data = eventdat)) plot(out) ## eventdat <.1) eventdat <.list(y). multiply v2 with random number eventfun <.frame ## ============================================================================= ## derivative function: derivatives set to derivs <. value = c(1.function(t. .frame(var = c(rep("v1". "rep". parms = NULL. 1 )). var.data.c(v1 = 1. parms) { list(c( .events Examples ## ============================================================================= ## 1. method = rep("add". time = c(1. events = list(data = eventdat)) plot(out) ## ============================================================================= ## 2. 5. rep("v2".seq( .vode(func = derivs. 2. 1 ). parms) { list(dvar = rep( . v2)) }) . times = times. 9) . 3. 1 . "v1"). time = c(1:1 . value = runif(2 ). 2)) } yini <. "v2".5 * runif(1) return(c(v1.. parms = NULL. EVENTS in a data. y. v2 = 2) times <.function(t. 4). method = c("add".

out <. pars) { return(y . p) x[2] . y. x. pars) { return(list(. . parms = NULL. parms = NULL. p ) list(c( x[2].2 times <. events = list(func = eventfun.function(t.function(t.1) out <. v2 = 2) times <. root = TRUE specifies that the event is ## triggered by a root.function(t. by = .seq( .. EVENTS triggered by a root function ## ============================================================================= ## derivative: simple first-order decay derivs <. x.c(v1 = 1. type = "l") ## time of the root: troot <. 1 .ode(times = times..function(t.36 } yini <. root = TRUE). rootfun = rootfun) plot(out. pars) { return(y = 1) } yini <.attributes(out)$troot points(troot.function (t. type = "l") ## ============================================================================= ## 3.5) } ## sets state variable = 1 eventfun <. More ROOT examples: Rotation function ## ============================================================================= Rotate <.1 * y)) } ## event triggered if state variable = rootfun <. func = derivs. y = yini. length(troot))) ## ============================================================================= ## 4. time = 1:9) ) plot(out. -x[1] )) ## Root = when second state variable = rootfun <.ode(func = derivs.1) ## uses ode to solve. times = times. 1 . y = yini. y.5 events .seq( . events = list(func = eventfun.5. y. rep( .

5) event3 <. parms = times = times. y = c(x1 = 5. rootfun = root3. Stop at 5th root . root = TRUE. by = . cex = 2) ## Multiple roots and stop at first time root 1.function(t. method = "radau". rep( . events = list(func = eventfun.ode(func = Rotate. length (troot)). x. rootfun = root2. p) x out2 <.attributes(out2)$indroot # which root was found points(troot. which = 2) troot <.seq( . ## 2.ode(func = Rotate. nroot = ). y = c(5. terminalroot = 2)) . . parms = .only works with radau. root = TRUE) ) plot(out) troot <. x2 = 5. 5). 5).function (t. pch = 18. root = TRUE.attributes(out)$troot # time of roots points(troot.ode(func = Rotate. p) c(x[2]. times = times. rootfun = rootfun) tail(out1) . events = list(func = event3. x. out3 <. times = times. times = times. y = c(5. p ) list(c( x[2].ode(func = Rotate. Continues till end of times and records the roots out <. col = indroot.ode(func = Rotate. x. rootfun = root2.rep( . times = times.function(t. rootfun = rootfun. x[3] . p) x times <. parms = .seq(from = . parms = . y = c(5.events 37 ## "event" returns state variables unchanged eventfun <. root = TRUE) ) plot(out2. events = list(func = eventfun. terminalroot = 1)) ## ============================================================================= ## 5.function(t. x. x[3]+1) times <. No event: stops at first root out1 <. )) ## Root = when second state variable = root3 <.function(t. to = 15.1) ## 1. ## ============================================================================= Rotate <.1) out3 <. -x[1]. y = c(5. parms = . length (troot))) ## Multiple roots: either one of the state variables = root2 <. x. events = list(func = eventfun. 15.attributes(out2)$troot indroot <. 5). 5). p) c(x[1:2].

This is the compiled-code equivalent of approxfun or approx. to interpolate at the current timestep. using R’s approxfun. it is most efficient to: 1. if a model uses forcing variables. define a function that performs the linear interpolation. If the model is defined in R code.f) + y1 * f so that f = is right-continuous and f = 1 is left-continuous. . max(times)]. such as to allow extrapolation outside of the time interval. Note that the default differs from the approx default. If y and y1 are the values to the left and right of the point then the value is y * (1 . as these may exceed the last time point. as well as in R. "nroot". If rule is 1 then an error will be triggered and the calculation will stop if times extends the interval of the forcing function data set. Thus.and right-continuous step functions. it is imposed as a time-series. a warning will be printed if verbose is TRUE. If it is 2. Rather. "indroot")] forcings forcings Passing Forcing Functions to Models Written in R or Compiled Code. f For method = "constant" a number between and 1 inclusive. the value at the closest data extreme is used. as provided in ‘dllname’. In this case: 1. while 3. initforc is the name of the forcing function initialisation function. Models may be defined in compiled C or FORTRAN code. It is generally recommended to use rule = 2. 2. Choices are "linear" or "constant". Details The forcing functions are imposed as a data series. Description A forcing function is an external variable that is essential to the model. indicating a compromise between left. the forcing function data series is provided by means of argument forcings. the default. rule an integer describing how interpolation is to take place outside the interval [min(times). especially when using the Livermore solvers. fcontrol is a list used to finetune how the forcing update should be performed. The fcontrol argument is a list that can supply any of the following components (conform the definitions in the approxfun function): method specifies the interpolation method to be used. their value at each time point needs to be estimated by interpolation of a data series. call this function within the model’s derivative function.38 plot(out3) attributes(out3)[c("troot". See first example. but not explicitly modeled. 2. that contains the values of the forcings at specified times. it is possible to use deSolves forcing function update algorithm. If the models are defined in compiled C or FORTRAN code.

2 2.345. ties = "ordered") Note that only ONE specification is allowed.439.3 9. . Alternative values for ties are mean. Note How to write compiled code is described in package vignette "compiledCode".254.1 3. 91. if the dataset is not ordered.893. .143. f = . 41. 1. . Author(s) Karline Soetaert. .183. . in the C code this will mean that -if ties exist. . . then nonsense will be produced.3 4.4 4. 83.923. Woodrow Setzer (Maintainer) See Also approx or approxfun. 93.28 .193.365. min etc The defaults are: fcontrol = list(method = "linear".737. 214.277.772. .matrix(ncol=2. .1. . .127. Note that the default is "ordered". rule = 2.1.data=c( 1. 234. 113. 173. 1) . This vignette also contains examples on how to pass forcing functions. 1.767.123.163. which should be referred to for details.726.224.1.691. .1.889.231.654. . More information about models defined in compiled code is in the package vignette ("compiledCode"). R. .byrow=TRUE.599.1.135)) parms <. 153.c(k= . 294.186. 335.681.226. .forcings 39 ties Handling of tied times values. .255.194. .168.R-code: ## ============================================================================= ## Forcing function data Flux <.286.355.624.264.1.284 . the R function.133.996. . 1. 73. even if there is more than one forcing function data set.325. 11. hence the existence of ties will NOT be investigated. . 274.244. . 7 . . .315. .167. Either a function with a single vector argument returning a single number result or the string "ordered".2 4.14 . the first value will be used. 21. Thomas Petzoldt. 6 . . Examples ## ============================================================================= ## FORCING FUNCTION: The sediment oxygen consumption example . . events for how to implement events. 1.

which = "depo". Flux = Flux. type = "l". rule = 2) Out2 <. now constant interpolation Depo <.5.SCOC(times. func = sediment. col = "red") lines(out[.par(mfrow = c(2.ode(times = times."Depo"].1]. lwd = 2) ## ============================================================================= ## SCOC is the same model. 1)) plot (Out. y = c(O2 = 63).SCOC(times."O2"]. parms = parms) ## same forcing functions. Flux = Flux) plot(out[."time"]. out[. type = "l". rule = 2 avoids NaNs in interpolation Depo <. Out2[. as implemented in FORTRAN ## ============================================================================= out<. k) list (c(Depo(t) . col = "blue") ## Constant interpolation of forcing function . out2[. rule = 2) Out <. method = "linear".ode(times = times. type = "l".1:365 ## the model sediment <.1]."depo"].approxfun(x = Flux[. out[."time"]. func = sediment. method = "constant". depo = Depo(t)) # the forcing functions."Mineralisation"].function( t. col = "red". y = c(O2 = 63)."time"]. lwd = 2) plot (Out. col = "red". parms = parms) mf <."Depo"]."Mineralisation"]. which = "O2". col = "red") lines(out2[. lwd = 2. type = "l". mfrow = NULL) lines(Out2[."time"]. parms = parms.list(method = "constant") out2 <. col = "blue") forcings ## ## ## ## Not run: ============================================================================= show examples (see respective help pages for details) ============================================================================= example(aquaphy) ## show package vignette with tutorial about how to use compiled models ## + source code of the vignette ## + directory with C and FORTRAN sources vignette("compiledCode") . fcontrol = fcontrol) plot(out2[.left side of interval fcontrol <. y = Flux[. parms = parms.2].2].k * O2)."time"].approxfun(x = Flux[. Out2[. O2."time"]. out2[. lwd = 2. y = Flux[. f = .40 times <. mfrow = NULL) lines(Out2[.

The R function lsoda provides an interface to the FORTRAN ODE solver of the same name. . . The system of ODE’s is written as an R function (which may. parms. forcings = NULL. dllname = NULL.. func. lags = NULL. rtol = 1e-6. maxords = 5. or for parameter estimation using any appropriate modeling tool for non-linear models in R such as optim. verbose = FALSE.lsoda edit(vignette("compiledCode")) browseURL(paste(system. etc. sep = "")) ## End(Not run) 41 lsoda Solver for Ordinary Differential Equations (ODE). hmin = . ynames = TRUE.. fcontrol = NULL. tcrit = NULL. to call foreign code) or be defined in compiled code that has been dynamically loaded.file(package = "deSolve"). maxsteps = 5 . maxordn = 12. jactype = "fullint". The first value in times must be the initial time. banddown = NULL. atol = 1e-6.) Arguments y times the initial (state) values for the ODE system. hmax = NULL. so the solver may be used as part of a modeling package for ODEs.Fortran. If y has a name attribute. hini = . Hindmarsh. nroot = . This means that the user does not have to determine whether the problem is stiff or not. initfunc = dllname. It always starts with the nonstiff method. times at which explicit estimates for y are desired. events = NULL. written by Linda R. rpar = NULL. A vector of parameters is passed to the ODEs. jacfunc = NULL. rootfunc = NULL.Call. nlm or nlme lsoda differs from the other integrators (except lsodar) in that it switches automatically between stiff and nonstiff methods. bandup = NULL. times. use . nout = . Usage lsoda(y. initpar = parms. of course. the names will be used to label the output matrix. Petzold and Alan C. and the solver will automatically choose the appropriate method. .C. nls. ipar = NULL... initforc = NULL. "/doc". Switching Automatically Between Stiff and Non-stiff Methods Description Solving initial value problems for stiff or non-stiff systems of first-order ordinary differential equations (ODEs). outnames = NULL.

and whose next elements are global values that are required at each point in times. then lsodar will be called. rootfunc should return a vector with the function values whose root is sought.. If the Jacobian is banded.see details. absolute error tolerance.g. parms. either a scalar or an array as long as y. The R calling sequence for rootfunc is identical to that of func. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices). If the Jacobian is a full matrix. rotated row-wise. See package vignette "compiledCode" for more details. "bandusr" or "bandint" .42 func lsoda either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t.. parms is a vector or list of parameters. jacfunc should return a matrix ∂ y/∂y. if the system is stiff. If there is a time beyond which integration parms rtol atol jacfunc jactype rootfunc verbose nroot tcrit .. y is the current estimate of the variables in the ODE system. e.). only used if ‘dllname’ is specified: the number of constraint functions whose roots are desired during the integration. the structure of the Jacobian. If the initial values y has a names attribute. When rootfunc is provided. if not NULL. See details. if rootfunc is an R-function. or a string giving the name of a function or subroutine in ˙ ‘dllname’ that computes the Jacobian (see vignette "compiledCode" for more about this option). See first example of lsode. the names will be available inside func. supplying jacfunc can speed up the computations. The derivatives should be specified in the same order as the state variables y. then lsoda cannot integrate past tcrit. vector or list of parameters used in func or jacfunc. "fullusr". The return value of func should be a list. it must be defined as: func <. whose first element is a vector containing the derivatives of y with respect to time. where the ˙ ith row contains the derivative of dyi /dt with respect to yj . or a character string giving the name of a compiled function in a dynamically loaded shared library. if not NULL. y. and interpolates values for the desired time points. (optional) are any other arguments passed to the function. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. If func is a string. then dllname must give the name of the shared library (without extension) which must be loaded before lsoda() is called. If func is an R-function. one of "fullint". relative error tolerance. an R function that computes the function whose root has to be estimated or a string giving the name of a function or subroutine in ‘dllname’ that computes the root function. the solver estimates the number of roots. The R calling sequence for jacfunc is identical to that of func. See details. In some circumstances. if not NULL. . that computes the Jacobian of the system of differential equations ∂ yi /∂yj .. will print the diagnostiscs of the integration . if TRUE: full output to the screen.. The FORTRAN routine lsoda overshoots its targets (times points in the vector times).function(t. either a scalar or an array as long as y. an R function.either full or banded and estimated internally or by user. t is the current time point in the integration.

value). a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. to initialise the common blocks (FORTRAN) or global variables (C. Should be <= 5. initial step size to be attempted. as provided in ‘dllname’.lsoda 43 should not proceed (perhaps because of a singularity). only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. See package vignette "compiledCode". if FALSE: names of state variables are not passed to function func. each present as a two-columned matrix. only used if ‘dllname’ is specified: a list with the forcing function data sets. if 0. the initial step size is determined by the solver. in case the Jacobian is banded.you have to perform this check in the code. present in the shared library. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. hmax is set to the largest difference in times. logical. that should be provided in tcrit. maximal number of steps per output interval taken by the solver. no maximal size is specified. the name of the initialisation function (which initialises values of parameters). to avoid that the simulation possibly ignores short-term events. Reduce maxord to save storage space. this may speed up the simulation especially for large models. if not NULL. the maximum order to be allowed in case the method is stiff. Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. See package vignette "compiledCode". hmax hini ynames maxordn maxords bandup banddown maxsteps dllname initfunc initpar rpar ipar nout outnames forcings . Reduce maxord to save storage space. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll . Should be <= 12. See package vignette "compiledCode". interpolation outside the interval [min(times). in case the Jacobian is banded. hmin an optional minimum value of the integration stepsize. If not specified. number of non-zero bands above the diagonal. In special situations this parameter may speed up computations with the cost of precision. These names will be used to label the output matrix. See forcings or package vignette "compiledCode". only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. with (time. present in the shared library. C++). max(times)] is done by taking the value at the closest data extreme. number of non-zero bands below the diagonal. the maximum order to be allowed in case the method is non-stiff. If 0.

the size of the bands specified by bandup and banddown. If verbose = TRUE. the name of the forcing function initialisation function. the FORTRAN subroutine lsoda will return an error code. as provided in ‘dllname’. calculated by lsoda. The solver will control the vector e of estimated local errors in y. "bandusr" a banded Jacobian. If jactype = "fullusr" or "bandusr" then the user must supply a subroutine jacfunc. . according to an inequality of the form max-norm of ( e/ewt ) ≤ 1.. where ewt is a vector of positive error weights. i. A list that specifies timelags. "bandint" banded Jacobian. The implementation is based on the 12 November 2003 version of lsoda. additional arguments passed to func and jacfunc allowing this to be a generic function. dede for more information. Details All the hard work is done by the FORTRAN subroutine lsoda. whose documentation should be consulted for details (it is included as comments in the source file ‘src/opkdmain. specified by user function jacfunc the size of the bands specified by bandup and banddown. specified by user function jacfunc. the diagnostics will written to the screen at the end of the integration. the default.f’). To be used for delay differential equations. fcontrol events lags . It always starts with the nonstiff method. from Netlib. A list of control parameters for the forcing functions. It will write a warning if it does so. The diagnostics of the integration can be printed to screen by calling diagnostics. It MUST be present if forcings has been given a value. "fullusr" a full Jacobian. The form of the Jacobian can be specified by jactype which can take the following values: "fullint" a full Jacobian. the number of steps that has to be kept.. above): The input parameters rtol. See forcings or vignette compiledCode. The form of ewt is: rtol × abs(y) + atol where multiplication of two vectors is element-by-element. The values of rtol and atol should all be non-negative.44 initforc lsoda if not NULL. under some circumstances. i. the R function lsoda will attempt a reasonable reduction of precision in order to get an answer. See forcings or package vignette "compiledCode". This means that the user does not have to determine whether the problem is stiff or not.e. calculated internally by lsoda. lsoda switches automatically between stiff and nonstiff methods. The following description of error control is adapted from the documentation of the lsoda source code (input arguments rtol and atol. See timelags. when the value of a state variable is suddenly changed. and the solver will automatically choose the appropriate method. A list that specifies events.e. and atol determine the error control performed by the solver. See events for more information. If the request for precision exceeds the capabilities of the machine.

Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func.netlib.55–64 of Stepleman.gov> References Hindmarsh. Alan C. • lsode. which can also find a root • lsodes. . A Systematized Collection of ODE Solvers. plus and additional column for the time value. Note The ‘demo’ directory contains some examples of using gnls to estimate parameters in a dynamic model. Models may be defined in compiled C or FORTRAN code. vode. 136–148. See package vignette "compiledCode" for details. Linda R. 4. Sci. • ode for a general interface to most of the ODE solvers.2D for integrating 2-D models.[ed. North-Holland. (1983) ODEPACK. Netlib: http://www. If y has a names attribute. • ode. information about linking forcing functions to compiled code is in forcings. Siam J. Author(s) R. diagnostics to print diagnostic messages. • ode.W. in p.lsoda 45 See vignette("deSolve") for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. More information about models defined in compiled code is in the package vignette ("compiledCode"). Amsterdam.1D for integrating 1-D models. • ode.3D for integrating 3-D models. Woodrow Setzer <setzer.org See Also • rk. Comput. rkMethod. Stat.] (1983) Scientific Computing. Petzold.woodrow@epa. • ode. daspk for other solvers of the Livermore family. R. as well as in an R-function. There will be a row for each element in times unless the FORTRAN routine ‘lsoda’ returns with an unrecoverable error. (1983) Automatic Selection of Methods for Solving Stiff and Nonstiff Systems of Ordinary Differential Equations. it will be used to label the columns of the output value. et al.band for solving models with a banded Jacobian. Examples in both C and FORTRAN are in the ‘dynload’ subdirectory of the deSolve package directory. lsodar. rk4 and euler for Runge-Kutta integrators.

length = 1 1) ## external signal with rectangle impulse signal <. { import <. main = c("substrate". rule = 2) ## Start values for steady state y <.approxfun(signal$times.c(S = 1.1.e*P*C .lsoda(xstart."C"].seq( . "consumer")) plot(out[.import .1. parameter and state variable names made accessible via "with" function 2. ) ## vector of timesteps times <. ylab = "consumer") par(mfrow = mf) ## ======================================================================= ## Example 2: .function(t.list(c(parms.c(b = #substrate #producer #consumer . function sigimp accessible through lexical scoping (see also ode and rk examples) ======================================================================= lsoda SPCmod <. C = 1) ## Solving out <. signal$import. dC) list(res) }) } ## Parameters parms <."P"]. out[.data.d*C*P dC <.xstart <. parms) ## Plotting mf <. import = rep( .f*C res <. dP. .c*S*P .b*S*P + g*C dP <. P = 1. c = . parms) { with(as. g = .sigimp(t) dS <.frame(list(times = times. f = . x.par("mfrow") plot(out. times. type = "l". d = .2 sigimp <. e = . "producer". SPCmod.1.as.length(times)))) signal$import[signal$times >= 1 & signal$times <= 11] <.46 Examples ## ## ## ## ## ## ## ## ## ## ======================================================================= Example 1: A simple resource limited Lotka-Volterra-Model Note: 1.c(dS. xlab = "producer". 1 .1. x)).

4.-p["k1"] * y[1] + p["k2"] * y[2]*y[3] yd3 <. at at at at at at at at at at at at t t t t t t t t t t t t = = = = = = = = = = = = 4. ## measure speed (here and below) system.659 31e1.62194 e. 4.atol <.c(1e-6.941774e. c(massbalance = sum(y))) } exampjac <. parms <.222964e.113371e-11 1. ). 4.p["k3"] * y[2]^2 list(c(yd1.lsoda(c(1. -yd1-yd3.c( . 3.p["k2"]*y[3] .time( out <.95 636e9. e+ 2 2 1 1 1 1 1 1 1 1 1 ## Using the analytic Jacobian speeds up execution a little : . p) { matrix(c(-p["k1"]. atol = my. e. 4.lsoda ## from lsoda source code ## ======================================================================= ## names makes this easier to read.831975e3.function(t. parms. 4.936363e5.179817e5.999482e9. p["k2"]*y[2].c(k1 = . hmax = Inf) ) out ## This is what the authors of lsoda got for the example: ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## the output of this program (on a cdc-76 is as follows.7 1.function(t.851712e9.984221e. ). 4.. y.89873 e4. rtol = 1e-4. y. k3 = 3e7) my.4 * 1 ^(-1:1 )) lsexamp <.5 9. p) { yd1 <.atol.24 655e. 1e-6) times <.4 428 e1 1 1 1 1 2 3 4 5 6 7 8 in single precision) 3. 1e-1 . 4. 4. 47 . but may slow down execution.2834 1e4.863613e-12 5.8 2. lsexamp.5 2.168 16e9. 65786e.5 525 e1.6 8.994838e9. 72 32e-1 2. p["k1"].494717e8. 55333e7.999947e9. .44443 e2. p["k2"]*y[3]. 4.617126e-14 1.161831e5.1584 3e4.6 3. 4.7 1.9 2.186334e.999995e1.2*p["k3"]*y[2]. 3) } -p["k2"]*y[2]. times. 2*p["k3"]*y[2]. yd3).8415 5e5. .61 125e9. 4. 4.479493e9.1 e+ e+ 1 e+ 2 e+ 3 e+ 4 e+ 5 e+ 6 e+ 7 e+ 8 e+ 9 e+1 y y y y y y y y y y y y = = = = = = = = = = = = 9.38638 e. k2 = 1e4.

bandup = NULL.atol.data.. times. rootfunc = NULL. initforc = NULL. lsodar differs from lsode in two respects. jacfunc = NULL.frame(outJ)) # TRUE diagnostics(out) diagnostics(outJ) # shows what lsoda did internally lsodar lsodar Solver for Ordinary Differential Equations (ODE). nroot = . parms. lsexamp. as. Hindmarsh and Linda R. rtol = 1e-4. .e. forcings=NULL. Two uses of lsodar are: • To stop the simulation when a certain condition is met • To trigger an events. i. • It finds the root of at least one of a set of constraint functions g(i) of the independent and dependent variables. hmin = . fcontrol=NULL.see description of lsoda for details. rpar = NULL. Petzold. • It switches automatically between stiff and nonstiff methods (similar as lsoda). hmax = Inf) ) all.frame(out).lsoda(c(1.. The system of ODE’s is written as an R function or be defined in compiled code that has been dynamically loaded. tcrit = NULL.) . func. hini = . ipar = NULL. initfunc = dllname. dllname = NULL. Usage lsodar(y. a sudden change in one of the state variables when a certain condition is met. events=NULL. The R function lsodar provides an interface to the FORTRAN ODE solver of the same name. nout = . ). atol = 1e-6. lags = NULL. jactype = "fullint". jacfunc = exampjac. banddown = NULL. written by Alan C. maxordn = 12. hmax = NULL. times. parms. . initpar = parms. .equal(as.48 system.data. outnames = NULL. atol = my. when a particular condition is met. rtol = 1e-6. jactype = "fullusr".time( outJ <. maxsteps = 5 . ynames = TRUE. Switching Automatically Between Stiff and Non-stiff Methods and With Root Finding Description Solving initial value problems for stiff or non-stiff systems of first-order ordinary differential equations (ODEs) and including root-finding. verbose = FALSE. maxords = 5.

See details. If the Jacobian is a full matrix. If func is an R-function. y is the current estimate of the variables in the ODE system. will print the diagnostiscs of the integration . If the Jacobian is banded. an R function. and whose next elements are global values that are required at each point in times.. rootfunc should return a vector with the function values whose root is sought. The derivatives should be specified in the same order as the state variables y. . (optional) are any other arguments passed to the function. The R calling sequence for jacfunc is identical to that of func. where the ˙ ith row contains the derivative of dyi /dt with respect to yj . the structure of the Jacobian. an R function that computes the function whose root has to be estimated or a string giving the name of a function or subroutine in ‘dllname’ that computes the root function.function(t. when TRUE.see details. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices). if not NULL. if not NULL. supplying jacfunc can speed up the computations.. a logical value that. either a scalar or an array as long as y. the names will be used to label the output matrix. See first example of lsode. or a character string giving the name of a compiled function in a dynamically loaded shared library. rotated row-wise. jacfunc should return a matrix ∂ y/∂y. parms. In some circumstances. absolute error tolerance.).. See package vignette "compiledCode" for more details. the names will be available inside func. The R calling sequence for rootfunc is identical to that of func. t is the current time point in the integration. vector or list of parameters used in func or jacfunc. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. whose first element is a vector containing the derivatives of y with respect to time. The first value in times must be the initial time. relative error tolerance. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. y. The return value of func should be a list. it must be defined as: func <. If y has a name attribute. then dllname must give the name of the shared library (without extension) which must be loaded before lsodar() is called.lsodar Arguments y times func 49 the initial (state) values for the ODE system. "bandusr" or "bandint" . If func is a string. times at which explicit estimates for y are desired. If the initial values y has a names attribute.either full or banded and estimated internally or by user. either a scalar or an array as long as y. parms is a vector or list of parameters.. See details. parms rtol atol jacfunc jactype rootfunc verbose . or a string giving the name of a function or subroutine in ˙ ‘dllname’ that computes the Jacobian (see vignette "compiledCode" for more about this option). if the system is stiff. "fullusr". one of "fullint".. that computes the Jacobian of the system of differential equations ∂ yi /∂yj .

If there is a time beyond which integration should not proceed (perhaps because of a singularity). the initial step size is determined by the solver. See package vignette "compiledCode". See package vignette "compiledCode". the name of the initialisation function (which initialises values of parameters). number of non-zero bands above the diagonal. that should be provided in tcrit. if not NULL. maximal number of steps per output interval taken by the solver. present in the shared library. C++). a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. to avoid that the simulation possibly ignores short-term events.See package vignette "compiledCode". only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. the solver estimates the number of roots. this may speed up the simulation especially for large models. only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. In special situations this parameter may speed up computations with the cost of precision. if 0. If 0. logical.you have to perform this check in the code . Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. tcrit hmin hmax hini ynames maxordn maxords bandup banddown maxsteps dllname initfunc initpar rpar ipar nout . The FORTRAN routine lsodar overshoots its targets (times points in the vector times). and interpolates values for the desired time points. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll . if rootfunc is an R-function. the maximum order to be allowed in case the method is non-stiff. as provided in ‘dllname’. then lsodar cannot integrate past tcrit. the maximum order to be allowed in case the method is stiff. If not specified. initial step size to be attempted. in case the Jacobian is banded. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. Reduce maxord to save storage space. Should be <= 12. to initialise the common blocks (FORTRAN) or global variables (C. in case the Jacobian is banded. number of non-zero bands below the diagonal. Should be <= 5. if not NULL. Reduce maxord to save storage space. if FALSE: names of state variables are not passed to function func. hmax is set to the largest difference in times.50 nroot lsodar only used if ‘dllname’ is specified: the number of constraint functions whose roots are desired during the integration. an optional minimum value of the integration stepsize. no maximal size is specified.

each present as a two-columned matrix. when the value of a state variable is suddenly changed. and otherwise returns the solution according the specified stop condition. .value). If jactype = "fullusr" or "bandusr" then the user must supply a subroutine jacfunc. See forcings or vignette compiledCode. specified by user function jacfunc. only used if ‘dllname’ is specified: a list with the forcing function data sets. The form of the Jacobian can be specified by jactype which can take the following values: jactype = "fullint": a full Jacobian. lsodar may return false roots. present in the shared library. from Netlib. if not NULL. calculated internally by lsodar. calculated by lsodar. It always starts with the nonstiff method. It MUST be present if forcings has been given a value.. A list that specifies events. These names will be used to label the output matrix. the default. The implementation is based on the November. and atol determine the error control performed by the solver.f’). the size of the bands specified by bandup and banddown. Details The work is done by the FORTRAN subroutine lsodar. lsodar switches automatically between stiff and nonstiff methods (similar as lsoda).. jactype = "bandusr": a banded Jacobian. See events for more information. See lsoda for details. See timelags. Caution: Because of numerical errors in the function rootfun due to roundoff and integration error. the size of the bands specified by bandup and banddown. dede for more information.e. i. lsodar can find the root of at least one of a set of constraint functions rootfunc of the independent and dependent variables. or return the same root at two or more nearly equal values of time. jactype = "fullusr": a full Jacobian. whose documentation should be consulted for details (it is included as comments in the source file ‘src/opkdmain. max(times)] is done by taking the value at the closest data extreme. specified by user function jacfunc. as provided in ‘dllname’. The input parameters rtol.e. and the solver will automatically choose the appropriate method. the name of the forcing function initialisation function. To be used for delay differential equations. with (time. the number of steps that has to be kept. jactype = "bandint": banded Jacobian. forcings initforc fcontrol events lags . See forcings or package vignette "compiledCode". interpolation outside the interval [min(times). i. A list that specifies timelags. This means that the user does not have to determine whether the problem is stiff or not. additional arguments passed to func and jacfunc allowing this to be a generic function. A list of control parameters for the forcing functions. See forcings or package vignette "compiledCode".lsodar outnames 51 only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. It then returns the solution at the root if that occurs sooner than the specified stop condition. 2003 version of lsodar.

rk4 and euler for Runge-Kutta integrators. lsode. 136-148. rkMethod.52 lsodar The output will have the attribute iroot.soetaert@nioo. ODEPACK. (Eds. North-Holland.org See Also • roots for more examples on roots and events • rk. the output will have the attribute iroot.knaw. daspk for other solvers of the Livermore family. 4 (1983). plus and additional column for the time value. • ode. Author(s) Karline Soetaert <k. Stat. if a root was found iroot is a vector. Comput. its length equal to the number of constraint functions it will have a value of 1 for the constraint function whose root that has been found and 0 otherwise. as well as in an R-function. The diagnostics of the integration can be printed to screen by calling diagnostics. Automatic Selection of Methods for Solving Stiff and Nonstiff Systems of Ordinary Differential Equations. Siam J. information about linking forcing functions to compiled code is in forcings. A Systematized Collection of ODE Solvers.band for solving models with a banded Jacobian. R. in Scientific Computing. Amsterdam. an integer indicating which root has been found. Linda R. Sci. lsodes. If a root has been found.netlib. vode. Models may be defined in compiled C or FORTRAN code. Kathie L. S. 55-64. Hindmarsh. . it will be used to label the columns of the output value. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func.nl> References Alan C. February 1980. Sandia Report SAND80-0180. the diagnostics will written to the screen at the end of the integration. pp. If y has a names attribute. 1983. Examples in both C and FORTRAN are in the ‘dynload’ subdirectory of the deSolve package directory. See vignette("deSolve") for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. Shampine. More information about models defined in compiled code is in the package vignette ("compiledCode"). • lsoda. Petzold. Implicitly Defined Output Points for Solutions of ODEs. Netlib: http://www.). If verbose = TRUE. • ode for a general interface to most of the ODE solvers. See package vignette "compiledCode" for details. pp. Stepleman et al. Hiebert and Lawrence F. There will be a row for each element in times unless the FORTRAN routine ‘lsodar’ returns with an unrecoverable error.

3. 1e-6).y[1] .3D for integrating 3-D models.-. ) c( . { ## substrate uptake death respiration dBact <. .lsodar • ode.]) diagnostics(out) ## ======================================================================= ## Example 2: ## using lsodar to estimate steady-state conditions ## ======================================================================= ## Bacteria (Bac) are growing on a substrate (Sub) model <.vector(len = 2) yroot[1] <. 1e-1 .-ydot[1] .gmax*eff*Sub/(Sub+ks)*Bact .2D for integrating 2-D models.rB*Bact dSub <.1. diagnostics to print diagnostic messages.vector(len = 3) ydot[1] <.1D for integrating 1-D models. parms = NULL) print(paste("root is found for eqn". pars)).lsodar(y = y.1.function (t. parms) { yroot <.function (t. .dSub))) . 4*y[1] + 1.y[3] . fun = Fun. pars) { with (as.e7*y[2]*y[2] ydot[2] <. rootfun = rootFun. atol = c(1e-6.e-2 return(yroot) } y times Out ny out <<<<c(1.list(c(state.ydot[3] return(list(ydot. state. rtol = 1e-4. y. ytot = sum(y))) } rootFun <. y.dB*Bact . parms) { ydot <. Examples ## ======================================================================= ## Example 1: ## from lsodar source code ## ======================================================================= Fun <. times = times.e-4 yroot[2] <. which(attributes(out)$iroot == 1))) print(out[nrow(out).e4*y[2]*y[3] ydot[3] <.-gmax *Sub/(Sub+ks)*Bact + dB*Bact + input return(list(c(dBact.function(t.4*1 ^( :8)) NULL length(y) 53 <. • ode. • ode.

tout. events = list(func=eventfun.unlist(model(t. derivfun <.lsodar(func=derivfun.1e-1 ) } pars <..parms) return(y + runif(1)) yini <.y.function (t. rB = . pars. input = . pars)) # rate of change vector return(sum(abs(dstate)) . rootfunc = rootfun. rootfun = rootfun) print(out) lsode ## ======================================================================= ## Example 3: ## using lsodar to trigger an event ## ======================================================================= ## a state variable is decaying at a first-order rate. times=times.parms) return(y .y.1.1) tout <. type = "l". Sini = 1 . a random amount is added. state. eff = .. 1e1 ) state <. 1. 1. root = TRUE)) plot(out.function (t. ks = . Sub = pars$Sini) out <.c(Bact = pars$Bini.c( .function (t. pars) { dstate <. y = yini..1) eventfun <. dB = .lsodar(state.5.parms) list (.list(Bini = .8 times <. lwd = 2. ## when it reaches the value . gmax = .:2 out <.y. main = "lsodar with event") lsode Solver for Ordinary Differential Equations (ODE) . state. model.54 }) } ## root is the condition where sum of |rates of change| ## is very small rootfun <.function(t. 5 * y) rootfun <.1.5.5.

lags = NULL. events=NULL. times. initfunc = dllname. outnames = NULL. nroot = . Usage lsode(y. If func is an R-function. a copy is not kept. bandup = NULL. initforc = NULL. a sudden change in one of the state variables. the names will be used to label the output matrix. If the initial values y has a names attribute. hmax = NULL. whose first element is a vector containing the derivatives of y with respect to time.lsode Description 55 Solves the initial value problem for stiff or nonstiff systems of ordinary differential equations (ODE) in the form: dy/dt = f (t. atol = 1e-6. In addition. or a character string giving the name of a compiled function in a dynamically loaded shared library. (optional) are any other arguments passed to the function.. time sequence for which output is wanted.). rtol = 1e-6.. initpar = parms. Hindmarsh and Andrew H. The return value of func should be a list. rpar = NULL. t is the current time point in the integration.. in vode it is possible to choose whether or not a copy of the Jacobian is saved for reuse in the corrector iteration algorithm. If y has a name attribute. nout = . forcings=NULL. The system of ODE’s is written as an R function or be defined in compiled code that has been dynamically loaded. dllname = NULL. the user has to specify whether or not the problem is stiff and choose the appropriate solution method. if only one step is to be taken. it must be defined as: func <. This can be used to stop the simulation or to trigger events. verbose = FALSE..) Arguments y times func the initial (state) values for the ODE system. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. In contrast to lsoda. maxsteps = 5 .. The R function lsode provides an interface to the FORTRAN ODE solver of the same name. hini = .e. ipar = NULL. fcontrol=NULL. hmin = . ynames = TRUE. banddown = NULL. func.function(t. jacfunc = NULL. set times = NULL. parms. i.. the first value of times must be the initial time.. rootfunc = NULL. the names will be available inside func. y. parms is a vector or list of parameters. jactype = "fullint". y) . but uses a fixed-step-interpolate method rather than the variablecoefficient method in vode. written by Alan C. and whose next elements are .. lsode is very similar to vode. tcrit = NULL. maxord = NULL. Sherman. In lsode. parms. . y is the current estimate of the variables in the ODE system. It combines parts of the code lsodar and can thus find the root of at least one of a set of constraint functions g(i) of the independent and dependent variables. mf = NULL.

and interpolates values for the desired time points. overruled if mfis not NULL. then lsode cannot integrate past tcrit. the "method flag" passed to function lsode .see details. If the Jacobian is a full matrix.overrules jactype . In special situations this parameter may speed up computations with the cost of precision. hmax is set to the largest difference in times. The FORTRAN routine lsode overshoots its targets (times points in the vector times). rootfunc should return a vector with the function values whose root is sought. will print the diagnostiscs of the integration . relative error tolerance. only used if ‘dllname’ is specified: the number of constraint functions whose roots are desired during the integration. If there is a time beyond which integration should not proceed (perhaps because of a singularity). In some circumstances. supplying jacfunc can speed up the computations. jacfunc should return a matrix ∂ y/∂y. if not NULL. an R function that computes the function whose root has to be estimated or a string giving the name of a function or subroutine in ‘dllname’ that computes the root function. either a scalar or an array as long as y. See first example of lsode. The derivatives should be specified in the same order as the state variables y. if not NULL. or a string giving the name of a function or subroutine in ˙ ‘dllname’ that computes the Jacobian (see vignette "compiledCode" for more about this option). parms rtol atol jacfunc jactype mf rootfunc verbose nroot tcrit hmin hmax . vector or list of parameters used in func or jacfunc. e.g.provides more options than jactype . if rootfunc is an R-function. If the Jacobian is banded. "bandusr" or "bandint" . rotated row-wise. "fullusr". If func is a string. no maximal size is specified. then dllname must give the name of the shared library (without extension) which must be loaded before lsode() is called. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. to avoid that the simulation possibly ignores short-term events. The R calling sequence for jacfunc is identical to that of func.either full or banded and estimated internally or by user. if the system is stiff. one of "fullint". that should be provided in tcrit. See details. See package vignette "compiledCode" for more details. if not NULL. Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. either a scalar or an array as long as y. an R function that computes the Jacobian of the system of differential equations ∂ yi /∂yj . If not specified. the solver estimates the number of roots.see details. See details. absolute error tolerance. the structure of the Jacobian. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices). where the ˙ ith row contains the derivative of dyi /dt with respect to yj . if TRUE: full output to the screen. The R calling sequence for rootfunc is identical to that of func.56 lsode global values that are required at each point in times. an optional minimum value of the integration stepsize. If 0.

e. as provided in ‘dllname’. Reduce maxord to save storage space.value). number of non-zero bands below the diagonal.e. order 12 if implicit Adams method (meth = 1). only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. i. i. present in the shared library. To be used for delay differential equations. when the value of a state variable is suddenly changed. number of non-zero bands above the diagonal. each present as a two-columned matrix. in case the Jacobian is banded. if not NULL. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. dede for more information. See events for more information. if FALSE names of state variables are not passed to function func. the number of steps that has to be kept. if 0. See package vignette "compiledCode". See forcings or package vignette "compiledCode". the name of the initialisation function (which initialises values of parameters). A list that specifies timelags. See forcings or vignette compiledCode. a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. if not NULL. present in the shared library. A list of control parameters for the forcing functions. with (time. See package vignette "compiledCode". logical. only used if ‘dllname’ is specified: a list with the forcing function data sets.e. interpolation outside the interval [min(times). Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll . only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. in case the Jacobian is banded. maximal number of steps per output interval taken by the solver. C++). only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. bandup banddown maxsteps dllname initfunc initpar rpar ipar nout outnames forcings initforc fcontrol events lags . NULL uses the default.See package vignette "compiledCode". as provided in ‘dllname’. See forcings or package vignette "compiledCode". i.you have to perform this check in the code . the maximum order to be allowed. the initial step size is determined by the solver. to initialise the common blocks (FORTRAN) or global variables (C. It MUST be present if forcings has been given a value. the name of the forcing function initialisation function. See timelags. These names will be used to label the output matrix.lsode hini ynames maxord 57 initial step size to be attempted. A list that specifies events. only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. max(times)] is done by taking the value at the closest data extreme. this may speed up the simulation especially for multi-D models. order 5 if BDF method (meth = 2).

the size of the bands specified by bandup and banddown. whose documentation should be consulted for details (it is included as comments in the source file ‘src/opkdmain. as well as in an R-function. corresponds to mf = 25. calculated internally by lsode. Models may be defined in compiled C or FORTRAN code. 24. The diagnostics of the integration can be printed to screen by calling diagnostics. mf = (10*METH + MITER). MITER = 5 means chord iteration with an internally generated banded Jacobian (using ML+MU+1 extra calls to func per df/dy evaluation). See vignette("deSolve") for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. the size of the bands specified by bandup and banddown. If the problem is nonstiff. 23.. 11. The options for jactype are jactype = "fullint" a full Jacobian. If the problem is stiff. 25. MITER = 1 means chord iteration with a user-supplied full (NEQ by NEQ) Jacobian. MITER = 2 means chord iteration with an internally generated (difference quotient) full Jacobian (using NEQ extra calls to func per df/dy value). mf is a positive two-digit integer. Before using the integrator lsode. 22.58 . lsode additional arguments passed to func and jacfunc allowing this to be a generic function. 20. If MITER = 1 or 4. 12. the user has to decide whether or not the problem is stiff. where METH indicates the basic linear multistep method: METH = 1 means the implicit Adams method. and atol determine the error control performed by the solver. from Netlib. Inspection of the example below shows how to specify both a banded and full Jacobian. The legal values of mf are 10. .. 14. no Jacobian used. More options are available when specifying mf directly. use method flag mf = 10. corresponds to mf = 22. See lsoda for details. The implementation is based on the November. METH = 2 means the method based on backward differentiation formulas (BDF-s). calculated by lsode. 2003 version of lsode. there are four standard choices which can be specified with jactype or mf. MITER indicates the corrector iteration method: MITER = 0 means functional iteration (no Jacobian matrix is involved). MITER = 3 means chord iteration with an internally generated diagonal Jacobian approximation (using 1 extra call to func per df/dy evaluation). Details The work is done by the FORTRAN subroutine lsode. jactype = "bandusr" a banded Jacobian. which selects a nonstiff (Adams) method. the user must supply a subroutine jacfunc. jactype = "bandint" a banded Jacobian. specified by user function jacfunc. See package vignette "compiledCode" for details. The input parameters rtol. 15. corresponds to mf = 24. the diagnostics will written to the screen at the end of the integration. 13. jactype = "fullusr" a full Jacobian. specified by user function jacfunc.f’). 21. MITER = 4 means chord iteration with a user-supplied banded Jacobian. corresponds to mf = 21. If verbose = TRUE.

5 state variables . et al. vode. • rk4 and euler for Runge-Kutta integrators. 1983). See Also • rk. lsodes. Amsterdam.1D for integrating 1-D models.band for solving models with a banded Jacobian.3D for integrating 3-D models. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func. • lsoda. • ode for a general interface to most of the ODE solvers. plus and additional column for the time value. Hindmarsh.soetaert@nioo. 55-64.nl> References Alan C. Examples in both C and FORTRAN are in the ‘dynload’ subdirectory of the deSolve package directory. Caution: Because of numerical errors in the function rootfun due to roundoff and integration error. R. It then returns the solution at the root if that occurs sooner than the specified stop condition. ## ======================================================================= ## the model. S. (North-Holland. There will be a row for each element in times unless the FORTRAN routine ‘lsode’ returns with an unrecoverable error. Author(s) Karline Soetaert <k. Examples ## ======================================================================= ## Example 1: ## Various ways to solve the same model. • ode. "ODEPACK. pp. If y has a names attribute. lsode can find the root of at least one of a set of constraint functions rootfunc of the independent and dependent variables. Eds. lsode may return false roots.knaw.. • ode. diagnostics to print diagnostic messages.2D for integrating 2-D models. or return the same root at two or more nearly equal values of time. lsodar.lsode 59 More information about models defined in compiled code is in the package vignette ("compiledCode"). • ode. it will be used to label the columns of the output value." in Scientific Computing. daspk for other solvers of the Livermore family. Stepleman. information about linking forcing functions to compiled code is in forcings. A Systematized Collection of ODE Solvers. and otherwise returns the solution according the specified stop condition. • ode.

function (t.2*y[2] <. ncol = 5.3. data = c( . .1.lsode(yini.. f1. byrow = TRUE. .2.. . .function (t..1)) return(jac) } ## the Jacobian..lsode(yini.. ..1*y[4] . parms) { ydot <. parms = . jactype = "fullint") ## stiff method.1*y[2] . . .. y. banddown = 1) ## stiff method. parms) { jac <. .2.3. f1..2*y[3] <.2*y[4] <.. f1.1*y[1] . times.3*y[2] + . .. user-generated banded Jacobian out4 <. ..1...matrix(nrow = 5.2. bandup = 1. ncol = 5.60 f1 <. . written in banded form bandjac <.3.1. . . ..1. .lsode(yini. )) return(jac) } ## initial conditions and output times yini <. .3. .3*y[4] + . byrow = TRUE. . . y. data = c( . ... times.1..3. parms = . bandup = 1. . parms) { jac <. jactype = "fullusr"... y.2. parms = .1.2.. parms = . ... jactype = "bandusr". . .. user-generated full Jacobian out2 <.1:5 times <.2.. .1. jacfunc = fulljac) ## stiff method.lsode(yini.3.2.1*y[5] lsode return(list(ydot)) } ## the Jacobian.vector(len = 5) ydot[1] ydot[2] ydot[3] ydot[4] ydot[5] <. f1. . . .3.3*y[1] + . .. . . full Jacobian out <. .1*y[3] .3*y[3] + . times. jacfunc = bandjac. times. internally-generated banded Jacobian ## one nonzero band above (up) and below(down) the diagonal out3 <. jactype = "bandint".1. . . .2.2*y[5] <. banddown = 1) ## non-stiff method . .3. .function (t.1:2 ## default: stiff method.1. written as a full matrix fulljac <.matrix(nrow = 3. internally generated.

n)^2) } } filled.]).dY . whereas the true ## half-bandwidths are equal to n.])/dx ## diffusion in Y-direction Flux <.palette = terrain. color.1/(n*n) * (dst .colors) ## ======================================================================= ## jacfunc need not be estimated exactly ## a crude approximation.-y[.])/dx dY <.(Flux[. ncol = n. 1 .1 Dy <. with a smaller bandwidth will do.2:n]-y[.(Flux[2:(n+1). f1.r*y # production ## diffusion in X-direction.function(t.n/2)^2 + (j .-Dx * rbind(y[1.1:(n-1)]). mf = 1 ) 61 ## ======================================================================= ## Example 2: ## diffusion on a 2-D grid ## partially specified Jacobian ## ======================================================================= diffusion2D <.(y[2:n.matrix(nrow = n..5 <.1].1:n])/dy return(list(as.lsode out5 <.].]-y[1:(n-1).lsode(yini. ## Here the half-bandwidth 1 is used.and Y-direction # production rate <. Y. ## This corresponds to ignoring the y-direction coupling in the ODEs. X.par(ask = FALSE) ## initial condition for (i in 1:n) { for (j in 1:n) { dst <.vector(dY))) } ## parameters dy <.-Dy * cbind(y[.(y[. boundaries = -concentration Flux <. j] <.time( for (i in 1:2 ) { . par) { y <.]-Flux[1:n. data = Y) dY <. 1) n y # grid size # diffusion coeff.max( . ncol = n.1 r <. times. parms = .dY . ## ======================================================================= print(system.(i . ) pa <.n/2)^2 y[i.contour(y.Dx <. 25 times <.c( .2:(n+1)]-Flux[.n])/dy dY <.matrix(nrow = n.-y[n.dx <.

initfunc = dllname. zlim = c( .colors. The R function lsodes provides an interface to the FORTRAN ODE solver of the same name. time sequence for which output is wanted. hmax = NULL.. func. y) and where the Jacobian matrix df/dy has an arbitrary sparse structure. ncol = n. out[2. nout = . jactype = "bandint". . .1). maxsteps = 5 . tcrit = NULL. -1] } )) par(ask = pa) lsodes Solver for Ordinary Differential Equations (ODE) With Sparse Jacobian Description Solves the initial value problem for stiff systems of ordinary differential equations (ODE) in the form: dy/dt = f (t. atol = 1e-6. The system of ODE’s is written as an R function or be defined in compiled code that has been dynamically loaded.62 out <lsode(func = diffusion2D. the first value of times must be the initial time. times = times.vector(y). initforc = NULL.out[2. banddown = 1) lsodes filled. hmin = . if only one step is to be taken. liw = NULL. lrw = NULL. events=NULL. dllname = NULL. y = as. set times = NULL. lags = NULL. rootfunc = NULL. parms = NULL.) Arguments y times the initial (state) values for the ODE system. If y has a name attribute. times. ynames = TRUE. outnames = NULL. forcings=NULL. written by Alan C. the names will be used to label the output matrix.palette = terrain. nroot = . nnz = NULL.contour(matrix(nrow = n. maxord = NULL. parms.-1]). bandup = 1. verbose = FALSE. Sherman. inz = NULL. fcontrol=NULL. main = i) y <. initpar = parms. rpar = NULL. Hindmarsh and Andrew H. ipar = NULL. color.. sparsetype = "sparseint". jacvec = NULL. Usage lsodes(y. hini = . rtol = 1e-6.

Thus. or a string giving the name of a function or ˙ subroutine in ‘dllname’ that computes the column of the Jacobian (see vignette "compiledCode" for more about this option). The R calling sequence for jacvec is identical to that of func. e.). The derivatives should be specified in the same order as the state variables y. jacvec should be called as: jacvec = func(t. rootfunc should return a vector with the function values whose root is sought. If func is an R-function.. See details. The FORTRAN routine lsodes overshoots its targets (times points in the vector times). an R function that computes a column of the Jacobian of the system of differential equations ∂ yi /∂yj .column) indices to the nonzero elements in the sparse Jacobian. The return value of func should be a list.g. but with extra parameter j. (optional) are any other arguments passed to the function. relative error tolerance. See package vignette "compiledCode" for more details. then lsodes cannot integrate past tcrit. else ignored. parms is a vector or list of parameters.. only used if ‘dllname’ is specified: the number of constraint functions whose roots are desired during the integration. then dllname must give the name of the shared library (without extension) which must be loaded before lsodes() is called. the solver estimates the number of roots. j. absolute error tolerance. use an estimate). either a scalar or an array as long as y.. i. and whose next elements are global values that are required at each point in times. the number of nonzero elements in the sparse Jacobian (if this is unknown.. The R calling sequence for rootfunc is identical to that of func. Necessary if sparsetype = "sparseusr". if not NULL. whose first element is a vector containing the derivatives of y with respect to time. it must be defined as: func <. If func is a string. y. its i-th value is ∂ yi /∂yj .see details. the sparsity structure of the Jacobian. sparsity estimated internally by lsodes or given by the user. parms. if not NULL. y. parms) and jacvec should return a vector containing column j of the Jacobian. one of "sparseint" or "sparseusr".lsodes func 63 either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. If the initial values y has a names attribute. or a character string giving the name of a compiled function in a dynamically loaded shared library. vector or list of parameters used in func or jacfunc. if rootfunc is an R-function. and interpolates parms rtol atol jacvec sparsetype nnz inz rootfunc verbose nroot tcrit . denoting the column number. (row. either a scalar or an array as long as y. the names will be available inside func. If this function is absent. See details.e. will print the diagnostiscs of the integration . y is the current estimate of the variables in the ODE system. an R function that computes the function whose root has to be estimated or a string giving the name of a function or subroutine in ‘dllname’ that computes the root function. ˙ lsodes will generate the Jacobian by differences.function(t.. . if TRUE: full output to the screen. if not NULL. t is the current time point in the integration.

Therefore. and if not sufficient. hmax is set to the largest difference in times. that should be provided in tcrit. to avoid that the simulation possibly ignores short-term events. due to the sparsicity. For instance.64 lsodes values for the desired time points. If NULL. a guess will be made. hmin an optional minimum value of the integration stepsize. and if not sufficient. exceeds LRW (=I2) In above message. lsodes will return with a message indicating the size of rwork actually required. the length of the real work array rwork. no maximal size is specified. Length needed is . If 0. some experimentation may be necessary to estimate the value of liw. if not NULL. See package vignette "compiledCode". If there is a time beyond which integration should not proceed (perhaps because of a singularity). initial step size to be attempted. hmax hini ynames maxord maxsteps lrw dllname initfunc initpar rpar ipar . the initial step size is determined by the solver. the maximum order to be allowed. if you get the error: DLSODES. this may speed up the simulation especially for multi-D models. LENRW (=I1). if FALSE names of state variables are not passed to function func. a guess will be made. order 12 if implicit Adams method (meth = 1). Therefore. Reduce maxord to save storage space. In special situations this parameter may speed up computations with the cost of precision. only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. some experimentation may be necessary to estimate the value of lrw. i. NULL uses the default. logical. the name of the initialisation function (which initialises values of parameters). See package vignette "compiledCode". to initialise the common blocks (FORTRAN) or global variables (C.e. order 5 if BDF method (meth = 2).RWORK length is insufficient to proceed. Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. if 0. this cannot be readily predicted. due to the sparsicity. as provided in ‘dllname’. If not specified. a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. I1 = 27627 I2 = 25932 set lrw equal to 27627 or a higher value liw the length of the integer work array iwork. this cannot be readily predicted. If NULL. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc.ge. maximal number of steps per output interval taken by the solver. C++). lsodes will return with a message indicating the size of iwork actually required.

If nnz is not specified. If jacvec and inz are present. .f’). i. It MUST be present if forcings has been given a value. by differences.e. only used if ‘dllname’ is specified: a list with the forcing function data sets.lsodes nout 65 only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. present in the shared library. from Netlib. lsodes is applied for stiff problems. the number of steps that has to be kept. column) to the nonzero elements in the Jacobian matrix. additional arguments passed to func and jacfunc allowing this to be a generic function. it is advisable to provide an estimate of the number of non-zero elements in the Jacobian (inz). A list that specifies timelags. See timelags. See package vignette "compiledCode". each present as a two-columned matrix. dede for more information. See forcings or vignette compiledCode. then the Jacobian will be generated internally by differences. as provided in ‘dllname’. If function jacvec is present.value). then it should return the j-th column of the Jacobian matrix. i. A list of control parameters for the forcing functions. See forcings or package vignette "compiledCode". whose documentation should be consulted for details (it is included as comments in the source file ‘src/opkdmain. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll . If neither nnz nor jacvec is present. where the Jacobian has a sparse structure. There are four choices depending on whether jacvec and inz is specified. A list that specifies events. outnames forcings initforc fcontrol events lags . then it should contain indices (row. See events for more information. Details The work is done by the FORTRAN subroutine lsodes.you have to perform this check in the code. then the Jacobian is fully specified by the user. but not jacvec then the Jacobian will be estimated internally. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func.. If nnz is present. but not nnz then the structure of the Jacobian will be obtained from NEQ + 1 calls to jacvec. If jacvec is present. present in the shared library. The implementation is based on the November. 2003 version of lsodes.. If matrix inz is present. These names will be used to label the output matrix. interpolation outside the interval [min(times). max(times)] is done by taking the value at the closest data extreme. if not NULL. with (time. its structure (indices to nonzero elements) will be obtained from NEQ + 1 initial calls to func. See forcings or package vignette "compiledCode". To be used for delay differential equations. the name of the forcing function initialisation function.e. when the value of a state variable is suddenly changed.

S. • ode for a general interface to most of the ODE solvers. The Nonsymmetric Codes. Yale Sparse Matrix Package: I. Eisenstat. If verbose = TRUE. C. • lsoda. lsodar.66 lsodes The input parameters rtol. 1977. M. J. If y has a names attribute. C. See vignette("deSolve") for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. Sherman. of Computer Sciences. It then returns the solution at the root if that occurs sooner than the specified stop condition. Schultz. H. Author(s) Karline Soetaert <k. Meth. Examples in both C and FORTRAN are in the ‘doc/examples/dynload’ subdirectory of the deSolve package directory. pp. Int. More information about models defined in compiled code is in the package vignette ("compiledCode"). or return the same root at two or more nearly equal values of time. See Also • rk. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func. The diagnostics of the integration can be printed to screen by calling diagnostics. M. C. North-Holland. See lsoda for details. it will be used to label the columns of the output value.). H.soetaert@nioo. and otherwise returns the solution according the specified stop condition. . Eisenstat. Research Report No. M. R. Yale University. There will be a row for each element in times unless the FORTRAN routine ‘lsodes’ returns with an unrecoverable error. lsode. 1983. Schultz. 1145-1151. as well as in an R-function. and A. H. ODEPACK. (Eds. C. Num. S. The Symmetric Codes. Gursky. Amsterdam.knaw. Dept. See package vignette "compiledCode" for details. Models may be defined in compiled C or FORTRAN code. vode. the diagnostics will written to the screen at the end of the integration.. Yale Sparse Matrix Package: II. Stepleman et al. in Scientific Computing. and atol determine the error control performed by the solver. Caution: Because of numerical errors in the function rootfun due to roundoff and integration error. Eng.nl> References Alan C. • rk4 and euler for Runge-Kutta integrators. information about linking forcing functions to compiled code is in forcings. pp. lsodes may return false roots. A Systematized Collection of ODE Solvers. 55-64. and A. Sherman. S. lsodes can find the root of at least one of a set of constraint functions rootfunc of the independent and dependent variables. Gursky. M. Hindmarsh. H. plus and additional column for the time value. daspk for other solvers of the Livermore family. 18 (1982). 114.

) = = = = 5 .rk17*Y[1 ]*Y[12] rk6 *Y[1 ] .rk19*rk14*Y[5] . rk3 5 . .5. 2. pars) { with (as. .list(pars).rk7 *Y[1 ]*Y[3] . diagnostics to print diagnostic messages. n) times <. n) dy <.5.1. ## ## ## ## ======================================================================= The example from lsodes source code A chemical model ======================================================================= 67 n <. rk7 5 .rk16 5 . { dy[1] <.1. rk8 5 .rk9 *Y[1 ] .rk17*Y[1 ]*Y[12] . e-4 atol <. • ode.5.rk15*Y[2]*Y[12] .rk5 *Y[3] + rk12*rk14*Y[6] + rk2 *rk14*Y[7] + rk13*rk14*Y[8] . . rk14 1 .c( .rk12*rk14*Y[6] .5.rk1 *Y[8] dy[12] <.1*(1 ^( :4))) # chemistry <. .rk2 *rk14*Y[7] . e-6 parms <. .rk1 *Y[8] dy[9] <. Examples ## Various ways to solve the same model.lsodes • ode. . rk2 = = = = = 1 . Y.rk16*Y[5] dy[6] <.rk15*Y[2]*Y[12] .1D for integrating 1-D models.function (time. .rk9*Y[1 ] dy[11] <.rk18 = = = = 2.rk5 *Y[3] . rk5 = . rtol <.c(rk1 rk6 rk11 rk15 rk19 = = = = = . . .rep(1.rk17*Y[1 ]*Y[12] .-rk1 *Y[1] dy[2] <.1. rk4 2.rk2*Y[2] dy[3] <.rk3*Y[2]*Y[3] rk7*Y[1 ]*Y[3] + rk11*rk14*Y[4] + rk12*rk14*Y[6] dy[4] <. • ode.rk13 2.rk8*Y[6] dy[7] <. rk12 1 .rk4 *Y[4] + rk16*Y[5] + rk8*Y[6] + rk18*Y[7] dy[1 ] <. .rk3 *Y[2]*Y[3] .rk6 *Y[1 ] + rk19*rk14*Y[5] + rk2 *rk14*Y[7] rk15*Y[2]*Y[12] . • ode.rep( . . 3 .1. .rk1 *Y[1] + rk11*rk14*Y[4] + rk19*rk14*Y[5] rk3 *Y[2]*Y[3] . rk17 5 . .12 y <.rk2 *Y[2] . rk1 = 5. .rk13*rk14*Y[8] .2D for integrating 2-D models.rk18*Y[7] dy[8] <.rk7 *Y[1 ]*Y[3] .3D for integrating 3-D models.band for solving models with a banded Jacobian.rk4*Y[4] dy[5] <. 5 .rk11*rk14*Y[4] . rk2 1 . rk9 5 .

y = y. times = times. 2. 5. 1 . 7. rtol = rtol.rtol = rtol) #gives warning out2 <. # d (dyi)/dy4 2. # inz = nonzero. rtol = rtol. 11. 1 . 6. 6. atol = atol. the structure of the Jacobian is input ## lsodes calculates the Jacobian by differences ## this is not so efficient. 9. times = times. 2.1 . atol = atol. parms = parms. ## ======================================================================= ## elements of Jacobian that are not zero nonzero <. 12.rk15*Y[12] .68 return(list(dy)) }) } ## ======================================================================= ## application 1. sparsetype = "sparseusr". 3. 1. 7. 5.12) ) ## when run. 5. j. 4. the default length of rwork is too small ## lsodes will tell the length actually needed # out2 <. 12. 2. 8. data = c( 1. 1. 2.rep( . 3. 7. 5. parms = parms. 7.rk2 rk2 . 8. 1 . 2. times = times. atol = atol. 4.rk3*Y[3] . parms = parms.12. 8. 7. 1 . 12. verbose = TRUE. 6. 7. 4.12. verbose = TRUE) ## ======================================================================= ## application 2. 9.list(pars).lsodes(func = chemistry.lsodes(func = chemistry. # influence of sp1 on rate of change of others 2. Y. 5. 5.1 . 2. 12.matrix(nc = 2. inz = nonzero. 1 . 2. 3. 1 .lsodes(func = chemistry. 9. 3.12.1 . 4. lsodes estimates the structure of the Jacobian ## and calculates the Jacobian by differences ## ======================================================================= out <.12.1 . 3.1 . 4. 3. 4. 3. 7. 3. 3. 6. 6. 12.function (time. 4.. { PDJ <. byrow = TRUE.n) if (j == 1){ PDJ[1] <PDJ[2] <} else if (j PDJ[2] <PDJ[3] <- lsodes -rk1 rk1 == 2) { -rk3*Y[3] . 6. 5. lrw = 351) ## ======================================================================= ## application 3. y = y. y = y. 8.. 2. 6. 9. 3. lsodes estimates the structure of the Jacobian ## the Jacobian (vector) function is input ## ======================================================================= chemjac <. pars) { with (as. 2.

rk17*Y[1 ] PDJ[1 ] <.rk17*Y[12] PDJ[8] <. y = y.rk1 PDJ[1 ] <.-rk12*rk14 .rk2 *rk14 PDJ[12] <.-rk2 *rk14 .-rk17*Y[1 ] PDJ[12] <.rk11*rk14 PDJ[4] <.rk13*rk14 PDJ[11] <.rk7*Y[1 ] PDJ[4] <.rk4 PDJ[9] <.rk3*Y[2] .lsodes PDJ[4] <.rk17*Y[12] else if (j == 12) { PDJ[2] <.-rk15*Y[2] PDJ[5] <.rk12*rk14 else if (j == 7) { PDJ[7] <.rk3*Y[2] PDJ[6] <.rk6 .rk6 .rk5 .rk7*Y[1 ] else if (j == 4) { PDJ[2] <.rk17*Y[1 ] 69 } } } } } } } } } return(PDJ) }) } out3 <. rtol = rtol) . atol = atol.rk8 PDJ[1 ] <.-rk15*Y[2] .rk1 else if (j == 1 ) { PDJ[3] <.rk3*Y[3] PDJ[5] <. times = times.rk19*rk14 else if (j == 6) { PDJ[3] <.-rk13*rk14 .-rk19*rk14 .rk11*rk14 PDJ[3] <.rk17*Y[12] .rk19*rk14 PDJ[5] <.-rk5 . parms = parms.-rk7*Y[3] PDJ[6] <.rk16 PDJ[12] <.rk12*rk14 PDJ[6] <.rk15*Y[2] PDJ[7] <.rk15*Y[12] PDJ[12] <.-rk7*Y[3] .rk7*Y[1 ] PDJ[1 ] <.lsodes(func = chemistry.rk9 PDJ[12] <. jacvec = chemjac.rk2 *rk14 else if (j == 8) { PDJ[8] <.rk18 PDJ[1 ] <.-rk3*Y[2] PDJ[3] <.rk16 PDJ[9] <.rk7*Y[3] PDJ[7] <.rk4 else if (j == 5) { PDJ[2] <.rk8 PDJ[9] <.rk18 PDJ[9] <.-rk15*Y[12] else if (j == 3) { PDJ[2] <.rk9 PDJ[1 ] <.-rk11*rk14 .

"iteration"). which = select. method = c("lsoda". "ode23". "lsodes". parms is a vector or list of parameters. rtol = rtol. atol = atol. "rk4". If the initial values y has a names attribute. sparsetype = "sparseusr". subset = NULL. y. a wrapper around the implemented ODE solvers Usage ode(y.. "bdf".. If func is an R-function. time sequence for which output is wanted. "daspk"..) ## S3 method for class ’deSolve’ print(x. func. parms = parms. jacvec = chemjac. the names will be used to label the output matrix. t is the current time point in the integration. times. "radau". verbose = TRUE) ode General Solver for Ordinary Differential Equations Description Solves a system of ordinary differential equations...function(t. "bdf_d". either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. If y has a name attribute. parms. ..lsodes(func = chemistry. "impAdams". "impAdams_d". whose first element is a vector containing the derivatives of y with respect to time. parms.. "adams".. select = NULL. and whose next elements are .) ## S3 method for class ’deSolve’ summary(object. a vector. .70 ode ## ======================================================================= ## application 4.). . (optional) are any other arguments passed to the function. y is the current estimate of the variables in the ODE system.. The return value of func should be a list. "lsodar". The structure of the Jacobian (nonzero elements) AND ## the Jacobian (vector) function is input ## not very efficient. "vode".. times = times.. or a character string giving the name of a compiled function in a dynamically loaded shared library. lrw = 351. . "lsode". "ode45".) Arguments y times func the initial (state) values for the ODE system. "euler".. ## ======================================================================= out4 <. inz = nonzero.. it must be defined as: func <. the names will be available inside func. the first value of times must be the initial time. y = y.

the BDF with diagonal representation of the Jacobian. or a string ("lsoda". It returns one summary column for a multi-dimensional variable. It is best suited to solve stiff (systems of) equations. See package vignette "compiledCode" for more details. x object which select subset . This can be used for individual based models. and whose summary is to be calculated. If func is a string.frame. The default integrator used is lsoda. Options "bdf". this returns a data.ode 71 global values that are required at each point in times. logical expression indicating elements or rows to keep when calculating a summary: missing values are taken as FALSE additional arguments passed to the integrator or to the methods. In contrast to R’s default. "adams".. "rk4". Details This is simply a wrapper around the various ode solvers. "bdf_d". See the selected integrator for the additional options. "euler".. The option method = "bdf_d" selects the backward differentiation formula that uses JacobiNewton iteration (neglecting the off-diagonal elements of the Jacobian (it is equal to using method = "lsode". The default integrator used is lsoda. The derivatives should be specified in the same order as the state variables y. "bdf_d". either a function that performs integration. (equal to method = "lsode". "radau"."iteration"). Method "iteration" is special in that here the function func should return the new value of the state variables rather than the rate of change. an object of class deSolve. "daspk". then dllname must give the name of the shared library (without extension) which must be loaded before ode is called. "ode23". method = "adams" triggers the Adams method that uses functional iteration (no Jacobian used). The option method = "bdf" provdes a handle to the backward differentiation formula (it is equal to using method = "lsode"). "lsode". "lsodes". the integrator to use. as returned by the integrators. See package vignette for information about specifying the model in compiled code."vode". parms method parameters passed to func. It is often the best choice for solving non-stiff (systems of) . which variable/columns to be selected. "impAdams" or "impAdams_d" are the backward differentiation formula. or in those cases where the integration is performed within func). for difference equations. "impAdams" or "impAdams_d" . mf = 23). and to be printed or to be subsetted."lsodar". "ode45". the name(s) or the index to the variables whose summary should be estimated. or a list of class rkMethod. an object of class deSolve. as returned by the integrators. Default = all variables. "adams". and the implicit Adams method with diagonal representation of the Jacobian respectively (see details). "bdf". mf = 1 . the (explicit) Adams and the implicit Adams method. It is best suited to solve stiff (systems of) equations. See last example.

radau. • ode.function(Time. lsodes.knaw.rMort * Predator dPrey <.rIng * Prey * Predator GrowthPrey <. There will be one row for each element in times unless the integrator returns with an unrecoverable error. lsode. rkMethod.Ingestion .72 ode equations.deSolve for plotting the outputs. where ode is used. vode. Pars) { with(as.nl> See Also • plot. Examples ## ======================================================================= ## Example1: Predator-Prey Lotka-Volterra model (with logistic prey) ## ======================================================================= LVmod <. • lsoda. method = "impAdams" selects the implicit Adams method that uses Newton.Newton iteration. • aquaphy.rGrow * Prey * (1 . • dede general solver for delay differential equations • ode. although it is in fact implicit. mf = 12. mf = 13. State. ccl4model. If y has a names attribute.Raphson iteration (equal to method = "lsode". • ode. • ode. method = "impAdams_d" selects the implicit Adams method that uses Jacobi.3D for integrating 3-D models. i. Note: when functional iteration is used.soetaert@nioo. method = "daspk" may outperform method = "bdf".2D for integrating 2-D models. Author(s) Karline Soetaert <k. • rk. it will be used to label the columns of the output value. diagnostics to print diagnostic messages.list(c(State. daspk. the method is often said to be explicit. For very stiff systems. neglecting all off-diagonal elements (equal to method = "lsode". plus an additional column (the first) for the time value.e.GrowthPrey . lsodar.band for solving models with a banded Jacobian. { Ingestion <.1D for integrating 1-D models.Prey/K) MortPredator <. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the second element of the return from func. Pars)).

out[ . assimilation efficiency mmol/m3.5. type = "l".Ingestion * assEff . LVmod.c*S*P . .ode dPredator <. length = 1 1) ## external signal with rectangle impulse signal <. 2:3]. e = . d = .import . x. length(times))) . import = rep( .list(c(parms. g = .input(t) dS <. 1. 1. col = 1:2.b*S*P + g*C # substrate dP <. mortality rate of predator -. input) { with(as. rate of ingestion /day.c(dS. parms.d*C*P # producer dC <.MortPredator 73 return(list(c(dPrey.1. lty = 1:2) ## ======================================================================= ## Example2: Substrate-Producer-Consumer Lotka-Volterra model ## ======================================================================= ## Note: ## Function sigimp passed as an argument (input) to model ## (see also lsoda and rk examples) SPCmod <. lwd = 2) legend("topright". c("prey". c = .2 . by = 1) out <.f*C # consumer res <. . Predator = 2) times <. dPredator))) }) } pars <.c(rIng rGrow rMort assEff K = = = = = .ode(yini. 2 .2. dC) list(res) }) } ## The parameters parms <. .1. dP. growth rate of prey /day. pars) summary(out) ## Default plot method plot(out) ## User specified plotting matplot(out[ . 1]. x)). { import <. ylab = "Conc". carrying capacity yini <.c(Prey = 1. xlab = "time".seq( .c(b = .data.seq( .frame(times = times. ) ## vector of timesteps times <.function(t. 1 ) # # # # # /day.1. main = "Lotka-Volterra". "predator").e*P*C . f = . 2 .1. times.

284.5). rule = 2) ## Start values for steady state xstart <. "P". P = 1. ## ======================================================================= Parasite <P <. y = c(P = method = "iteration") ## Plot all 3 scenarios in one figure plot(out.5.y[2] f <. lty = 1.5). out3. times = :5 . xlab = "time".A Pnew <. y = c(P = method = "iteration") out2<. signal$import. parms = 35. ylab = "state") legend("topright". out[.82 # rate of increase A <. . times = :5 . times = times.15 # half-saturation density out <. xlab = "producer".5. col = 1:3. legend = c("S".2:4]. parms = parms. func = SPCmod. parms = 25. Hnew)) } rH <.ode(func = Parasite. out2.ode(y = xstart. ## Springer .1 # attack rate ks <. C = 1) ## Solve model out <. y. out[.5.5). 2 9. H = . .H) .using method = "iteration" ## The host-parasitoid model from Soetaert and Herman.exp(-f)) * exp(rH * (1 . type = "l". parms = ks. ks) { * P / (ks + H) * (1 .f) list (c(Pnew.74 ode signal$import[signal$times >= 1 & signal$times <= 11] <- .y[1] H <.ode(func = Parasite.par(mfrow = c(1. H = ."P"]. . type = "l". input = sigimp) ## Default plot method plot(out) ## User specified plotting mf <. ylab = "consumer") par(mfrow = mf) ## ======================================================================= ## Example3: Discrete time model .ode(func = Parasite.2. lty = 1:3. lwd = 2) . 2)) matplot(out[.H function(t. "C")) plot(out[.p. y = c(P = method = "iteration") out3<.1]. lwd = 2.2 sigimp <.H Hnew <. times = :5 .approxfun(signal$times.c(S = 1. H = ."C"].

or a character string giving the name of a compiled function in a dynamically loaded shared library. parms.ode. method= c("lsoda". "impAdams". a vector. "rk4"... bandwidth = 1. The return value of func should be a list. t is the current time point in the integration. y = c(P = .. names = NULL. If the initial values y has a names attribute. whose first element is a vector containing the derivatives of y with respect to time. the names will be available inside func. parms nspec .1D(y. time sequence for which output is wanted. "lsodar".function(t. If func is an R-function. restructure = FALSE. 2). method = "iteration") plot(out. then dimens should be specified. .1D 75 ## Same like "out". Usage ode. "adams". times = seq( . 5 . If NULL. but *output* every two steps ## hini = 1 ensures that the same *internal* timestep of 1 is used outb <. dimens = NULL. "ode45". "iteration"). parms. parameters passed to func. "lsode".1D Solver For Multicomponent 1-D Ordinary Differential Equations Description Solves a system of ordinary differential equations resulting from 1-Dimensional partial differential equations that have been converted to ODEs by numerical differencing.. parms is a vector or list of parameters.. (optional) are any other arguments passed to the function. and whose next elements are global values that are required at each point in times. "daspk". either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. func. the first value of times must be the initial time. If y has a name attribute.5. outb. H = . type = c("l". y. nspec = NULL. the number of species (components) in the model. "vode". .ode(func = Parasite. . parms = ks. "ode23". If func is a character string then integrator lsodes will be used. "bdf". See details. the names will be used to label the output matrix. times.). y is the current estimate of the variables in the ODE system. The derivatives should be specified in the same order as the state variables y. "p")) ode. "radau". "euler". hini = 1. "lsodes"..5).) Arguments y times func the initial (state) values for the ODE system. it must be defined as: func <.

. method = rkMethod("ode45ck") will trigger the Cash-Karp method of order 4(5). the method first calculates the sparsity pattern of the Jacobian. used for plotting. B[3]. I1 = 27627 I2 = 25932 . Use "vode".. the number of adjacent boxes over which transport occurs. if you get the error: DLSODES. Use one of the other Runge-Kutta methods via rkMethod. B[2]. or in those cases where the integration is performed within func) the names of the components.. additional arguments passed to the integrator. that are only subjected to transport between adjacent layers. This reformulation leads to a banded Jacobian with (upper and lower) half bandwidth = number of species.. "lsodar". Details This is the method of choice for multi-species 1-dimensional models. A[2]. Based on the dimension of the problem.. (for species A. For instance. set lrw equal to this number.. Values larger than 1 will not work with method = "lsodes". In the second try then.1D will return with an error message telling the size of the work array actually needed. "daspk".76 dimens method ode. B[1]. "euler". "impAdams" or "radau" may be best suited for mildly stiff problems. This can be used for individual based models... For instance. B[3]. "lsoda". . A[3]. it is possible that this will be too low.. Normally equal to 1 (box i only interacts with box i-1.ge. In this case.. ode. • The default method rearranges the state variables as A[1]. If NULL.RWORK length is insufficient to proceed.. LENRW (=I1). B[2]. A[3]..1D the number of boxes in the model. • The second method uses lsodes. A[2]. "ode45". Although a reasonable guess of lrw is made. lrw. Then the selected integrator solves the banded problem. and i+1).. "rk4". exceeds LRW (=I2) In above message. "lsode". More specifically. this method is to be used if the state variables are arranged per species: A[1].. Only used if the method is an integrator function. for difference equations. "adams" are most efficient for non-stiff problems. FALSE if explicit. then nspec should be specified. whether or not the Jacobian should be restructured. under the assumption that transport is only occurring between adjacent layers. Should be TRUE if the method is implicit. As lsodes is used to integrate. . Length needed is .. names bandwidth restructure . .. B[1].. Method "iteration" is special in that here the function func should return the new value of the state variables rather than the rate of change. Then lsodes is called to solve the problem. Ignored if the method is explicit. or "lsodes" if the model is very stiff. it may be necessary to specify the length of the real work array. B)) Two methods are implemented. "ode23". the integrator. Also allowed is to pass an integrator function.

Note It is advisable though not mandatory to specify both nspec and dimens.soetaert@nioo.nl> See Also • ode for a general interface to most of the ODE solvers. Value A matrix with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the second element of the return from func. lsoda. based on lsodes is the only solution method. Examples ## ## ## ## ## ## ## ======================================================================= example 1 a predator and its prey diffusing on a flat surface in concentric circles 1-D model with using cylindrical coordinates Lotka-Volterra type biology ======================================================================= .vode for the integration options. diagnostics to print diagnostic messages. • ode.3D for integrating 3-D models • lsodes. the settings of istate and rstate will be written to the screen. lsodar. The output will have the attributes istate. If verbose = TRUE.band. The first element of istate returns the conditions under which the last call to the integrator returned.ode. plus an additional column (the first) for the time value. it will be used to label the columns of the output value. If y has a names attribute. Normal is istate = 2. There will be one row for each element in times unless the integrator returns with an unrecoverable error.band for integrating models with a banded Jacobian • ode.e. For single-species 1-D models. See the help for the selected integrator for details. In this case. See the selected integrator for the additional options. if nspec * dimens == length(y)). two vectors with several useful elements.1D set lrw equal to 27627 or a higher value 77 If the model is specified in compiled code (in a DLL). you may also use ode. and rstate.knaw. then option 2. Author(s) Karline Soetaert <k. the solver can check whether the input makes sense (i.2D for integrating 2-D models • ode.lsode.

seq(dr/2.rMort * PRED ## Rate of change = Flux gradient + Biology dPREY <.-Da * diff(c(PRED[1].rep( .-diff(ri * FluxPrey)/rr/dr + GrowthPrey . . .function (time.list(parms). PREY[N]))/dri FluxPred <.2 N <.rGrow * PREY * (1-PREY/cap) MortPredator <. dPRED))) }) } ## ================== ## Model application ## ================== ## model parameters: R <.len = N) ri <.dr parms <. m 1 concentric circles thickness of each layer distance of center to mid-layer distance to layer interface dispersion distances m2/d. PREY.len = N+1) dri <.state[1:N] PRED <.by = dr. rr.1D ## Initial conditions: both present in central circle (box 1) only state <. rate of ingestion /day.-diff(ri * FluxPred)/rr/dr + Ingestion * assEff . assimilation efficiency density.state[(N+1):(2*N)] ## Fluxes due to diffusion ## at internal and external boundaries: zero gradient FluxPrey <. dri) { with (as.78 ## ================ ## Model equations ## ================ lvmod <. .MortPredator return (list(c(dPREY.R/N r <.5. ri. dispersion coefficient /day. growth rate of prey /day. . { PREY <.2. PRED.Ingestion dPRED <. 5. N.c(Da rIng rGrow rMort assEff cap = = = = = = .1 .by = dr.rIng * PREY * PRED GrowthPrey <. 2 * N) state[1] <.seq( .2 . PRED[N]))/dri ## Biology: Lotka-Volterra model Ingestion <. parms.-Da * diff(c(PREY[1]. carrying capacity ode.1 dr <. state. 1. mortality rate of pred -.state[N + 1] <. 1 ) # # # # # # # # # # # # total radius of surface. dr.

colors.out[. grid = r) # summaries of 1-D variables summary(out) # 1-D plots: matplot.contour(x = times. legend = TRUE.seq( . nspec = 2. times = times. main = "Prey density") # similar: image(out. times = times. which = "PREY". N = N. rr = r. m". "PRED"). color = topo.1D(out. subset = time == 1 ) matplot. Default: banded reformulation print(system. ylab = "Distance.ode. type = "l". by = 1) 79 # output wanted at these time intervals ## the model is solved by the two implemented methods: ## 1. dri = dri. grid = r.time( out <. m". parms = parms. PREY.function(t.ode. subset = time > 1 & time < 2 ) ## ## ## ## ## ======================================================================= Example 2.1D(y = state. names = c("PREY".ode.1D ## RUNNING the model: times <. 2 . parms = parms. xlab = "time. days"."PRED"). dr = dr. Using sparse method print(system.1D(y = state. 2-N+1: the prey # N+2:2*N+1: predators PREY <. xlab = "time. 2:(N + 1)] filled. Biochemical Oxygen Demand (BOD) and oxygen (O2) dynamics in a river ======================================================================= ## ================ ## Model equations ## ================ O2BOD <. ylab = "Distance. rr = r. method = "lsodes") )) ## ================ ## Plotting output ## ================ # the data in ’out’ consist of: 1st col times. dr = dr. state. func = lvmod. type = "l". dri = dri) )) ## 2. pars) { . ri = ri. N = N. y = r. nspec = 2. func = lvmod. main = "Prey density") image(out2. names = c("PREY". days". ri = ri.time( out2 <.1D(out.

dO2 = dO2))) } ## ================== ## Model application ## ================== ## parameters dx <.out[. by = dx) # m.1e3 # x <. first-order decay of BOD /day. distance from river /day.r * BOD ode. "O2")) ## ================ ## Plotting output ## ================ ## select oxygen (first column of out:time.colors filled..v * c(O2_ .seq( . O2BOD.length(x) r <. m". m") .3 # O2_ <.1D(y = state. 5 N <. air-sea exchange rate mmol/m3 saturated oxygen conc mmol/m3 riverine oxygen conc mmol/m3 riverine BOD concentration ## initial conditions: state <. nlevels = 5 .-diff(FluxO2)/dx . times.-diff(FluxBOD)/dx . ylab = "Distance from river. then BOD. N). y = x.2 # BOD_ <. BOD) FluxO2 <. rep(2 times <.80 BOD <. O2) BODrate <.c(rep(2 . then O2 O2 <.contour(x = times.1) . 2 . days".BODrate dO2 <. ylab = "Distance from river. (N + 2):(2 * N + 1)] color = topo. color = color.BODrate + p * (O2sat-O2) return(list(c(dBOD = dBOD.seq(dx/2.consumption + reaeration (O2) dBOD <. names = c("BOD". by = .v * c(BOD_ .1D # fluxes due to water transport # 1-st order consumption ## rate of change = flux gradient . xlab = "time. main = "Oxygen") ## or quicker plotting: image(out. O2. grid = x. xlab = "time. 5 # p <.25 # v <.1 # grid size of 25 meters velocity.state[(N+1):(2*N)] ## BOD dynamics FluxBOD <. N)) ## running the model ## step 1 : model spinup out <. parms = NULL.state[1:N] O2 <.5 # O2sat <.. m/day . nspec = 2.ode. days".

method = rkMethod("ode45ck") will trigger the Cash-Karp method of order 4(5). and whose next elements are global values that are required at each point in times. y. . times. parms. time sequence for which output is wanted.. "iteration"). the integrator. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t.) Arguments y times func the initial (state) values for the ODE system. "adams". the names will be available inside func. the names of the components. Usage ode.. the first value of times must be the initial time. Use one of the other Runge-Kutta methods via rkMethod.. the names will be used to label the output matrix. it must be defined as: func <. "impAdams" may be best suited for mildly stiff problems. see details. method= c("lsodes".ode.). y is the current estimate of the variables in the ODE system. If y has a name attribute. "euler". . "ode23".2D(y. (optional) are any other arguments passed to the function. The derivatives should be specified in the same order as the state variables y.2D Solver for 2-Dimensional Ordinary Differential Equations Description Solves a system of ordinary differential equations resulting from 2-Dimensional partial differential equations that have been converted to ODEs by numerical differencing. "adams" are most efficient for non-stiff problems. a vector. parms nspec dimens cyclicBnd names method . "rk4". Also allowed is to pass an integrator function. dimens. if not NULL then a number or a 2-valued vector with the dimensions where a cyclic boundary is used .. func. parms. parameters passed to func. or a character string giving the name of a compiled function in a dynamically loaded shared library.. 2: y-dimension. used for plotting. "ode45". If func is an R-function. 2-valued vector with the number of boxes in two dimensions in the model. nspec = NULL. The return value of func should be a list. "rk4". "euler".1: x-dimension. "ode45". .2D 81 ode.function(t. "ode23". t is the current time point in the integration. parms is a vector or list of parameters. For instance. whose first element is a vector containing the derivatives of y with respect to time. names = NULL. cyclicBnd = NULL. If the initial values y has a names attribute.. the number of species (components) in the model. Use "lsodes" if the model is very stiff.

For innstance. it is likely that this will be too low. or in those cases where the integration is performed within func) additional arguments passed to lsodes. There will be one row for each element in times unless the integrator returns with an unrecoverable error. In this case. then it is more efficient to use one of the explicit integration routines Value A matrix with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the second element of the return from func. This is when the first boxes in x-or y-direction interact with the last boxes. This can be used for individual based models. The output will have the attributes istate. For instance. whereas cyclicBnd = c(1. If lsodes is used to integrate. LENRW (=I1). it will be used to label the columns of the output value. the settings of istate and rstate will be written to the screen. set lrw equal to this number. See lsodes for the additional options.and y-direction. for difference equations. under the assumption that transport is only occurring between adjacent layers. The default is no cyclic boundaries. if you get the error: DLSODES. and if lsodes is used as the integrator. two vectors with several useful elements. Normal is istate = 2.2D If "lsodes" is used. In this case. it will probably be necessary to specify the length of the real work array. In the second try then. Although a reasonable guess of lrw is made.RWORK length is insufficient to proceed. Details This is the method of choice for 2-dimensional models. Method "iteration" is special in that here the function func should return the new value of the state variables rather than the rate of change. the method first calculates the sparsity pattern of the Jacobian.82 ode. and rstate. plus an additional column (the first) for the time value. exceeds LRW (=I2) In above message.. If the model is not stiff. that are only subjected to transport between adjacent layers.ge. then also the size of the work array should be specified (lrw) (see lsodes). ode. I1 = 27627 I2 = 25932 set lrw equal to 27627 or a higher value In some cases. The occurrence of cyclic boundaries can be toggled on by specifying argument cyclicBnd. Based on the dimension of the problem. See the help for the selected integrator for details. . Length needed is . a cyclic boundary condition exists. Then lsodes is called to solve the problem.2D will return with an error message telling the size of the work array actually needed.2) imposes a cyclic boundary for both x. If verbose = TRUE. The first element of istate returns the conditions under which the last call to the integrator returned. cyclicBnd = 1 indicates that a cyclic boundary is required only for the x-direction. . there will be extra non-zero fringes in the Jacobian which need to be taken into account. If y has a names attribute. lrw..

Pred[1:(N-1).])/dx dPred <.state[1:NN]) Pred <.matrix(nrow = N.2D Note 83 It is advisable though not mandatory to specify both nspec and dimens. zero fluxes near boundaries FluxPrey <. the solver can check whether the input makes sense (as nspec * dimens[1] * dimens[2] == length(y)). Da. N) ## 1. dx) { NN <.soetaert@nioo.rIng * Prey * Pred dPred <. Do not use this method for problems that are not 2D! Author(s) Karline Soetaert <k.]).-Da * rbind(zero.dPrey .] .])/dx .state[(NN+1):(2*NN)]) with (as.function (time. ncol = N.rGrow * Prey * (1. zero)/dx FluxPred <. Fluxes in x-direction.nl> See Also • ode for a general interface to most of the ODE solvers.band for integrating models with a banded Jacobian • ode. • ode.1D for integrating 1-D models • ode.]). ncol = N.(FluxPrey[2:(N+1).(Pred[2:N.dPred .(Prey[2:N.FluxPrey[1:N.matrix(nrow = N.-Da * rbind(zero.Prey[1:(N-1).rMort * Pred zero <.list(pars).] . state.ode. Examples ## ## ## ## ======================================================================= A Lotka-Volterra predator-prey model with predator and prey dispersing in 2 dimensions ======================================================================= ## ================== ## Model definitions ## ================== lvmod2D <.rep( .(FluxPred[2:(N+1). N.N*N Prey <. { ## Biology dPrey <. pars.knaw.3D for integrating 3-D models • lsodes for the integration options. diagnostics to print diagnostic messages.FluxPred[1:N.Prey/K) . In this case.rIng * Prey * Pred*assEff .] .] . zero)/dx ## Add flux gradient to rate of change dPrey <.

84
## 2. Fluxes in y-direction; zero fluxes near boundaries FluxPrey <- -Da * cbind(zero,(Prey[,2:N] - Prey[,1:(N-1)]), zero)/dx FluxPred <- -Da * cbind(zero,(Pred[,2:N] - Pred[,1:(N-1)]), zero)/dx ## Add flux gradient to rate of change dPrey <- dPrey - (FluxPrey[,2:(N+1)] - FluxPrey[,1:N])/dx dPred <- dPred - (FluxPred[,2:(N+1)] - FluxPred[,1:N])/dx return(list(c(as.vector(dPrey), as.vector(dPred)))) }) }

ode.2D

## =================== ## Model applications ## =================== pars <- c(rIng rGrow rMort assEff K = .2, = 1. , = .2 , = .5, = 5 ) # # # # # # # # # /day, rate of ingestion /day, growth rate of prey /day, mortality rate of predator -, assimilation efficiency mmol/m3, carrying capacity total length of surface, m number of boxes in one direction thickness of each layer m2/d, dispersion coefficient

R N dx Da

<- 2 <- 5 <- R/N <- . 5

NN <- N*N

# total number of boxes

## initial conditions yini <- rep( , 2*N*N) cc <- c((NN/2):(NN/2+1)+N/2, (NN/2):(NN/2+1)-N/2) yini[cc] <- yini[NN+cc] <- 1 ## solve model (5 state variables... use Cash-Karp Runge-Kutta method times <- seq( , 5 , by = 1) out <- ode.2D(y = yini, times = times, func = lvmod2D, parms = pars, dimens = c(N, N), names = c("Prey", "Pred"), N = N, dx = dx, Da = Da, method = rkMethod("rk45ck")) diagnostics(out) summary(out) ## Not run: ## plot results Col <- colorRampPalette(c("# 7F", "blue", "# 7FFF", "cyan", "#7FFF7F", "yellow", "#FF7F ", "red", "#7F for (i in seq(1, length(times), by = 1)) image(matrix(nrow = N, ncol = N, out[i, 2:(NN+1)]), col = Col(1 ), xlab = , zlim = range(out[,2:(NN+1)])) ## similar:

"))

ode.2D
image(out, xlab = "x", ylab = "y") ## End(Not run) # plot prey and pred at prey1 <- matrix (nrow data = subset(out, pred1 <- matrix (nrow data = subset(out, t = 1 ; first use subset to select data = N, ncol = N, select = "Prey", subset = (time == 1 ))) = N, ncol = N, select = "Pred", subset = (time == 1 )))

85

mf <- par(mfrow = c(1,2)) image(prey1 ) image(pred1 ) par (mfrow = mf) # same, using deSolve’s image: image(out, subset = (time == 1 )) ## ## ## ## ## ======================================================================= An example with a cyclic boundary condition. Diffusion in 2-D; extra flux on 2 boundaries, cyclic boundary in y =======================================================================

diffusion2D <- function(t, Y, par) { y <- matrix(nrow = nx, ncol = ny, data = Y) dY <- -r * y # consumption BNDx <- rep(1, nx) # boundary concentration BNDy <- rep(1, ny) # boundary concentration

# vector to 2-D matrix

## diffusion in X-direction; boundaries=imposed concentration Flux <- -Dx * rbind(y[1,] - BNDy, (y[2:nx,] - y[1:(nx-1),]), BNDy - y[nx,])/dx dY <- dY - (Flux[2:(nx+1),] - Flux[1:nx,])/dx ## diffusion in Y-direction Flux <- -Dy * cbind(y[,1] - BNDx, (y[,2:ny]-y[,1:(ny-1)]), BNDx - y[,ny])/dy dY <- dY - (Flux[,2:(ny+1)] - Flux[,1:ny])/dy ## extra flux on two sides dY[,1] <- dY[,1] + 1 dY[1,] <- dY[1,] + 1 ## and exchange between sides on y-direction dY[,ny] <- dY[,ny] + (y[,1] - y[,ny]) * 1 return(list(as.vector(dY))) } ## dy Dy r parameters <- dx <- 1 # grid size <- Dx <- 1 # diffusion coeff, X- and Y-direction <- . 5 # consumption rate

86
nx <- 5 ny <- 1 y <- matrix(nrow = nx, ncol = ny, 1) ## model most efficiently solved with lsodes - need to specify lrw print(system.time( ST3 <- ode.2D(y, times = 1:1 , func = diffusion2D, parms = NULL, dimens = c(nx, ny), verbose = TRUE, names = "Y", lrw = 4 , atol = 1e-1 , rtol = 1e-1 , cyclicBnd = 2) )) # summary of 2-D variable summary(ST3) # plot output at t = 1 t1 <- matrix (nrow = nx, ncol = ny, data = subset(ST3, select = "Y", subset = (time == 1 ))) persp(t1 , theta = 3 , border = NA, phi = 7 , col = "lightblue", shade = .5, box = FALSE) # image plot, using deSolve’s image function image(ST3, subset = time == 1 , method = "persp", theta = 3 , border = NA, phi = 7 , main = "", col = "lightblue", shade = .5, box = FALSE) ## Not run: zlim <- range(ST3[, -1]) for (i in 2:nrow(ST3)) { y <- matrix(nrow = nx, ncol = ny, data = ST3[i, -1]) filled.contour(y, zlim = zlim, main = i) } # same image(ST3, method = "filled.contour") ## End(Not run)

ode.3D

ode.3D

Solver for 3-Dimensional Ordinary Differential Equations

Description Solves a system of ordinary differential equations resulting from 3-Dimensional partial differential equations that have been converted to ODEs by numerical differencing.

Use "lsodes" if the model is very stiff. that are only subjected to transport between adjacent layers. This can be used for individual based models. the names of the components. If y has a name attribute. "adams" are most efficient for non-stiff problems.function(t. "impAdams" may be best suited for mildly stiff problems..3D Usage 87 ode.3D(y. "euler". the integrator. the first value of times must be the initial time. dimens. if not NULL then a number or a 3-valued vector with the dimensions where a cyclic boundary is used . . and whose next elements are global values that are required at each point in times. "ode23". cyclicBnd = NULL. "ode45". . method = rkMethod("ode45ck") will trigger the Cash-Karp method of order 4(5). Details This is the method of choice for 3-dimensional models.. y. y is the current estimate of the variables in the ODE system. "rk4". the number of species (components) in the model. func.. a vector. "adams".. "rk4". . . or a character string giving the name of a compiled function in a dynamically loaded shared library. "euler". names = NULL. method = c("lsodes". Also allowed is to pass an integrator function. If func is an R-function. "iteration"). parms nspec dimens names cyclicBnd method . for difference equations. it must be defined as: func <.. The derivatives should be specified in the same order as the state variables y. used for plotting. nspec = NULL. 2: y-dimension.1: x-dimension.ode.) Arguments y times func the initial (state) values for the ODE system. Method "iteration" is special in that here the function func should return the new value of the state variables rather than the rate of change.. parameters passed to func.. 3: z-dimension. whose first element is a vector containing the derivatives of y with respect to time. times. The return value of func should be a list. "ode23". "ode45". For instance. the names will be used to label the output matrix.. parms. parms.). (optional) are any other arguments passed to the function. t is the current time point in the integration. If the initial values y has a names attribute. or in those cases where the integration is performed within func) additional arguments passed to lsodes. parms is a vector or list of parameters. time sequence for which output is wanted. 3-valued vector with the number of boxes in three dimensions in the model. Use one of the other Runge-Kutta methods via rkMethod. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. the names will be available inside func.

2D will return with an error message telling the size of the work array actually needed. . exceeds LRW (=I2) In above message. For instance. In this case. ode.nl> See Also • • • • • ode for a general interface to most of the ODE solvers. two vectors with several useful elements. it will probably be necessary to specify the length of the real work array.RWORK length is insufficient to proceed. See the help for the selected integrator for details. the method first calculates the sparsity pattern of the Jacobian. the settings of istate and rstate will be written to the screen. Value A matrix with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the second element of the return from func. Normal is istate = 2. I1 = 27627 I2 = 25932 set lrw equal to 27627 or a higher value. Then lsodes is called to solve the problem. In the second try then. If y has a names attribute. Although a reasonable guess of lrw is made.knaw. and rstate.soetaert@nioo.88 ode. diagnostics to print diagnostic messages. it is likely that this will be too low. lrw. See lsodes for the additional options. There will be one row for each element in times unless the integrator returns with an unrecoverable error. If verbose = TRUE.ge. the solver can check whether the input makes sense (as nspec*dimens[1]*dimens[2]*dimens[3] == length(y)). In this case. ode. set lrw equal to this number. Note It is advisable though not mandatory to specify both nspec and dimens.1D for integrating 1-D models ode.2D for integrating 2-D models lsodes for the integration options. if you get the error: DLSODES. plus an additional column (the first) for the time value.3D Based on the dimension of the problem. LENRW (=I1). under the assumption that transport is only occurring between adjacent layers. Length needed is . The first element of istate returns the conditions under which the last call to the integrator returned. it will be used to label the columns of the output value. The output will have the attributes istate. Do not use this method for problems that are not 3D! Author(s) Karline Soetaert <k.band for integrating models with a banded Jacobian ode. As lsodes is used to integrate.

-r*yy # consumption BND <. 1)) else if (along == 2) aperm(array(dim = dimens. Array. c(1. 25 89 # grid size # diffusion coeff.Flux[. Mat2)). yy. yy.2:(n+2)] . Mat2)) else if (along == 1) aperm(array(dim = dimens.])/dy dY[] <.dY[] . along = 2) Flux <. Mat2.])/dx ## diffusion in y-direction BNDy <. aperm(Array.function(t.-Dx * (BNDx[2:(n+2).n. aperm(Array. BND. X.dY[] .Flux[1:n.Flux[.1 <.array(dim=c(n.Dz <-1 <.mbind(BND.matrix(nrow = n. c(1. BND. 2.data=1 .2:(n+2).mbind(BND.3D Examples ## ======================================================================= ## Diffusion in 3-D..] . data = c(Mat1.BNDx[1:(n+1). data = Y) # vector to 3-D array dY <.function (Mat1. 2) if (along == 3) array(dim = dimens. n).and Y-direction # consumption rate <. Y.(Flux[2:(n+1)... data=c(Mat1. 3. 3.] . c(3.1:(n+1)])/dz dY[] <. imposed boundary conditions ## ======================================================================= diffusion3D <.-Dz * (BNDz[.vector(dY))) } ## dy Dy r n y parameters <.] . data = 1) # boundary concentration ## diffusion in x-direction ## new array including boundary concentrations in X-direction BNDx <. par) { ## function to bind two matrices to an array mbind <. Mat2)). 1)).(Flux[. yy.2:(n+1)] .-Dy * (BNDy[.n). 2)) } yy <.dx <.(Flux[. along = 1) ## diffusive Flux Flux <. 2. along = 1) { dimens <. c(3. ncol = n. BND. 2)).ode. n..2:(n+1).flux gradient dY[] <..] .BNDy[..1:n.mbind(BND. .) .1:n])/dz return(list(as.])/dx ## rate of change = . Array. data = c(Mat1.])/dy ## diffusion in z-direction BNDz <.dz <-1 <. along = 3) Flux <.dim(Array) + c( ..1:(n+1)..BNDz[.dY[] .array(dim=c(n.Dx <..

y is the current .contour(y[.time( RES <. t is the current time point in the integration.. verbose = TRUE) )) y <. parms = NULL. nspec = NULL.. the default (for n>2 .array(dim=c(n.contour(y[.). the first value of times must be the initial time. the names will be used to label the output matrix.) Arguments y times func the initial (state) values for the ODE system. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. func. lrw = 12 . If y has a name attribute. n.main=i. bandup = nspec.. Runge-Kutta more efficient) print(system. it must be defined as: func <. or a character string giving the name of a compiled function in a dynamically loaded shared library.palette=terrain. n).band Solver for Ordinary Differential Equations. n). color. banddown = nspec.array(dim = c(n.n.. times = 1:2 . n/2]. names = NULL.-1]) filled. Suitable for 1-D models that include transport only between adjacent layers and that model only one species.ode.1D).data=RES[i. data = RES[nrow(RES). atol = 1e-1 .palette = terrain.band ode. -1]) filled. times. dimens = c(n. but does not rearrange the state variables (in contrast to ode.colors) summary(RES) ## Not run: for (i in 2:nrow(RES)) { y <.color. dimens = NULL.function(t. y. If func is an R-function. rtol = 1e-1 . Assumes a banded Jacobian matrix. . time sequence for which output is wanted. a vector. Usage ode. .colors) } ## End(Not run) ode. Assumes a Banded Jacobian Description Solves a system of ordinary differential equations.. . method = "lsode". n. parms.band(y. func = diffusion3D.3D(y.n).n/2]. parms.90 ## use lsodes.

Author(s) Karline Soetaert <k. For multi-species 1-D models. two vectors with several elements. If y has a names attribute. the number of *species* (components) in the model. The output will have the attributes istate and rstate... (optional) are any other arguments passed to the function. This is the method of choice for single-species 1-D reactive transport models. B[2]. If verbose = TRUE. B). plus an additional column (the first) for the time value.. the names of the components. whose first element is a vector containing the derivatives of y with respect to time. B[1]. By default.. If NULL. additional arguments passed to the integrator. and whose next elements are global values that are required at each point in times. the model function will have the species arranged as A[1]. Normal is istate = 2. then nspec should be specified.soetaert@nioo. Value A matrix with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the second element of the return from func. in this case.The derivatives should be specified in the same order as the state variables y. "radau". A[3]. per species (e. B[1].band 91 estimate of the variables in the ODE system. for species A. parms nspec dimens bandup banddown method names . See the help for the selected integrator for details. "lsodar". use ode. the names will be available inside func.g. the first element of istate returns the conditions under which the last call to the integrator returned. B[3]. "lsoda"... • ode. it will be used to label the columns of the output value. used for plotting.. .1D. . Details parameters passed to func. There will be one row for each element in times unless the integrator returns with an unrecoverable error. the number of boxes in the model.1D for integrating 1-D models . one of "vode". the number of nonzero bands above the Jacobian diagonal. the settings of istate and rstate will be written to the screen.. .. the integrator to use. B[3]. parms is a vector or list of parameters. the number of nonzero bands below the Jacobian diagonal. . B[2]. If the initial values y has a names attribute. this method can only be used if the state variables are arranged per box.ode.nl> See Also • ode for a general interface to most of the ODE solvers. A[1]. The return value of func should be a list. A[2]. A[3].knaw. A[2]. "lsode". See the selected integrator for the additional options..

5. nspec = 1. diagnostics to print diagnostic messages.c ( .c(APHIDS = APHIDS) # initialise state variables ## RUNNING the model: times <. Springer. .2D for integrating 2-D models • ode. A practical guide to ecological modelling. vode for the integration options.3D for integrating 3-D models • lsode. Examples ## ## ## ## ## ======================================================================= The Aphid model from Soetaert and Herman. names = "Aphid") ## ================ .ode. 2 . rep(1.5) Flux <. length. ))/deltax dAPHIDS <. times = numboxes) APHIDS[3 :31] <. numboxes-1). 1 m intervals Distance <.-D*diff(c( . 2 9. ind/m2 ## aphids present only on two central boxes APHIDS <.seq( . APHIDS.rep( . parms = .band ## 1-D diffusion model ## ================ ## Model equations ## ================ Aphid <.1 state <.-diff(Flux)/delx + APHIDS*r list(dAPHIDS) } ## ================== ## Model application ## ================== ## the model D <r <delx <numboxes <parameters: . Using R as a simulation platform. parameters) { deltax <. 1 # /day net growth rate 1 # m thickness of boxes 6 # the output ## distance of boxes on plant. ======================================================================= ode. Aphid.band(state. times.3 # m2/day diffusion rate . m.92 • ode. by = 1) # output wanted at these time intervals out <. by = delx.5.out = numboxes) ## Initial conditions. lsoda.seq(from = . APHIDS.function(t. lsodar.

. ask = NULL. . 4 . subset = NULL.. . which = select. . legend = FALSE. type = "l") 93 ## End(Not run) plot. obs = data. xlab = "time. 2 . subset = NULL. grid = NULL. obs = NULL.1 . 6 ). which = select.contour". 2 . 3 . select = NULL. which = select. delay = .5. select = NULL.25.) plot. . add.deSolve ## Plotting output ## ================ image(out.1. ask = NULL. col="red")) ## Not run: plot. ylab = "Distance on plant. grid = Distance.1D (x. grid = NULL.cbind(dist = c( . grid = Distance.1D(out.) ## S3 method for class ’deSolve’ image(x. obspar = list(pch = 18. type = "l"....25.1. m"...) ## S3 method for class ’deSolve’ subset(x. method = "image". select = NULL. Aphid = c( .1D(out. by = 1 )) # add an observed dataset to 1-D plot (make sure to use correct name): data <.contour = FALSE. . subset = NULL) .1D(out. cex = 2. Usage ## S3 method for class ’deSolve’ plot(x. obspar = list(). xyswap = FALSE. obspar = list(). subset = time %in% seq( .. Image and Histogram Method for deSolve Objects Description Plot the output of numeric integration routines.. grid = Distance. obs = NULL. subset = NULL) ## S3 method for class ’deSolve’ hist(x. 2 . .. subset = time %in% seq( . grid = Distance. )) matplot.deSolve Plot. subset = NULL. ask = NULL. 5 .. type = "l".plot. select = NULL. ask = NULL. select = 1:(ncol(x)-1). . . which = select. . which = select. days". . main = "Aphid density on a row of plants") matplot. method = "filled. by = 1 ). vertical = FALSE..

obs = NULL. for plotting the observed data. vertical = FALSE. obspar = list(). as returned by the integrators.see second example. select = NULL. . For plot. By default the first column of an observed data set should contain the timevariable.1D). then 1. common to both obs and x will be plotted. additional graphics arguments passed to points.2D). or the x. subset = NULL. which = select. The other columns contain the observed values and they should have names that are known in x. Useful for drawing vertical profiles. If obs is a list containing multiple observed data sets. except time.deSolve. where the first three columns contain (name. Useful for drawing vertical profiles.frames and/or matrices containing observed data. for xlim.. then the variables. time. which select subset ask add. specifying each data set separately. if TRUE. the user is asked before each plot.deSolve an object of class deSolve. grid = NULL. ask = NULL.1D: the 1-D grid as a vector (for output generated with ode.1D (x. only for image plots and for plot.frame or matrix with "observed data" that will be added as points to the plots. the name(s) or the index to the variables that should be plotted or selected. "filled. it is allowed to pass several objects of class deSolve after x (unnamed) . if TRUE. value).) Arguments x plot. see example 2. x-and y-values are swapped. if NULL the user is only asked if more than one page of plots is necessary and the current graphics device is set interactive. then it is assumed that the data are presented in long (database) format. "persp".g.1D to enable animations. ylim). if TRUE. see par(ask) and dev. which variable/columns to be selected. obs can also be a list with multiple data. the x-axis is on top.contour". the name of the plotting method to use. the y-axis is from top to bottom. if TRUE.and y-grid. will add contours to the image plot. adds a delay (in milliseconds) between consecutive plots of plot. logical expression indicating elements or rows to keep in select: missing values are taken as FALSE logical. a data. "contour". If obs is not NULL and which is NULL. as a list (for output generated with ode. then the graphics arguments can be a vector or a list (e.contour method grid xyswap vertical delay obs obspar . margin 3 and the main title gets the value of the x-axis. If the first column of obs consists of factors or characters (strings)..94 matplot. and to be plotted.interactive. then x-and y-values are swapped and the y-axis is from top to bottom. one of "image". xyswap = FALSE. Default = all variables.

cex. For plot. axes.main) or according to the number of lines within one plot (other parameters e. plot will always have times on the x-axis. main. cex. an image with times as x.) so it is possible to assign specific axis labels to individual plots. frame.panel.panel.function(t. a color legend will be drawn on the right of each image. as passed by obspar can be vectorized.2D. Similarly.e. col. "filled. as solved with ode.1D which will plot how spatial variables change with time. lwd etc. n. different plotting style. For problems solved with ode. Details The number of panels per page is automatically determined up to 3 x 3 (par(mfrow = c(3. for all times. . sub. according to the number of observed data sets. These plots will have the grid on the x-axis. A Predator-Prey model with 4 species in matrix formulation ## ======================================================================= LVmatrix <. 95 additional arguments. ode.r * n + n * (A %*% n) return(list(c(dn))) }) } parms <. parms) { with(parms. ann. ylab. In the first case.last. Plotting parameter ylim. Parameters are vectorized. an x-y plot will be created. if TRUE. deSolve Examples ## ======================================================================= ## Example 1. log. image or hist For plot.axis. Other graphical parameters can be passed as well. or xlim can also be a list to assign different axis limits to individual plots. resp. and plot. xlim. 3))).default. In this case.deSolve.see second example.1D and ode. See Also print.g.plot.first.plot. in order to use the respective plotting method. "contour" or "persp". ylim. Set mfrow equal to NULL to avoid the plotting function to change user-defined mfrow or mfcol settings. asp.1D. the column names should be the same. must be matched exactly.. and to be plotted on the same graphs as x . the arguments after . This default can be overwritten by specifying user-defined settings for mfrow or mfcol. . the user will be asked to confirm page changes. the dots may contain other objects of class deSolve. the graphical parameters for observed data. i. For images.1D. either according to the number of plots (xlab. x and and these other objects should be compatible.list( . in second case. { dn <.cex.deSolve legend . as returned by the integrators. lty.lab. it is possible to pass an argument method which can take the values "image" (default).and the grid as y-axis will be created. The graphical arguments are passed to plot.deSolve. Image plots will only work for 1-D and 2-D variables.contour".. Unless ask = FALSE. it may be more useful to use plot.deSolve.

.96 r = c(r1 = . "Prey 2". "Pred 2"). . parms3) # plot all three outputs plot(out. lwd = 2) plot(out[. . mfrow = NULL. . parms) ## Basic line plot plot(out.2. . LVmatrix. and observations ## ======================================================================= # New runs with different parameter settings parms2 <. # predator 1. . . LVmatrix. by = . times. . col = c("red". r2 = .c(prey1 = 1."pred1"]. "Pred 1". pred1 = 2. . . # prey 2 .. type = "l") ## User-specified axis labels plot(out.1."pred2"].1. parms2) # New runs with different parameter settings parms3 <. xlab = "Time (d)". main = "Time Series") ## Set user-defined mfrow pm <..ode(y.ode(y. xlab = "Time (d)". ylab = "pred1".. 1. . ncol = 4.1. ylab = c("Prey 1". type = "l".1. # predator 2. .1. ylab = c("Prey 1".ode(y.. type = "l".. to = 5 ."prey1"].par (mfrow = c(2. .seq(from = . 2. LVmatrix. lwd = 2) plot(out[. "Pred 1". r3 = . . A = matrix(c( . 2.2. out2. out3. pred2 = 2) out <. type = "l". byrow=TRUE) ) times <. times.1).deSolve ## ======================================================================= ## Example 2. ). "pred2"). 5 out3 <.2 out2 <.. main = "Time Series". type = "l".lwd = 2) ## restore graphics parameters par ("mfrow" = pm) plot. "Prey 2". 2)) ## "mfrow=NULL" keeps user-defined mfrow plot(out.parms parms3$r[1] <. ylab = "pred2". 1. times. . Add second and third output. r4 = . out[. . out[. prefers prey 2 nrow = 4.parms parms2$r[1] <. xlab="prey1". xlab = "prey2". # prey 1 . which = c("prey1". . "blue". prefers prey 1 ."prey2"]. type = "l". . "darkred")) .1) y <. prey2 = 1. "Pred 2"). .

as. 2 9.data. type = "l". 5 plot(out. cex = 2. 5 ). "red". by = 3 ). 1 . type = "l".3). cex = 2)) plot(out. col = "red") . breaks = 5 . obspar = c(pch = 18.5. . obs = obs. 4 ).-diff(Flux)/delx + APHIDS * r . type = "l".1] %in% seq(1 .1] %in% seq(1 . log = c("y".7. which = c("prey1". 1)) OBS plot(out.data. 4. rep(1. Using R as a simulation platform. subset = prey1 < . 5 . . log plot(out. ]) ## second set of ’observed’ data and two outputs obs2 <. cex = 2)) # a subset only: plot(out. "black").frame(out2[out2[. . numboxes . type = "p") # Simple histogram hist(out.1). col = c("red". "blue")). time = c(1 . subset = prey1<1 & prey2 < 1) # different parameters per plot hist(out. obs = list(obs. ======================================================================= ## 1-D diffusion model ## ================ ## Model equations ## ================ Aphid <. APHIDS. ))/deltax dAPHIDS <.data.frame(out[out[.5. col = "darkblue". breaks = 5 ) hist(out.5.5 )) ## ## ## ## ## ======================================================================= The Aphid model from Soetaert and Herman. A practical guide to ecological modelling. breaks = c(1 .plot.-D * diff(c( . col = "darkblue".5) Flux <. c( . out2. obs = obs. obspar = list(pch = 18:19.deSolve 97 ## ’observed’ data obs <. "prey1"). value = c( . rep("prey2". 5.function(t. "blue"). 25 .c ( . ]) ## manual xlim. obs2). 1 . col = c("darkblue".""). xlim = list(c(1 . "orange".as. obspar = list(pch = 18. .frame(name = c(rep("prey1". which = "prey1". parameters) { deltax <. Springer. APHIDS. col = c("red".2)). by = 5 ). obs = OBS. 4 ))) ## data in ’long’ format OBS <.

lwd = 2. ask = FALSE.deSolve ## distance of boxes on plant. by = delx.1D(state. times = numboxes) APHIDS[3 :31] <. m". theta = 3 ) FluxAphid <.98 list(dAPHIDS.1D(out. main = "Aphid model".ode.subset(out. type = "l". m. main = "Aphid model". ylab = "distance. grid = Distance. type = "l". xyswap = TRUE. type = "l". m". m". names = "Aphid") image(out. xyswap = TRUE. times. grid = Distance. ask = FALSE.5. border = NA. lwd = 2. by = 1 ). 1 m intervals Distance <. col = "grey") ## Not run: plot(out. 1 # /day net growth rate 1 # m thickness of boxes 6 plot.1 state <. method = "persp".c(APHIDS = APHIDS) # initialise state variables ## RUNNING the model: times <.seq(from = . nspec = 1. type = "l". 1)) plot. lty = 1. grid = Distance. lwd = 2. main = "Aphid model".1D(out. parms = .out = numboxes) ## Initial conditions.rep( . Flux = Flux) } ## ================== ## Model application ## ================== ## the model D <r <delx <numboxes <parameters: . subset = time %in% seq( . length.1D(out. lty = 1. ind/m2 ## aphids present only on two central boxes APHIDS <.3 # m2/day diffusion rate . legend = TRUE. subset = time < 1 ) image(out. mfrow = c(1. xyswap = TRUE. lwd = 2.seq( . legend = TRUE) # restricting time image(out. ylab = "distance.1D(out. select = "Flux". subset = time < 5 ) matplot. lty = 1) matplot. 2 . subset = time < 5 ) matplot. ylab = "distance. by = 1) # output wanted at these time intervals out <. Aphid. xyswap = TRUE) ## End(Not run) . 2 .

nind = c(length(y). Wanner. func can also be a character string giving the name of a compiled function in a dynamically loaded shared library. written by Ernst Hairer and G. hmax = NULL. the first value of times must be the initial time. nout = . rpar = NULL. initforc = NULL. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. If y has a name attribute. (if mass is supplied then the problem is assumed a DAE). rtol = 1e-6. massdown = NULL. or the right-hand side of the equation M dy/dt = f (t. times. ipar = NULL. atol = 1e-6. func. events=NULL. ynames = TRUE. verbose = FALSE. fcontrol = NULL. which implements the 3-stage RADAU IIA method. if only one step is to be taken. . The R function radau provides an interface to the Fortran solver RADAU5. initfunc = dllname. massup = NULL. If func is an R-function. maxsteps = 5 . the names will be used to label the output matrix. nroot = . lags = NULL. bandup = NULL. y) . It implements the implicit Runge-Kutta method of order 5 with step size control and continuous output. ). parms. set times = NULL. it must be defined as: . initpar = parms. dllname = NULL.. y) or linearly implicit differential algebraic equations in the form: M dy/dt = f (t. . outnames = NULL.. rootfunc = NULL. jactype = "fullint". jacfunc = NULL. mass = NULL. The system of ODEs or DAEs is written as an R function or can be defined in compiled code that has been dynamically loaded. hini = . time sequence for which output is wanted. banddown = NULL. y) if a DAE.) Arguments y times func the initial (state) values for the ODE system. Usage radau(y. forcings = NULL.radau 99 radau Implicit Runge-Kutta RADAU IIA Description Solves the initial value problem for stiff or nonstiff systems of ordinary differential equations (ODE) in the form: dy/dt = f (t.

The return value of func should be a list.. In some circumstances.100 radau func <. where the ˙ ith row contains the derivative of dyi /dt with respect to yj . the problem is a linearly implicit DAE and defined as M dy/dt = f (t. it should be of dimension n2 where n is the number of y-values. if a DAE system: a three-valued vector with the number of variables of index 1.). 2. in case it is banded. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. absolute error tolerance. The sum of the variables of different index should equal N. either a scalar or an array as long as y. if the system is stiff. "fullusr". rtol atol jacfunc jactype mass massup massdown . 3 respectively.either full or banded and estimated internally or by user. the structure of the Jacobian. If func is a string. the names will be available inside func. and the mass-matrix is stored diagonal-wise with element (i. If not NULL. "bandusr" or "bandint" . number of non-zero bands below the diagonal of the mass matrix. If mass = NULL then the model is an ODE (default) number of non-zero bands above the diagonal of the mass matrix. y). relative error tolerance. t is the current time point in the integration. if not NULL. the mass matrix. jacfunc should return a matrix ∂ y/∂y. y is the current estimate of the variables in the ODE system. supplying jacfunc can speed up the computations. or a string giving the name of a function or subroutine ˙ in ‘dllname’ that computes the Jacobian (see vignette "compiledCode" from package deSolve. j) stored in mass(i . If the mass-matrix M is full. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices). parms. for more about this option)...function(t. If the Jacobian is banded. then dllname must give the name of the shared library (without extension) which must be loaded before radau() is called. one of "fullint". the total number of variables. in case it is banded. y. See details.. If the Jacobian is a full matrix. See example. parms is a vector or list of parameters. either a scalar or an array as long as y. If the initial values y has a names attribute. an R function that computes the Jacobian of the system of differential equations ∂ yi /∂yj . (optional) are any other arguments passed to the function. whose first element is a vector containing the derivatives of y with respect to time. The R calling sequence for jacfunc is identical to that of func. parms nind vector or list of parameters used in func or jacfunc. The equations must be defined such that the index 1 variables precede the index 2 variables which in turn precede the index 3 variables. See details.. and whose next elements are global values that are required at each point in times. See deSolve package vignette "compiledCode" for more details.j + mumas + 1. . The derivatives should be specified in the same order as the state variables y. j). rotated row-wise. if banded the number of rows should be less than n.

only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func.you have to perform this check in the code . this may speed up the simulation especially for multi-D models. The R calling sequence for rootfunc is identical to that of func. average maximal number of steps per output interval taken by the solver.g. C++). only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. verbose nroot hmax hini ynames bandup banddown maxsteps dllname initfunc initpar rpar ipar nout outnames . See vignette "compiledCode" from package deSolve. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. in case the Jacobian is banded. RADAU only accepts the maximal number of steps for the entire integration. the initial step size is set equal to 1e-6. This argument is defined such as to ensure compatibility with the Livermore-solvers. in case the Jacobian is banded. rootfunc should return a vector with the function values whose root is sought. if not NULL. if rootfunc is an R-function. only used if ‘dllname’ is specified: the number of constraint functions whose roots are desired during the integration. If not specified. only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. the solver estimates the number of roots. number of non-zero bands above the diagonal.radau rootfunc 101 if not NULL. See vignette "compiledCode" from package deSolve. number of non-zero bands below the diagonal. only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. if 0. if TRUE: full output to the screen.see details. e. as provided in ‘dllname’. present in the shared library. an R function that computes the function whose root has to be estimated or a string giving the name of a function or subroutine in ‘dllname’ that computes the root function. If 0. Note: it is not automatically checked whether this is indeed the number of output variables calculed in the DLL . a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. present in the shared library. no maximal size is specified. hmax is set to the largest difference in times. Usually 1e-3 to 1e-5 is good for stiff equations logical. an optional maximum value of the integration stepsize.See vignette "compiledCode" from package deSolve. initial step size to be attempted. to avoid that the simulation possibly ignores short-term events. to initialise the common blocks (FORTRAN) or global variables (C. if FALSE names of state variables are not passed to function func. will print the diagnostiscs of the integration . These names will be used to label the output matrix. and this is calculated as length(times) * maxsteps. the name of the initialisation function (which initialises values of parameters).

specified by user function jacfunc. It MUST be present if forcings has been given a value. radau may return false roots. See events for more information. i. radau can find the root of at least one of a set of constraint functions rootfunc of the independent and dependent variables. as well as in an R-function.102 forcings radau only used if ‘dllname’ is specified: a list with the forcing function data sets. which roughly keeps the local error of y(i) below rtol(i) ∗ abs(y(i)) + atol(i). 2002. the name of the forcing function initialisation function. A list that specifies timelags. with (time. The diagnostics of the integration can be printed to screen by calling diagnostics. max(times)] is done by taking the value at the closest data extreme. A list that specifies events. See forcings or vignette compiledCode. It then returns the solution at the root if that occurs sooner than the specified stop condition. when the value of a state variable is suddenly changed. A list of control parameters for the forcing functions. Details The work is done by the FORTRAN subroutine RADAU5. Caution: Because of numerical errors in the function rootfun due to roundoff and integration error. dede for more information. the number of steps that has to be kept. calculated internally by the solver.. The input parameters rtol. whose documentation should be consulted for details. To be used for delay differential equations. jactype = "bandusr" a banded Jacobian. See vignette("deSolve") from the deSolve package for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. additional arguments passed to func and jacfunc allowing this to be a generic function.. calculated by radau. interpolation outside the interval [min(times). There are four standard choices for the Jacobian which can be specified with jactype. jactype = "fullusr" a full Jacobian. See forcings or package vignette "compiledCode". Information about linking forcing functions to compiled code is in forcings (from package deSolve). if not NULL. See timelags. Models may be defined in compiled C or FORTRAN code. See forcings or package vignette "compiledCode". Inspection of the example below shows how to specify both a banded and full Jacobian. the size of the bands specified by bandup and banddown. jactype = "bandint" a banded Jacobian. value). i. If verbose = TRUE. The options for jactype are jactype = "fullint" a full Jacobian. or return the same root at two or more nearly equal values of time. and atol determine the error control performed by the solver. initforc fcontrol events lags . each present as a two-columned matrix. the size of the bands specified by bandup and banddown. as provided in ‘dllname’. . and otherwise returns the solution according the specified stop condition.e. the diagnostics will be written to the screen at the end of the integration.e. specified by user function jacfunc. The implementation is based on the Fortran 77 version from January 18. See package vignette "compiledCode" from package deSolve for details.

Springer series in computational mathematics 14.1*y[3] . . it will be used to label the columns of the output value.function (t. • ode.. • ode. Springer-Verlag.2*y[2] <. Wanner.matrix(nrow = 5.. Hairer and G.1*y[4] . There will be a row for each element in times unless the FORTRAN routine returns with an unrecoverable error.3*y[1] + . byrow = TRUE. Solving Ordinary Differential Equations II.2*y[3] <.3*y[3] + .1*y[1] .2*y[4] <. written as a full matrix fulljac <.2*y[5] <. parms) { jac <. • daspk for integrating DAE models up to index 1 diagnostics to print diagnostic messages..radau Value 103 A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func. second edition..1D for integrating 1-D models. y. plus and additional column for the time value. 1996. y..function (t. • ode.3*y[2] + . Stiff and Differentialalgebraic problems.3*y[4] + . 5 state variables f1 <...vector(len = 5) ydot[1] ydot[2] ydot[3] ydot[4] ydot[5] <. Author(s) Karline Soetaert References E.2D for integrating 2-D models.. parms) { ydot <.1*y[2] . Examples ## ======================================================================= ## Example 1: ODE ## Various ways to solve the same model. If y has a names attribute.1*y[5] return(list(ydot)) } ## the Jacobian. ncol = 5.. See Also • ode for a general interface to most of the ODE solvers . ## ======================================================================= ## the model.3D for integrating 3-D models.

data = c( .3. dy2.1. . parms) { jac <.2. . .3. . banddown = 1) radau ## ======================================================================= ## Example 2: ODE ## stiff problem from chemical kinetics ## ======================================================================= Chemistry <. 1 . . ..1. internally-generated banded Jacobian ## one nonzero band above (up) and below(down) the diagonal out3 <. parms = . f1. . internally generated.. f1.1. parms = ) plot(out) ## stiff method.1. full Jacobian out <.2.3.. user-generated full Jacobian out2 <. .e4*y[2]*y[3] dy2 <. bandup = 1. . .2. parms = .2..1:2 ## default: stiff method.1. jacfunc = fulljac) ## stiff method..3.e7*y[2]^2 dy3 <. . )) return(jac) } ## initial conditions and output times yini <.104 data = c( . times.2. .. 4*y[1] .1)) yini <..3... . .3. bandup = 1.function (t.1. jactype = "bandusr". .2. . . . .c(y1 = 1.radau(yini.3.radau(yini. y. parms = . . .1:5 times <.2. .e4*y[2]*y[3] . banddown = 1) ## stiff method.. dy3)) } times <. . . . . jactype = "fullusr". . . .1.radau(yini. y3 = ) . times.. ncol = 5. .-. jacfunc = bandjac. f1.3.1. times.2. y2 = . written in banded form bandjac <. . .1. .radau(yini. y.matrix(nrow = 3.1)) return(jac) } ## the Jacobian. ... times.. jactype = "bandint".e7*y[2]^2 list(c(dy1. .1. 4*y[1] + 1. p) { dy1 <.function (t. f1. .3. .1 ^(seq( .. by = . .3. user-generated banded Jacobian out4 <... byrow = TRUE.

dur.radau out <.dm. w <. lwd = 2) ## ## ## ## ## ## ## ## ## ## ============================================================================= Example 3: DAE Car axis problem.1. index 3 DAE.M * eps^2/2.(L -Ll) * yl/Ll + 2 * lam2 * (xl-xr) + lam1*xb + 2 * lam2 * (yl-yr) + lam1*yb . Research Unit of Bari.xb * xl + yb * yl <.8] <.(xl . g <.k * g <.7] <.L * L list(c(dxl.it/~testset. dvr.Mass[1 . ) # the mass matrix Mass <. .1 .c(xl = .9] <. = = = xr = L. type = "l".xr)^2 + (yl . dxr <. Magherini. y.1 yini <. dyl. Mazzia and C.k * g <.y.M * eps * eps/2 Mass[9. { yb xb Ll Lr <<<<r * sin(w * t) sqrt(L * L . lam2 . k <.radau(func = Chemistry.ul.2 * lam2 * (yl-yr) . vr lam1 = . parms = NULL) plot(out. Test Set for Initial Value Problem Solvers. yl = L ul = -L /L..xb)^2 + (yr . 1.. vl ur = -L /L.vl. y = yini.1 ] <Mass .5] <.Mass[7. parms) { with(as.6] <.1.. c2)) }) } eps <.5. dyr <.Mass[8.diag(nrow = 1 . yr = L . L <.ur. 2 algebraic equations from F. dvl. log = "x". 1) Mass[5.(L -Ll) * xl/Ll <.function(t. r <. L <.(L -Lr) * (xr-xb)/Lr . times = times.vr dul dvl dur dvr c1 c2 <. Available at http://www.4.1 .p).(L -Lr) * (yr-yb)/Lr . University of Bari and INdAM. c1. . M <.yb)^2) dxl <. 8 differential. February 2 8. ## caraxisfun implements the right-hand side: caraxisfun <. dyl <. ============================================================================= 105 ## Problem is written as M*y = f(t. dxr.Mass[6. dul.2 * lam2 * (xl-xr) <. Department of Mathematics.list(y). release 2.yb * yb) sqrt(xl^2 + yl^2) sqrt((xr .uniba.yr)^2 . dyr.

parms = NULL.. nlm or nlme Usage rk(y. The first value in times must be the initial time. verbose = FALSE.. 3. times at which explicit estimates for y are desired. hmin = . outnames = NULL. func = caraxisfun. hini = hmax.function(t. ipar = NULL. The system of ODE’s is written as an R function (which may. type = "l". or a character string giving the name of a compiled function in a dynamically loaded shared library...radau(y = yini.106 rk # index of the variables: 4 of index 1.C. parms. The R function rk is a top-level function that provides interfaces to a collection of common explicit one-step solvers of the Runge-Kutta family with fixed or variable time steps. ). either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. . by = . which = 1:4. . fcontrol = NULL. If y has a name attribute.Call. 1) out <. t is the current time point in the integration. nind = index) plot(out. mass = Mass. times. A vector of parameters is passed to the ODEs. func. lwd = 2) rk Explicit One-Step Solvers for Ordinary Differential Equations (ODE) Description Solving initial value problems for non-stiff systems of first-order ordinary differential equations (ODEs). use . or for parameter estimation using any appropriate modeling tool for non-linear models in R such as optim. 4. y. the names will be used to label the output matrix. rtol = 1e-6. atol = 1e-6. times = times. y is the current estimate of the variables in the ODE system.. ynames = TRUE. nls. to call foreign code) or be defined in compiled code that has been dynamically loaded. tcrit = NULL. etc.. 2) times <. of course.Fortran. parms. it must be defined as: func <. forcings = NULL.c(4. . so the solver may be used as part of a modeling package for ODEs. . initfunc = dllname.). hmax = NULL. 2 of index 3 index <. dllname = NULL.. If func is an R-function. nout = .) Arguments y times func the initial (state) values for the ODE system. method = rkMethod("rk45dp7". 4 of index 2. rpar = NULL.. initforc = NULL. If the initial values y has a names .seq( . maxsteps = 5 . initpar = parms. events = NULL.

the fifthorder Cash-Karp method "rk45ck" or the fifth-order Dormand-Prince method with seven stages "rk45dp7". second and fourth-order Runge Kutta ("rk2". the initial step size is determined automatically by solvers with flexible time step. see details. If 0. either a scalar or an array as long as y. see details. If not specified. hmax is set to the maximum of hini and the largest difference in times. If func is a string. For fixed step methods. either a scalar or an array as long as y. vector or list of parameters used in func. an optional minimum value of the integration stepsize. See package vignette "compiledCode" for more details. As a suggestion. whose first element is a vector containing the derivatives of y with respect to time. The return value of func should be a list. if 0.. triggers more verbose output from the ODE solver. this may speed up the simulation especially for large models. and whose next elements are global values that are required at each point in times. then dllname must give the name of the shared library (without extension) which must be loaded before rk is called. Runge-Kutta-Fehlberg "rk34f". The derivatives should be specified in the same order as the state variables y. initial step size to be attempted. relative error tolerance. This parameter is for compatibility with other solvers. Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. rk only accepts the maximal number of steps for the entire integration. one may use "rk23bs" (alias "ode23") for simple problems and "rk45dp7" (alias "ode45") for rough problems. absolute error tolerance.rk 107 attribute. when TRUE. Only applicable to methods with variable time step. the integrator to use. or the variable step methods Bogacki-Shampine "rk23bs". (optional) are any other arguments passed to the function. parms rtol atol tcrit verbose hmin hmax hini ynames method maxsteps . Similarly. average maximal number of steps per output interval taken by the solver. to avoid that the simulation possibly ignores short-term events. Only applicable to methods with variable time step. In special situations this parameter may speed up computations with the cost of precision. This argument is defined such as to ensure compatibility with the Livermore-solvers. . parms is a vector or list of parameters. if FALSE: names of state variables are not passed to function func . if not NULL. setting hini = forces internal time steps identically to external time steps provided by times.. no maximal size is specified. Note that hmin and hmax are ignored by fixed step methods like "rk4" or "euler". internal time steps of non-interpolating solvers cannot be bigger than external time steps specified in times. This can either be a string constant naming one of the pre-defined methods or a call to function rkMethod specifying a user-defined method. and this is calculated as length(times) * maxsteps. The most common methods are the fixed-step methods "euler". then rk cannot integrate past tcrit. "rk4"). a logical value that. the names will be available inside func.

to initialise the common blocks (FORTRAN) or global variables (C. A pre-defined set of common method parameters is in function rkMethod which also allows to supply user-defined Butcher tables. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll .value). A list of control parameters for the forcing functions. only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. The solver will control the vector of estimated local errors in y. if not NULL. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. present in the shared library.108 dllname rk a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. Not also that if events are specified. present in the shared library. Details Function rk is a generalized implementation that can be used to evaluate different solvers of the Runge-Kutta family of explicit ODE solvers.. each present as a two-columned matrix. See forcings or vignette compiledCode. and atol determine the error control performed by the solver. See package vignette "compiledCode". as provided in ‘dllname’.e. max(times)] is done by taking the value at the closest data extreme. See package vignette "compiledCode". See package vignette "compiledCode". with an internal step size less than or equal the difference of two adjacent points of times. the name of the initialisation function (which initialises values of parameters). The values of rtol and atol should all be non-negative. as provided in ‘dllname’. additional arguments passed to func allowing this to be a generic function. See forcings or package vignette "compiledCode". the name of the forcing function initialisation function. i. C++). initfunc initpar rpar ipar nout outnames forcings initforc fcontrol events . See events for more information. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. A list that specifies events. where ewt is a vector of positive error weights. with (time. according to an inequality of the form max-norm of ( e/ewt ) ≤ 1. The input parameters rtol.you have to perform this check in the code. See forcings or package vignette "compiledCode". when the value of a state variable is suddenly changed. interpolation outside the interval [min(times). then polynomial interpolation is switched off and integration takes place from one external time step to the next. if not NULL.. only used if ‘dllname’ is specified: a list with the forcing function data sets. It MUST be present if forcings has been given a value. only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. The form of ewt is: . only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc.

(1996) Numerik Algorithmen: Entscheidungshilfe zur Auswahl und Nutzung. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func.8 implicit Runge-Kutta methods are also supported by this general rk interface.. W. differential algebraic equations (DAEs).petzoldt@tu-dresden. A Systematized Collection of ODE Solvers. C.[ed. Note Arguments rpar and ipar are provided for compatibility with lsoda. H. and Flannery.rk 109 rtol × abs(y) + atol where multiplication of two vectors is element-by-element.. S. solvers of the Livermore family (i. Hindmarsh. If y has a names attribute. Author(s) Thomas Petzoldt <thomas. however their implementation is still experimental.e. W. Engeln-Muellges. or partial differential equations (PDEs). R. The return value of func should be a list. P. Alan C. and whose second element contains output variables that are required at each point in time. the ODEPACK solvers. parms). (1987) The numerical analysis of ordinary differential equations. Some of them are also suitable for stiff ODEs. Amsterdam. Runge-Kutta and general linear methods. plus and additional column for the time value. y. see below) are superior.de> References Butcher. whose first element is a vector containing the derivatives of y with respect to time. Examples are given below. Teukolsky. that must be called as: yprime = func(t. There will be a row for each element in times unless the integration routine returns with an unrecoverable error.55–64 of Stepleman. J. et al. Chichester and New York. Duesseldorf. . Wiley. G. A. (2007) Numerical Recipes in C. in p. and Reutter. Cambridge University Press. F.] (1983) Scientific Computing. Vetterling. North-Holland. VDI Verlag. (1983) ODEPACK. B. Models can be defined in R as a user-supplied R-function. T. Press. t is the current time point in the integration. Starting with version 1.W. See Also For most practical cases. it will be used to label the columns of the output value. Instead of this you may consider radau for a specific full implementation of an implicit Runge-Kutta method. y is the current estimate of the variables in the ODE system.

length = 1 1) ## external signal with rectangle impulse signal <.c(S = 1.import .e*P*C .c*S*P .3D for integrating 3-D models.1. rk 1.c(dS. x. vode. { import <.110 • rkMethod for a list of available Runge-Kutta parameter sets.function(t. c = . • ode.1.input(t) dS <. length(times))) signal$import[signal$times >= 1 & signal$times <= 11] <. • lsoda. dP.approxfun(signal$times. P = 1. lsodar.d*C*P # producer dC <. • ode.2 sigimp <.list(c(parms. • ode. daspk for solvers of the Livermore family. names accessible via "with" function ## . x)). 2 .b*S*P + g*C # substrate dP <. ) ## vector of timesteps times <. Examples ## ======================================================================= ## Example: Resource-producer-consumer Lotka-Volterra model ## ======================================================================= ## Notes: ## . g = . d = . input) { with(as.1.1. C = 1) . e = . • ode.band for solving models with a banded Jacobian.2D for integrating 2-D models. • rk4 and euler for special versions without interpolation (and less overhead).data. lsodes. dC) list(res) }) } ## The parameters parms <. rule = 2) ## Start values for steady state xstart <. • diagnostics to print diagnostic messages.Function sigimp passed as an argument (input) to model ## (see also ode and lsoda examples) SPCmod <. import = rep( .Parameters are a list. f = . parms.c(b = .seq( . signal$import.1D for integrating 1-D models. lsode.f*C # consumer res <. • ode for a general interface to most of the ODE solvers.frame(times = times.

lty = "dotted") legend("center". times. "dotted". forcings = NULL. out2. "P". func. lwd = c(1."P"]. fcontrol = NULL. main = c ("Substrate". lwd = 2) lines(out3[. 1). ipar = NULL. legend = c("euler". . 1)) ## user-specified plot function plot (out1[."P"].. "rk45dp7")."P"]. outnames = NULL. parms. "C"). initfunc = dllname. xlab = "Producer". ynames = TRUE. parms. func. times. outnames = NULL. col = c("black". method = "euler") ## classical Runge-Kutta 4th order out2 <. verbose = FALSE. "red". 3). "Producer". ylab = "Consumer") lines(out2[.1.. lwd = c(1. dllname = NULL. fcontrol = NULL. Description Solving initial value problems for systems of first-order ordinary differential equations (ODEs) using Euler’s method or the classical Runge-Kutta 4th order integration. SPCmod. rpar = NULL. nout = ."C"]. SPCmod. . nout = .par("mfrow") ## deSolve plot method for comparing scenarios plot(out1.) . method = "rk45dp7") mf <. input = sigimp. "Consumer"). input = sigimp.. "rk4". out3. dllname = NULL. times. out1[. ynames = TRUE. verbose = FALSE. rpar = NULL.rk(xstart. 2.) rk4(y. hini = input = sigimp. initforc = NULL. 2. lty = "dotted".. parms. which = c("S". out2[. times. col = "red". hini = 1. "green"). col = "green"."C"]. parms. forcings = NULL. initfunc = dllname. SPCmod. initpar = parms. initforc = NULL. "red". 3. lty = c(1. initpar = parms. parms. "green")) par(mfrow = mf) 111 .rk4 ## Euler method out1 <. rk4 Solve System of ODE (Ordinary Differential Equation)s by Euler’s Method or Classical Runge-Kutta 4th Order Integration.rk(xstart. col =c("black". hmax = 1. lty = c("solid"."C"]. "dotted"). times. out3[. ipar = NULL. type = "l".rk(xstart. method = "rk4") ## Dormand-Prince method of order 5(4) out3 <. Usage euler(y.

y. outnames = NULL. . initforc = NULL. when TRUE. to initialise the common blocks (FORTRAN) or global variables (C. times. only when ‘dllname’ is specified and an initialisation function initfunc is in the DLL: the parameters passed to the initialiser.. a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func.. See package vignette "compiledCode" for more details. initfunc = dllname. times at which explicit estimates for y are desired. If func is a string.112 euler. If NULL. and whose next elements are global values that are required at each point in times. triggers more verbose output from the ODE solver. dimens = NULL. (optional) are any other arguments passed to the function. then dllname must give the name of the shared library (without extension) which must be loaded before rk4 is called. this may speed up the simulation especially for large models. initpar = parms. whose first element is a vector containing the derivatives of y with respect to time.. forcings = NULL. If func is an R-function. nout = . the name of the initialisation function (which initialises values of parameters).function(t. The derivatives should be specified in the same order as the state variables y. for 1D models only: the names of the components. y is the current estimate of the variables in the ODE system.. ipar = NULL. verbose = FALSE. C++). If NULL. it must be defined as: func <. used for plotting. fcontrol = NULL. or a character string giving the name of a compiled function in a dynamically loaded shared library..). ynames = TRUE. names = NULL. The return value of func should be a list. parms. func. for 1D models only: the number of species (components) in the model. See package vignette "compiledCode". If the initial values y has a names attribute. See package vignette "compiledCode". If y has a name attribute.. for 1D models only: the number of boxes in the model. .. dllname = NULL. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. a logical value that. parms. then nspec should be specified. The first value in times must be the initial time. as provided in ‘dllname’. then dimens should be specified. t is the current time point in the integration. the names will be available inside func. nspec = NULL.1D(y. rpar = NULL. vector or list of parameters used in func. if FALSE: names of state variables are not passed to function func . if not NULL.) Arguments y times func rk4 the initial (state) values for the ODE system. parms nspec dimens names verbose ynames dllname initfunc initpar . parms is a vector or list of parameters. the names will be used to label the output matrix.

additional arguments passed to func allowing this to be a generic function. It MUST be present if forcings has been given a value. the name of the forcing function initialisation function. If you need different internal and external time steps or want to use events. See package vignette "compiledCode". value). present in the shared library.g. parms. times. it will be used to label the columns of the output value.. See forcings or vignette compiledCode. lsoda) are superior. A list of control parameters for the forcing functions. If y has a names attribute.you have to perform this check in the code. times. solvers with flexible timestep (e. Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. with (time. outnames forcings initforc fcontrol . as provided in ‘dllname’. Note For most practical cases. rk(method = "ode45") and especially solvers of the Livermore family (ODEPACK. rk. interpolation outside the interval [min(times). method = "euler"). See forcings or package vignette "compiledCode". only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. see ode. method = "rk4") or rk(y. only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. func. See help pages of rk and rkMethod for details. parms.g. please use: rk(y.1D essentially calls functioneuler but contains additional code to support plotting of 1D models. plus and additional column for the time value. no interpolation and no events) compared to the generic Runge-Kutta codes called by ode resp.g. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the DLL . See forcings or package vignette "compiledCode". Details rk4 and euler are special versions of the two fixed step solvers with less overhead and less functionality (e. There will be a row for each element in times unless the integration routine returns with an unrecoverable error. only used if ‘dllname’ is specified: a list with the forcing function data sets. max(times)] is done by taking the value at the closest data extreme. present in the shared library. . func.1D for details. e. each present as a two-columned matrix.rk4 rpar ipar nout 113 only when ‘dllname’ is specified: a vector with double precision values passed to the DLL-functions whose names are specified by func and jacfunc..1D and plot. Function euler. if not NULL.

systematic under-estimation time <. K = K) x <. col = "blue". daspk for solvers of the Livermore family. 12 ).frame(euler(x.de> See Also • rkMethod for a list of available Runge-Kutta parameter sets.c(N = N ) ## analytical solution plot(time.:1 N <.r * x[1] * (1 . • dede for integrating models with delay differential equations.petzoldt@tu-dresden. vode. parms)) points(out$time. r <.function(t. Examples ## ======================================================================= ## Example: Analytical and numerical solutions of logistic growth ## ======================================================================= ## the derivative of the logistic logist <. 2) out <. ylim = c( . • ode.1. parms) { with(as.seq( . lwd = 2) ## reasonable numerical solution with rk4 time <.5) ## same time step with euler. pch = 16.band for solving models with a banded Jacobian. pch = 1) . • ode.data. out$N. logist. K/(1 + (K/N -1) * exp(-r*time)). diagnostics to print diagnostic messages. lsodar.2D for integrating 2-D models. • ode.3D for integrating 3-D models. lsodes. cex = rk4 .as. logist.1 parms <. x. • rk for the more general Runge-Code.c(r = r.frame(rk4(x.list(parms).x[1]/K) list(dx) }) } time <.seq( .114 Author(s) Thomas Petzoldt <thomas.as. out$N. • ode for a general interface to most of the ODE solvers.1D for integrating 1-D models. K <.. 1 . time. • ode. 1 . time.5. parms)) points(out$time.data. lsode. 2) out <. { dx <. type = "l".. • lsoda. col = "red".

The following comparison gives an idea how the algorithms of deSolve are related to similar algorithms of other simulation languages: rkMethod "euler" "rk2" | | | Description Euler’s Method 2nd order Runge-Kutta. logist. Details This function supplies method settings for rk or ode. "euler. If called without arguments. 1. . "rk4" or the variable step methods "rk23bs" (alias "ode23"). "blue". Usage rkMethod(method = NULL. h=2". "rk45dp7" (alias "ode45") or "rk78f". col = "green") legend("bottomright". col = c("red".. "green")) rkMethod Collection of Parameter Sets (Butcher Arrays) for the Runge-Kutta Family of ODE Solvers Description This function returns a list specifying coefficients and properties of ODE solver methods from the Runge-Kutta family. h=2".. lty = c(1. lwd = c(2. 1. c("analytical". cex = .rkMethod 115 ## unstable result time <.seq( . "black". parms)) points(out$time. NA.data. time. . 8.as. "euler. NA. specification of a user-defined solver..5) ## method with automatic time step out <. 1. h=4". out$N. the names of all currently implemented solvers of the Runge-Kutta family are returned. see Value and example below.. logist. out$N. 16.data. 1.) Arguments method a string constant naming one of the pre-defined methods of the Runge-Kutta family of solvers. 1). "rk2". pch = 1.frame(lsoda(x. "black". 1 ."rk4. "lsoda").frame(euler(x. time. The most common methods are the fixed-step methods "euler". NA). fixed time step (Heun’s method) .as. 4) out <. pch = 8. parms)) points(out$time. pch = c(NA. 1). NA.

Matlab: ode23 Runge-Kutta-Fehlberg. coefficients of the higher order Runge-Kutta pair (optional. Octave: ode45. Note however. optional coefficients for built-in polynomial interpolation of the outputs from internal steps (dense output). local order 6 Dormand-Prince 4(5). (first same as last) optional boolean value specifying if the method allows re-use of the last function evaluation (TRUE) or not (FALSE or NULL). order 7(8) Dormand-Prince. The table reflects the state at time of writing and it is of course possible that implementations change. Octave: ode23 Bogacki-Shampine. coefficients for calculating the intermediate time steps. it is disabled by default (see nknots below). This is available for all RK methods and may be useful to speed up computation if no dense-output formula is available. order 4(5) Dormand-Prince. this matrix must be lower triangular. coefficients of the lower order Runge-Kutta pair. order 3(4) Runge-Kutta Cash-Karp. MATLAB: ode45. order 7(8) Note that this table is based on the Runge-Kutta coefficients only. order 4(5). b1 b2 c d . "ode23" "rk34f" "rk45ck" "rk45f" "rk45e" "rk45dp6" "rk45dp7". for embedded methods that allow variable time step). order 2(3). "ode45" "rk78f" "rk78dp" | | | | | | | | | | | | rkMethod classical 4th order Runge-Kutta. order 4(5). order 4(5) Runge-Kutta-Fehlberg. local order 7 (also known as dopri5. that this can introduce considerable local error. fixed time step Runge-Kutta. A must be a vector for fixed step methods where only the subdiagonal values are different from zero. in their stepsize adaption strategy and interpolation methods. As link{rk} supports only explicit methods. but the algorithms differ also in their implementation.116 "rk4" "rk23" "rk23bs". currently only available for method rk45dp7 (DormandPrince). pair=1 Runge-Kutta-England. Neville-Aitken polynomials can be used to interpolate between time steps. As an alternative. coefficient matrix of the method. Value A list with the following elements: ID varstep FSAL A name of the method (character) boolean value specifying if the method allows for variable time step (TRUE) or not (FALSE). pair=0) Runge-Kutta-Fehlberg. order 2(3). Methods "rk45dp7" (alias "ode45") and "rk45ck" contain specific and efficient built-in interpolation schemes (dense output). Octave: ode45.

4/Qerr. If nknots < 2 (the default) then internal interpolation is switched off and integration is performed step by step between external time steps. that supports also FSAL. • Classical "rk4" is traditionally used in cases where an adequate stepsize is known a-priori or if external forcing data are provided for fixed time steps only and frequent interpolation of external data needs to be avoided. If alpha is omitted. They will take small steps over bumpy ground and long steps over uninteresting terrain. re-use of the last intermediate steps (FSAL = first same as last) and built-in polynomial interpolation (dense output). one may use "rk23" (alias "ode23") for simple problems and "rk45dp7" (alias "ode45") for rough problems.petzoldt@tu-dresden. optional tuning parameter for stepsize adjustment. which need at least nknots + 1 internal time steps. Neville-Aitken polynomials are used. and parts where nothing much happens. it is set to 1/Qerr − 0.75beta. If nknots is between 3 and 8.de> .. Instead of this you may consider radau for a specific full implementation of an implicit Runge-Kutta method. because of its relatively high order (4). • As a suggestion. Author(s) Thomas Petzoldt <thomas.rkMethod densetype 117 optional integer value specifying the dense output formula. • Another good choice. optional tuning parameter for stepsize adjustment. currently only densetype = 1 for rk45dp7 (Dormand-Prince) and densetype = 2 for rk45ck (Cash-Karp) are supported. number of function evaluations needed (corresponds to number of rows in A). integer value specifying the order of interpolation polynomials for methods without dense output. however their implementation is still experimental. "rk45ck". may be useful for slightly stiff systems if demands on precision are relatively low. Typical values are 0 (default) or 0. • Solver "rk23bs". important for automatic time-step adjustment. especially if external and internal time steps are very different. • Method "rk45dp7" (alias "ode45") contains an efficient built-in interpolation scheme (dense output) based on intermediate function evaluations. assuring medium accuracy.8 implicit Runge-Kutta (irk) methods are also supported by the general rk interface. Interpolation may speed up integration but can lead to local errors higher than the tolerance. stage Qerr nknots alpha beta Note • Adaptive stepsize Runge-Kuttas are preferred if the solution contains parts where it changes fast. The default value is 1/Qerr (for beta = 0). The default solver is "rk45dp7" (alias "ode45"). densetype = NULL) disable dense output. global error order of the method. Undefined values (e. is the Cash-Karp Runge-Kutta method. Starting with version 1.g.

Phys. 1990. 46. F. (1989) A 3(2) pair of Runge-Kutta formulas. R. Kutta. length = 1 1) parms <. R. (1981) High order embedded Runge-Kutta formulae. Math. 6(1). Math. Fehlberg. W. Runge. 67–75. b = . R.c(dP.c(a = .{ dP <. Engeln-Muellges. P. J.Extra Packages for GNU Octave. C. Octave-Forge . J. C. http://www. and Shampine L. Appl. E. J. P.b * C * P dC <. Wiley.seq( . C = 1) ## rk using ode45 as the default method out <. (1967) Klassische Runge-Kutta-Formeln fuenfter and siebenter Ordnung mit SchrittweitenKontrolle. 201–222. 435–453. MATLAB (R) is a registed property of The Mathworks Inc. and Prince. P. 19–26.sourceforge. Math. Z. 1–9. Comput.c * C res <. A variable order Runge-Kutta method for initial value problems with rapidly varying right-hand sides. (1895) Ueber die numerische Aufloesung von Differentialgleichungen. 167–178.c(P = 2. J. ACM Transactions on Mathematical Software 16. c = . Cash. Lett. 2 . 2. parms) . Duesseldorf.1.a * P . http://octave. dC) list(res) }) } times <. J. x. Ann. H.1.F. 93–106. J.rk(x. Computing (Arch. Package OdePkg. ode Examples rkMethod() # returns the names of all available methods rkMethod("rk45dp7") # parameters of the Dormand-Prince 5(4) method rkMethod("ode45") # an alias for the same method func <. parms) { with(as.mathworks. Chichester and New York. (1901) Beitrag zur naeherungsweisen Integration totaler Differentialgleichungen. Comput. G..com/ See Also rk. (1996) Numerik Algorithmen: Entscheidungshilfe zur Auswahl und Nutzung.118 References rkMethod Bogacki. Runge-Kutta and general linear methods. and Dormand. net/odepkg Prince. J. times.list(c(parms. Math.function(t. and Karp A. Rechnen) 4. and Reutter. x)). J. (1987) The numerical analysis of ordinary differential equations. Butcher. Appl. 46. (1980) A family of embedded Runge-Kutta formulae. 7(1). Dormand. VDI Verlag.1) x <. func. Math. Elektron. Appl.b * P * C .

1]. Qerr = 1 . method = "lsoda".". method = rkMethod("rk4")) ## ’ode’ has aliases for the most common RK methods out <. 1).".par("mfrow" = c(4. times. times. c = c( . nknots = . method = rkMethod("rk45dp7". hmax = 1 ) ## stop and go: disable interpolation completely ## and integrate explicitly between external time steps o3 <. 1)) matplot(o1[. times. type = "l". type = "l". ylab = "Diff.o3[. nknots = 5). func. stage = 2. 1/2). xlab = "Time".ode(x.-1]. col = "grey") matplot(o [. xlab = "Time". b1 = c( . xlab = "Time". parms. func. parms. times. times. o1[. hmax = 1 ) ## disable dense-output interpolation ## and use only Neville-Aitken polynomials instead o2 <.ode(x.-1].-1] . func. atol = 1e-1 . type = "l".ode(x.1]. A = c( . col = "grey") par(mf) ##=========================================================================== ## rkMethod allows to define user-specified Runge-Kutta methods ##=========================================================================== out <. densetype = NULL.-1] .ode(x. type = "l". times.1]. parms. method = "ode45") ##=========================================================================== ## Comparison of local error from different interpolation methods ##=========================================================================== ## lsoda with lower tolerances (1e-1 ) used as reference o <. hmax=1 )) ## compare different interpolation methods with lsoda mf <.ode(x. 1/2). ylab = "Diff. parms. parms. main="Difference between lsoda and ode45 in ’stop and go’ mode") abline(h = .ode(x. o [. method = rkMethod("rk45dp7". parms. method = rkMethod(ID = "midpoint". densetype = NULL. ylab = "P. parms.". C") matplot(o [. main="Difference between lsoda and ode45 with Neville-Aitken") abline(h = . func. varstep = FALSE. func.o1[.ode(x. xlab = "Time". ylab = "Diff. col = "grey") matplot(o [. times. method = rkMethod("rk45dp7"). main="Difference between lsoda and ode45 with dense output") abline(h = . o [. func. main = "State Variables".o2[.1].rkMethod 119 ## all methods can be called also from ’ode’ by using rkMethod out <.-1].-1]. func. rtol = 1e-1 ) ## rk45dp7 with hmax = 1 > delta_t = 2 o1 <. o [.-1] .

120
) ) plot(out) ## compare method diagnostics times <- seq( , 2 , length = 1 ) o1 <- ode(x, times, func, parms, method = rkMethod("rk45ck")) o2 <- ode(x, times, func, parms, method = rkMethod("rk78dp")) diagnostics(o1) diagnostics(o2)

SCOC

SCOC

A Sediment Model of Oxygen Consumption

Description A model that describes oxygen consumption in a marine sediment. One state variable: • sedimentary organic carbon, Organic carbon settles on the sediment surface (forcing function Flux) and decays at a constant rate. The equation is simple: dC = F lux − kC dt This model is written in FORTRAN. Usage SCOC(times, y = NULL, parms, Flux, ...) Arguments times y parms Flux ... Details The model is implemented primarily to demonstrate the linking of FORTRAN with R-code. The source can be found in the ‘doc/examples/dynload’ subdirectory of the package. time sequence for which output is wanted; the first value of times must be the initial time, the initial value of the state variable; if NULL it will be estimated based on Flux and parms, the model parameter, k, a data set with the organic carbon deposition rates, any other parameters passed to the integrator ode (which solves the model).

timelags Author(s) Karline Soetaert <k.soetaert@nioo.knaw.nl> References

121

Soetaert, K. and P.M.J. Herman, 2009. A Practical Guide to Ecological Modelling. Using R as a Simulation Platform. Springer, 372 pp. See Also ccl4model, the CCl4 inhalation model. aquaphy, the algal growth model. Examples
## Forcing function data Flux <- matrix(ncol = 2, byrow = TRUE, data = c( 1, .654, 11, .167, 21, . 6 , 41, . 7 , 73, .277, 83, .186, 93, .14 ,1 3, .255, 113, .231,123, .3 9,133,1.127,143,1.923, 153,1. 91,163,1. 1, 173, 1.691,183, 1.4 4,194,1.226,2 4, .767, 214, .893,224, .737, 234, .772,244, .726,254, .624,264, .439, 274, .168,284 , .28 , 294, .2 2,3 4, .193,315, .286,325, .599, 335, 1.889,345, .996,355, .681,365,1.135)) parms <- c(k = . 1)

times <- 1:365 out <- SCOC(times, parms = parms, Flux = Flux) plot(out[,"time"], out[,"Depo"], type = "l", col = "red") lines(out[,"time"], out[,"Mineralisation"], col = "blue") ## Constant interpolation of forcing function - left side of interval fcontrol <- list(method = "constant") out2 <- SCOC(times, parms = parms, Flux = Flux, fcontrol = fcontrol) plot(out2[,"time"], out2[,"Depo"], type = "l",col = "red") lines(out2[,"time"], out2[,"Mineralisation"], col = "blue")

timelags

Time Lagged Values of State Variables and Derivatives.

122 Description

timelags

Functions lagvalue and lagderiv provide access to past (lagged) values of state variables and derivatives. They are to be used with function dede, to solve delay differential equations. Function timestep gives the current and next timestep of the integration. Usage lagvalue(t, nr) lagderiv(t, nr) timestep(prev = TRUE)

Arguments t nr prev the time for which the lagged value is wanted; this should be no larger than the current simulation time and no smaller than the initial simulation time. the number of the lagged value; if NULL then all state variables or derivatives are returned. if TRUE will return the timestep previously used; when FALSE will return the time step to be currently tried by the integrator.

Details The lagvalue and lagderiv can only be called during the integration, the lagged time should not be smaller than the initial simulation time, nor should it be larger than the current simulation time. Cubic Hermite interpolation is used to obtain an accurate interpolant at the requested lagged time. Function timestep returns the current simulation timestep; if the simulation has not yet started, will return 1. Use with care. Value a scalar (or vector) with the lagged value(s). Author(s) Karline Soetaert <k.soetaert@nioo.knaw.nl> See Also dede, for how to implement delay differential equations.

lagvalue(t .lag1 * lag2 dy2 <.History(t . select first element if (t < 2) lag2 <. parms = NULL.c(y1 = . 1) ##----------------------------## solve the model ##----------------------------yout <. lag1 = lag1.History(t .2) # faster than lagvalue(t .function(t) c(cos(t).timelags Examples ## ## ## ## ## ## ============================================================================= exercise 6 from Shampine and Thompson. 2 . func = derivs.2. sin(t)) if (t < 1) lag1 <. y2 = ) times <. parms) { History <.1)[1] else lag1 <.dede(y = yinit. times = times.seq( . dy2). lag2 = lag2) } ##----------------------------## parameters ##----------------------------r <.2)[2] else lag2 <. 2 solving delay differential equations with dde23 two lag values ============================================================================= 123 ##----------------------------## the derivative function ##----------------------------derivs <.lagvalue(t . y.19 ##----------------------------## initial values and times ##----------------------------yinit <. m <.function(t.-y[1] * lag2 list(c(dy1. atol = 1e-9) ##----------------------------## plot results ##----------------------------- .5.2)[2] dy1 <. by = .3.1)[1] # returns a vector.

xlab = "y1".y[1]/m) + b * y[1] * y[2] dy2 <.-1 . m <.lagvalue(tlag) # returns a vector dy1 <. 2 solving delay differential equations with dde23 a vector with lag valuess ============================================================================= ##----------------------------## the derivative function ##----------------------------predprey <. lwd = 2) diagnostics(yout) ..function(t. plot results ##----------------------------plot(yout. 1. type = "l".t . parms) { tlag <. parms = NULL) ##----------------------------## display. b <. 1) #----------------------------# solve the model #----------------------------yout <.c(y1 = 8 . mfrow = c(2. func = predprey.124 timelags plot(yout. 2)) plot(yout[. yout[. type = "l". by = .25.1 if (tlag < ) ylag <. ylab = "y2". lwd = 2) ## ## ## ## ## ## ## ============================================================================= The predator-prey model with time lags. 3 ) else ylag <.2]. main = "Predator-prey model". y. type = "l". times = times. 1. dy2)) } ##----------------------------## parameters ##----------------------------a <. from Hale problem 1 from Shampine and Thompson. lwd = 2.2 ##----------------------------## initial values and times ##----------------------------yinit <.dede(y = yinit.seq( . d <.c(8 . c <.a * y[1] * (1 .c * y[2] + d * ylag[1] * ylag[2] list(c(dy1. y2 = 3 ) times <.3].. 1 .

dede(y = yinit.1 if (tlag < ) dylag <. parms = NULL) ##----------------------------## display.lagderiv(tlag) list(c(dy = -dylag). lwd = 2) vode Solver for Ordinary Differential Equations (ODE) Description Solves the initial value problem for stiff or nonstiff systems of ordinary differential equations (ODE) in the form: dy/dt = f (t. y(t) t < = 1/t ## ## ============================================================================= ##----------------------------## the derivative function ##----------------------------derivs <. y.t . type = "l". 4. dylag = dylag) } ##----------------------------## initial values and times ##----------------------------yinit <times <. func = derivs. plot results ##----------------------------plot(yout.-1 else dylag <. .vode 125 ## ============================================================================= ## ## A neutral delay differential equation (lagged derivative) ## y’t = -y’(t-1).function(t. times = times.seq( . y) . 1) ##----------------------------## solve the model ##----------------------------yout <. parms) { tlag <.

and whose next elements are global values that are required at each point in times. parms is a vector or list of parameters. lags = NULL. or a character string giving the name of a compiled function in a dynamically loaded shared library. In addition. vector or list of parameters used in func or jacfunc. the user has to specify whether or not the problem is stiff and choose the appropriate solution method. If func is a string. bandup = NULL. ynames = TRUE. Hindmarsh and George D. The derivatives should be specified in the same order as the state variables y. rpar = NULL. t is the current time point in the integration. See package vignette "compiledCode" for more details.. initfunc = dllname. dllname = NULL. then dllname must give the name of the shared library (without extension) which must be loaded before vode() is called. y. events=NULL. the names will be used to label the output matrix. relative error tolerance. The return value of func should be a list. vode is very similar to lsode.. Byrne.. parms. .. The system of ODE’s is written as an R function or be defined in compiled code that has been dynamically loaded. nout = . jactype = "fullint".). written by Peter N. if only one step is to be taken.. parms rtol atol . in vode it is possible to choose whether or not a copy of the Jacobian is saved for reuse in the corrector iteration algorithm. it must be defined as: func <. If func is an R-function.126 vode The R function vode provides an interface to the FORTRAN ODE solver of the same name. maxord = NULL. See details.) Arguments y times func the initial (state) values for the ODE system.function(t. rtol = 1e-6. times. fcontrol=NULL. verbose = FALSE. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t. the names will be available inside func.. Brown. maxsteps = 5 . banddown = NULL. tcrit = NULL.. mf = NULL. either a scalar or an array as long as y. forcings=NULL. Alan C. absolute error tolerance. outnames = NULL. In lsode. whose first element is a vector containing the derivatives of y with respect to time. either a scalar or an array as long as y. hini = . hmin = . jacfunc = NULL. y is the current estimate of the variables in the ODE system. time sequence for which output is wanted. parms. ipar = NULL.. If y has a name attribute. func. set times = NULL. See details. In contrast to lsoda. a copy is not kept. Usage vode(y. atol = 1e-8. initpar = parms. but uses a variable-coefficient method rather than the fixed-stepinterpolate methods in lsode. (optional) are any other arguments passed to the function. initforc = NULL. hmax = NULL. the first value of times must be the initial time. If the initial values y has a names attribute.

In special situations this parameter may speed up computations with the cost of precision. if the system is stiff. logical. or a string giving the name of a function or subroutine in ˙ ‘dllname’ that computes the Jacobian (see vignette "compiledCode" for more about this option).e. will print the diagnostiscs of the integration . if FALSE: names of state variables are not passed to function func .see details. number of non-zero bands below the diagonal. NULL uses the default. if 0. Reduce maxord to save storage space. to avoid that the simulation possibly ignores short-term events. in case the Jacobian is banded. the structure of the Jacobian. overruled if mf is not NULL. rotated row-wise.overrules jactype . this may speed up the simulation especially for multi-D models. "bandusr" or "bandint" . The R calling sequence for jacfunc is identical to that of func. In some circumstances. Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. the maximum order to be allowed. initial step size to be attempted. If there is a time beyond which integration should not proceed (perhaps because of a singularity).either full or banded and estimated internally or by user. and interpolates values for the desired time points. an optional minimum value of the integration stepsize. where the ˙ ith row contains the derivative of dyi /dt with respect to yj . if not NULL. if TRUE: full output to the screen. e. number of non-zero bands above the diagonal. The FORTRAN routine dvode overshoots its targets (times points in the vector times). an R function that computes the Jacobian of the system of differential equations ∂ yi /∂yj . no maximal size is specified. a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. "fullusr". then vode cannot integrate past tcrit. the initial step size is determined by the solver. that should be provided in tcrit. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. order 12 if implicit Adams method (meth = 1). If 0.see details. hmax is set to the largest difference in times. one of "fullint". order 5 if BDF method (meth = 2).g. the "method flag" passed to function vode . If not specified. If the Jacobian is a full matrix. See first example of lsode. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices).vode jacfunc 127 if not NULL. i. maximal number of steps per output interval taken by the solver. See package vignette "compiledCode". jactype mf verbose tcrit hmin hmax hini ynames maxord bandup banddown maxsteps dllname . in case the Jacobian is banded. supplying jacfunc can speed up the computations. jacfunc should return a matrix ∂ y/∂y.provides more options than jactype . If the Jacobian is banded.

. rpar ipar nout outnames forcings initforc fcontrol events lags .128 initfunc initpar vode if not NULL. If the problem is nonstiff. each present as a two-columned matrix. if not NULL. To be used for delay differential equations. corresponds to mf = 21. See package vignette "compiledCode". the name of the initialisation function (which initialises values of parameters).e. only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. the name of the forcing function initialisation function.e. no Jacobian used. the user has to decide whether or not the problem is stiff. i. present in the shared library. which selects a nonstiff (Adams) method. the number of steps that has to be kept. forcings or package vignette "compiledCode" A list that specifies events. to initialise the common blocks (FORTRAN) or global variables (C. If the problem is stiff. specified by user function jacfunc. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. A list that specifies timelags. with (time. use method flag mf = 10. jac = "fullusr": a full Jacobian. dede for more information. present in the shared library. See forcings or package vignette "compiledCode". It MUST be present if forcings has been given a value.See package vignette "compiledCode".you have to perform this check in the code . there are four standard choices which can be specified with jactype or mf. The options for jactype are jac = "fullint": a full Jacobian. max(times)] is done by taking the value at the closest data extreme.. as provided in ‘dllname’. corresponds to mf = 22. C++). interpolation outside the interval [min(times). These names will be used to label the output matrix. i. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the dll . Details Before using the integrator vode. only used if ‘dllname’ is specified: a list with the forcing function data sets.value). only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. See forcings or package vignette "compiledCode". only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. only when ‘dllname’ is specified: a vector with double precision values passed to the dll-functions whose names are specified by func and jacfunc. A list of control parameters for the forcing functions. See timelags. calculated internally by vode. additional arguments passed to func and jacfunc allowing this to be a generic function. as provided in ‘dllname’. when the value of a state variable is suddenly changed. See events for more information. .

-21. The legal values of mf are 10. JSV = -1 means a copy of the Jacobian is not saved. 22. corresponds to mf = 25. METH = 2 means the method based on backward differentiation formulas (BDF-s). and atol determine the error control performed by the solver. where JSV = SIGN(mf) indicates the Jacobian-saving strategy: JSV = 1 means a copy of the Jacobian is saved for reuse in the corrector iteration algorithm. MITER = 5 means chord iteration with an internally generated banded Jacobian (using ML+MU+1 extra calls to func per df/dy evaluation). Models may be defined in compiled C or FORTRAN code. . The diagnostics of the integration can be printed to screen by calling diagnostics. -11. the diagnostics will written to the screen at the end of the integration. If verbose = TRUE. 14. calculated by vode. 13. The input parameters rtol. 24. MITER indicates the corrector iteration method: MITER = 0 means functional iteration (no Jacobian matrix is involved). the user must supply a subroutine jacfunc. the size of the bands specified by bandup and banddown. More information about models defined in compiled code is in the package vignette ("compiledCode"). specified by user function jacfunc. METH indicates the basic linear multistep method: METH = 1 means the implicit Adams method. If the request for precision exceeds the capabilities of the machine. The example for integrator lsode demonstrates how to specify both a banded and full Jacobian. -14. mf = JSV*(1 *METH + MITER). mf is a signed two-digit integer. -15. 11. as well as in an R-function. See vignette("deSolve") for an explanation of each element in the vectors containing the diagnostic properties and how to directly access them. 25. -25. More options are available when specifying mf directly.vode 129 jac = "bandusr": a banded Jacobian. MITER = 4 means chord iteration with a user-supplied banded Jacobian. If MITER = 1 or 4. jac = "bandint": a banded Jacobian. See package vignette "compiledCode" for details. 20. 12. vode will return an error code. 21. See lsoda for details. MITER = 3 means chord iteration with an internally generated diagonal Jacobian approximation (using 1 extra call to func per df/dy evaluation). the size of the bands specified by bandup and banddown. Examples in both C and FORTRAN are in the ‘dynload’ subdirectory of the deSolve package directory. MITER = 1 means chord iteration with a user-supplied full (NEQ by NEQ) Jacobian. MITER = 2 means chord iteration with an internally generated (difference quotient) full Jacobian (using NEQ extra calls to func per df/dy value). -22. -12. information about linking forcing functions to compiled code is in forcings. 23. corresponds to mf = 24. 15. -24.

1976. 1975. Amsterdam. 1977. SIAM J. An Alternative Implementation of Variable Step-Size Multistep Formulas for Stiff ODEs. plus and additional column for the time value. ODEPACK. Hindmarsh. Stepleman et al. Byrne and A. A. Sacks-Davis. C. • ode.1D for integrating 1-D models. 1980. Netlib: http://www. There will be a row for each element in times unless the FORTRAN routine ‘vode’ returns with an unrecoverable error. Byrne. If y has a names attribute.3D for integrating 3-D models. 1. VODE: A Variable Coefficient ODE Solver.. Jackson and R.band for solving models with a banded Jacobian. Brown. A Polyalgorithm for the Numerical Solution of Ordinary Differential Equations. A. lsodar. R. • ode. 10. C. Hindmarsh.nl> References P. 55-64. a Systematized Collection of ODE Solvers. D. pp.netlib. April 1976. • rk4 and euler for Runge-Kutta integrators. pp. 1983. EPISODE: An Effective Package for the Integration of Systems of Ordinary Differential Equations. C. C.130 Value vode A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func. Byrne. S. pp. . 1. Software. G. • ode. Math. Also. LLNL Report UCID-30112. Software.knaw. G. pp. D. N. • ode for a general interface to most of the ODE solvers. and A. June 1988. K. Hindmarsh. it will be used to label the columns of the output value. in Scientific Computing. eds.. 1989. Stat. C.soetaert@nioo. 71-96. ACM Trans. Hindmarsh. 295-318. 6. daspk for other solvers of the Livermore family. Rev.2D for integrating 2-D models. Sci. Author(s) Karline Soetaert <k. D. G. Comput. R. lsode. diagnostics to print diagnostic messages. Math. D. • ode. LLNL Report UCID-30132. LLNL Report UCRL-98412.org See Also • rk. lsodes. • lsoda. North-Holland. Hindmarsh and G. ACM Trans.. EPISODEB: An Experimental Package for the Integration of Systems of Ordinary Differential Equations with Banded Jacobians. 1038-1051. Byrne and A.

7 . . .-1 * (y .923. 153. ) plot(out. 91.654. 2 9. . . . state. xlab = "x". Atmos.315.691. 335. ======================================================================= 131 chaos <. .4 4. 2 SCOC model. z = 1) times <.-8/3 * x + y * z <. 2 . Flux[.1:365 . 83.183. 11.f". by = 1))$y) Yini <. 355.2]. 93.284.599.3 9. (simplified) ======================================================================= ## Forcing function data Flux <. .365. .127. 1) meanDepo <.737.1]. 234. byrow = TRUE.255. 1 .264. 1. chaos. 1.893.c(k = . type = "l") # all versus time plot(out[. . ylab = "y") ## ## ## ## ## ## ## ======================================================================= ex.286. 1.to see the FORTRAN code: browseURL(paste(system.matrix(ncol = 2.772.c(y = as.277. 1. 1.133.z list(c(dx. . 73.624. 113.244."x"]. . . .996.168. 1.vode(state.163.224.439. chapter 3. Sci. J. main = "Lorenz butterfly".z) <. . type = "l". 214.vode Examples ## ## ## ## ## ======================================================================= ex.1 3. . parameters) { with(as. 173. out[. 6 . dz)) }) } state <. 294.889. .254. .-x * y + 28 * y .726. 13 -141. .143. data = c( 1.226.2 2. 1) out <.seq( .681.193. .345. dy. 1. in FORTRAN .mean(approx(Flux[.135)) parms <.2 4. . .double(meanDepo/parms)) times <.14 . . 1. 21. .767. xout = seq(1. { dx dy dz <.194. .3 4.186.167.1. y = 1.c(x = 1.file(package="deSolve"). 274. .325. . "/doc/examples/dynload/scoc.123.1."y"].231.sep="")) example from Soetaert and Herman. 1 The famous Lorenz equations: chaos in the earth’s atmosphere Lorenz 1963. 365.function(t.28 . times.list(c(state)). 41.

initfunc = "scocpar". dllname = "deSolve". "blue"). ylab = "Depo") plot(out. nout = 2.132 out <. dllname = "deSolve". out2. dllname = "deSolve". The R function zvode provides an interface to the FORTRAN ODE solver of the same name. col = c("red". out3) zvode zvode Solver for Ordinary Differential Equations (ODE) for COMPLEX variables Description Solves the initial value problem for stiff or nonstiff systems of ordinary differential equations (ODE) in the form: dy/dt = f (t.vode(Yini. xlab = "time". Alan C. parms = parms. ylab = "Depo") ## Constant interpolation of forcing function .c("Depo". "blue"). times. type = "l". "Mineralisation")]. func = "scocder".1]. "Depo")) matplot(out3[.1]. xlab = "time". nout = 2. fcontrol = fcontrol.middle of interval fcontrol <. forcings = Flux. fcontrol = fcontrol. type = "l".vode(Yini.c("Depo". col = c("red". ylab = "Depo") ## Constant interpolation of forcing function . "Depo")) matplot(out[. out[.c("Depo". func = "scocder". forcings = Flux. times. out3[. forcings = Flux.vode(Yini. "Depo")) matplot(out2[. nout = 2.list(method = "constant". "Mineralisation")]. func = "scocder".list(method = "constant") out2 <. outnames = c("Mineralisation". Byrne.left side of interval fcontrol <. col = c("red". initforc = "scocforc". "Mineralisation")]. written by Peter N. times. "blue"). initfunc = "scocpar". f = . y) where dy and y are complex variables. initforc = "scocforc". initforc = "scocforc". outnames = c("Mineralisation". initfunc = "scocpar". xlab = "time". Hindmarsh and George D. parms = parms. outnames = c("Mineralisation". out2[. parms = parms. Brown. .5) out3 <. type = "l".1].

hini = . If y has a name attribute.zvode Usage zvode(y.function(t. . maxsteps = 5 . See details. maxord = NULL. and whose next elements are global values that are required at each point in times. the names will be used to label the output matrix. forcings = NULL. In some circumstances. outnames = NULL. initfunc = dllname. the first value of times must be the initial time. or a vector containing the matrix elements by columns (the way R and FORTRAN store matrices). . set times = NULL. if the system is stiff. the names will be available inside func. (optional) are any other arguments passed to the function. jacfunc = NULL. atol = 1e-8. parms. jactype = "fullint".. it must be defined as: func <.. ipar = NULL. . t is the current time point in the integration. absolute error tolerance. parms. where the ith row contains the derivative of dyi /dt with respect to yj . tcrit = NULL. nout = . hmax = NULL. bandup = NULL. If the initial values y has a names attribute.. y has to be complex time sequence for which output is wanted. See details. See package vignette "compiledCode" for more details. func. relative error tolerance. The return value of func should be a list. If func is a string. The R calling sequence for jacfunc is identical to that of func. parms rtol atol jacfunc . If func is an R-function. parms is a vector or list of parameters. or a character string giving the name of a compiled function in a dynamically loaded shared library. mf = NULL. rpar = NULL. if not NULL. banddown = NULL. y is the current estimate of the variables in the ODE system. dllname = NULL. They should be complex numbers. whose first element is a vector containing the derivatives of y with respect to time.). or a string giving the name of a function or subroutine in ˙ ‘dllname’ that computes the Jacobian (see vignette "compiledCode" for more about this option). either a scalar or an array as long as y.. supplying jacfunc can speed up the computations. vector or list of parameters used in func or jacfunc. initforc = NULL. Its elements should be complex numbers. y. fcontrol = NULL. jacfunc should return a matrix dy/dy. initpar = parms. an R function that computes the Jacobian of the system of differential equations ∂ yi /∂yj . times. ynames = TRUE. if only one step is to be taken. either an R-function that computes the values of the derivatives in the ODE system (the model definition) at time t.. hmin = . The derivatives should be specified in the same order as the state variables y..) Arguments y times func 133 the initial (state) values for the ODE system. verbose = FALSE. rtol = 1e-6. then dllname must give the name of the shared library (without extension) which must be loaded before zvode() is called. either a scalar or an array as long as y. ˙ If the Jacobian is a full matrix.

hmax is set to the largest difference in times.see details.provides more options than jactype . overruled if mf is not NULL. i. jactype the structure of the Jacobian.overrules jactype . and interpolates values for the desired time points. that should be provided in tcrit. if not NULL. the name of the initialisation function (which initialises values of parameters). If 0. NULL uses the default. then zvode cannot integrate past tcrit. "fullusr". mf verbose tcrit hmin hmax hini ynames maxord bandup banddown maxsteps dllname initfunc initpar rpar ipar . Reduce maxord to save storage space. See package vignette "compiledCode".134 zvode If the Jacobian is banded. order 5 if BDF method (meth = 2). number of non-zero bands below the diagonal. if TRUE: full output to the screen. C++). e. The FORTRAN routine dvode overshoots its targets (times points in the vector times). maximal number of steps per output interval taken by the solver. only when ‘dllname’ is specified: a vector with double precision values passed to the DLL-functions whose names are specified by func and jacfunc. jacfunc should return a matrix containing only the nonzero bands of the Jacobian. logical. the "method flag" passed to function zvode . initial step size to be attempted. See package vignette "compiledCode". If not specified. one of "fullint". an optional minimum value of the integration stepsize.e. order 12 if implicit Adams method (meth = 1). a string giving the name of the shared library (without extension) that contains all the compiled function or subroutine definitions refered to in func and jacfunc. "bandusr" or "bandint" . the maximum order to be allowed. only when ‘dllname’ is specified and an initialisation function initfunc is in the dll: the parameters passed to the initialiser. In special situations this parameter may speed up computations with the cost of precision. only when ‘dllname’ is specified: a vector with integer values passed to the dll-functions whose names are specified by func and jacfunc. if FALSE: names of state variables are not passed to function func . See first example of lsode.either full or banded and estimated internally or by user. if 0. will print the diagnostiscs of the integration . Don’t use hmin if you don’t know why! an optional maximum value of the integration stepsize. no maximal size is specified. if not NULL. in case the Jacobian is banded. number of non-zero bands above the diagonal. If there is a time beyond which integration should not proceed (perhaps because of a singularity).g. to avoid that the simulation possibly ignores short-term events. as provided in ‘dllname’. to initialise the common blocks (FORTRAN) or global variables (C. in case the Jacobian is banded. this may speed up the simulation especially for multi-D models.see details. the initial step size is determined by the solver. rotated row-wise.

max(times)] is done by taking the value at the closest data extreme..zvode nout 135 only used if dllname is specified and the model is defined in compiled code: the number of output variables calculated in the compiled function func. the name of the forcing function initialisation function. only used if ‘dllname’ is specified and nout > 0: the names of output variables calculated in the compiled function func. See forcings or package vignette "compiledCode". interpolation outside the interval [min(times). A list of control parameters for the forcing functions. Analyticity means that the partial derivative df(i)/dy(j) is a unique complex number. it will be used to label the columns of the output value. that is. each present as a two-columned matrix. and this fact is critical in the way zvode solves the dense or banded linear systems that arise in the stiff case. when each f(i) is an analytic function of each y(j). if not NULL. There will be a row for each element in times unless the FORTRAN routine ‘zvode’ returns with an unrecoverable error.you have to perform this check in the code .nl> . If y has a names attribute. present in the shared library. with (time. as provided in ‘dllname’. and for this problem one should instead use ode on the equivalent real system (in the real and imaginary parts of y). for details Value A matrix of class deSolve with up to as many rows as elements in times and as many columns as elements in y plus the number of "global" values returned in the next elements of the return from func. It MUST be present if forcings has been given a value. Author(s) Karline Soetaert <k. outnames forcings initforc fcontrol .knaw. Details see vode. plus and additional column for the time value. See forcings or package vignette "compiledCode". forcings or package vignette "compiledCode" additional arguments passed to func and jacfunc allowing this to be a generic function.. only used if ‘dllname’ is specified: a list with the forcing function data sets.See package vignette "compiledCode". zvode is likely to have convergence failures.f source code): When using zvode for a stiff system. These names will be used to label the output matrix. Note (adapted from the zvode.value). the double precision version. For a complex stiff ODE system in which f is not analytic.soetaert@nioo. present in the shared library. it should only be used for the case in which the function f is analytic. Note: it is not automatically checked whether this is indeed the number of output variables calculated in the DLL .

function(Time. times = times. Jackson and R.. LLNL Report UCID-30112. parms = pars. D. G. Netlib: http://www. Sacks-Davis. SIAM J. Comput.c(f = 1+ i) <. North-Holland.NULL <. eds. A. Hindmarsh. Byrne and A. June 1988. pp. C.org See Also vode for the double precision version Examples ## ## ## ## ## ======================================================================= Example 1 . C. pp. April 1976.1i*f return(list(df)) } pars yini times out atol <.. LLNL Report UCID-30132. EPISODEB: An Experimental Package for the Integration of Systems of Ordinary Differential Equations with Banded Jacobians. 1983. C. VODE: A Variable Coefficient ODE Solver. G. 10. Rev. 295-318. K. and A. Math. 1975. Software. 1989. 1976.2]. Hindmarsh. pp. D.netlib. C. length = 1 ) <. Pars) { df <. = 1e-1 . Stat. 1. Hindmarsh.exp(1i * times) ## compare numerical and analytical solution tail(cbind(out[. A Polyalgorithm for the Numerical Solution of Ordinary Differential Equations. ODEPACK.seq( . N. rtol = 1e-1 ) # The analytical solution to this ODE is the exp-function: # f(t) = exp(1i*t) # = cos(t)+1i*sin(t) (due to Euler’s equation) analytical. in Scientific Computing. y = yini. analytical. 1. R. Stepleman et al. Brown. Hindmarsh. Amsterdam. S.very simple example df/dt = 1i*f.136 References zvode P. a Systematized Collection of ODE Solvers. ACM Trans. ACM Trans. Byrne. A.. 1980. An Alternative Implementation of Variable Step-Size Multistep Formulas for Stiff ODEs. EPISODE: An Effective Package for the Integration of Systems of Ordinary Differential Equations. Byrne and A. 1977. 1038-1051. Also. Math. where 1i is the imaginary unit The initial value is f( ) = 1 = 1+ i ======================================================================= ZODE <. pp.solution)) . 71-96.solution <. LLNL Report UCRL-98412. D. R. 2*pi. Byrne. Sci. f. D. 6. Hindmarsh and G. C. 55-64.zvode(func = ZODE. G. Software.

State. { df <. df/dt = 1i*f (same as above ODE) dg/dt = -1i*g*g*f (an additional ODE depending on f) Initial values are g( ) = 1/2.-1i * g*g * f return(list(c(df. g = 1/2.example in "zvode.1) analytical <.f".2]. rtol = 1e-1 ) ## The analytical solution is ## f(t) = exp(1i*t) (same as above) ## g(t) = 1/(f(t) + 1.c(f = 1 + i. times = times.1 + i) <.1i * f dg <. 2*pi. y = yini.cbind(f = exp(1i * times). = 1e-1 . analytical[.1)) ## compare numerical solution and the two analytical ones: tail(cbind(out[. g = 1/(exp(1i * times) + 1.1])) .zvode(func = ZODE2.list(State).1 and z( ) = 1 ======================================================================= ZODE2<-function(Time.seq( . dg))) }) } yini times out atol <. length = 1 ) <. parms = NULL.Pars) { with(as.zvode 137 ## ## ## ## ## ## ## ## ## ======================================================================= Example 2 .

72. 45. 86 ode. 4.deSolve. 113. 44. 110. 27 DLLfunc. 38 timelags.deSolve). 125 zvode. 99 rk. 106 . 121 . 130 euler (rk4). 110. 62 ode. 92. 10 ccl4model. 122. 106 138 . 30 events.band. 53. 39 approxfun. 59. 52. 102. 55. 2 deSolve-package. 48. 4. 114.Fortran. 129. 90 radau. 28 DLLres. 130 dede. 52. 72. 4. 111 events. 39 aquaphy. 33. 66. 51. 72. 120 ∗Topic package deSolve-package. 94 diagnostics.deSolve (plot. 38. 4. 43–45. 114. 128 forcings.C. 17. 77. 93 ∗Topic math daspk. 103. 13. 6. 26 diagnostics. 26. 12. 27 DLLfunc. 48 lsode. 38. 52.deSolve. 10. 72. 4. 51. 17. 65. 5. 44. 121 cleanEventTimes. 67. 57. 65. 5 ccl4model. 13 lsoda. 128 deSolve. 34. 51. 72. 115 vode. 75 ode. 110. 95 hist. 18. 58. 130 diagnostics. 30 euler. 9. 121 ccl4data.deSolve. 83. 102. 70 ode. 95 . 54 lsodes. 2 dev. 111 rkMethod. 128. 45 hist. 102. 66. 44. 108. 39. 102. 4. 129. 32. 27. 103. 45. 41. 41. 81 ode. 108. 9 SCOC. 41 lsodar. 33 forcings. 52. 33 daspk. 132 ∗Topic misc cleanEventTimes. 106 rk4. 114. 45. 65. 19.Call. 17. 8 ∗Topic hplot plot. 59.2D. 2 ∗Topic utilities dede. 95 deSolve (deSolve-package). 22 diagnostics. 18. 13. 66.interactive. 59. 22. 13. 66.3D. 57. 34. 106 approx. 135 gnls. 41. 88. 57.1D. 8. 12 ∗Topic models aquaphy. 93 image.Index ∗Topic datasets ccl4data. 28 DLLres. 4. 13. 59. 19.

19. 66. 106 par. 95. 111. 72. 52. 24 lagderiv (timelags). 130 optim. 114. 72. 52. 70. 110. 130 ode. 33 SCOC. 4. 129. 92. 77. 59. 95 print. 59. 135. 45. 45. 130 ode. 34. 4. 114. 114. 34.1D (plot. 4. 130 ode. 54. 45. 19. 59.1D. 110. 48. 95 plot. 94 plot. 83. 45. 121 lsoda. 52. 103. 17. 4. 4.2D. 3. 130 rk4. 77. 130 lsodar. 92. 113 plot. 52. 103. 67.INDEX image. 59. 34. 34. 109. 23. 77. 114. 72. 95.deSolve (ode). 52. 130 lsode. 19. 53. 92. 107. 53. 77. 95. 52. 66.deSolve). 41. 72. 52. 114. 113. 45.deSolve. 114. 72. 23. 66. 52 roots (events). 83. 72. 59. 4. 55. 106 ode. 129. 106 nlme. 72. 19. 70 139 timelags. 45. 4. 67. 83.deSolve (ode). 88. 59. 19. 59. 66. 3. 110. 77. 132 .deSolve). 88. 77. 106. 24 lagvalue (timelags). 4. 136 zvode. 110. 115 roots.deSolve (plot. 93 nearestEvent (cleanEventTimes). 126.default. 51. 53. 130 rkMethod. 130 lsodes. 19. 45. 93 lagderiv. 45. 117 rk. 99. 72. 23. 83. 45. 110. 4. 58. 41. 77. 52. 114. 113–115. 41. 121 lagvalue. 118. 128 timestep (timelags). 52. 93 print.deSolve). 106 nls.deSolve. 114. 72. 51. 66. 19. 4. 113. 19. 19. 19.deSolve (plot. 121 vode. 110. 130 ode. 81. 55. 92. 86. 72. 41. 91. 110. 66. 18. 103.deSolve). 3. 44. 62. 93 plot. 72. 12 nlm. 93 summary. 34. 72. 90. 19. 45.band. 92. 102. 114. 70 radau. 83.1D (plot. 88. 77. 4. 19. 110. 91. 4. 82.3D. 65. 92. 77. 130 matplot. 120 subset. 125. 57. 66. 110. 110. 59. 121. 88. 110. 45. 41. 3. 59. 59. 67. 30. 4. 126. 110. 48. 4. 67. 113–115. 4. 4. 75. 114. 108. 72. 88. 71. 118. 19.1D. 59. 113. 103. 45.