Docsity

Package deSolve: Solving Initial Value Differential Equations ..., Study notes of Differential Equations

Toggle sidebar
bg1
Package deSolve: Solving Initial Value Differential
Equations in R
Karline Soetaert
Royal Netherlands Institute
of Sea Research (NIOZ)
Yerseke, The Netherlands
Thomas Petzoldt
Technische UniversitĀØ
at
Dresden
Germany
R. Woodrow Setzer
National Center for
Computational Toxicology
US Environmental Protection Agency
Abstract
Rpackage deSolve (BlueSoetaert, Petzoldt, and Setzer Blue2010b,Bluec) the successor
of Rpackage odesolve is a package to solve initial value problems (IVP) of:
ā¼
ordinary differential equations (ODE),
ā¼
differential algebraic equations (DAE),
ā¼
partial differential equations (PDE) and
ā¼
delay differential equations (DeDE).
The implementation includes stiff and nonstiff integration routines based on the ODE-
PACK FORTRAN codes (BlueHindmarsh Blue1983). It also includes fixed and adaptive
time-step explicit Runge-Kutta solvers and the Euler method (BluePress, Teukolsky, Vet-
terling, and Flannery Blue1992), and the implicit Runge-Kutta method RADAU (Blue-
Hairer and Wanner Blue2010).
In this vignette we outline how to implement differential equations as R-functions.
Another vignette (ā€œcompiledCodeā€) (BlueSoetaert, Petzoldt, and Setzer Blue2008), deals
with differential equations implemented in lower-level languages such as FORTRAN,C,
or C++, which are compiled into a dynamically linked library (DLL) and loaded into R
(BlueRDevelopment Core Team Blue2008).
Note that another package, bvpSolve provides methods to solve boundary value prob-
lems (BlueSoetaert, Cash, and Mazzia Blue2010a).
Keywords: differential equations, ordinary differential equations, differential algebraic equa-
tions, partial differential equations, initial value problems, R.
1. A simple ODE: chaos in the atmosphere
The Lorenz equations (Lorenz, 1963) were the first chaotic dynamic system to be described.
They consist of three differential equations that were assumed to represent idealized behavior
of the earth’s atmosphere. We use this model to demonstrate how to implement and solve
differential equations in R. The Lorenz model describes the dynamics of three state variables,
X,Yand Z. The model equations are:
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34

Partial preview of the text

Download Package deSolve: Solving Initial Value Differential Equations ... and more Study notes Differential Equations in PDF only on Docsity!

Package deSolve: Solving Initial Value Differential

Equations in R

Karline Soetaert

Royal Netherlands Institute of Sea Research (NIOZ) Yerseke, The Netherlands

Thomas Petzoldt

Technische UniversitĀØat Dresden Germany

R. Woodrow Setzer

National Center for Computational Toxicology US Environmental Protection Agency

Abstract R package deSolve (BlueSoetaert, Petzoldt, and Setzer Blue2010b,Bluec) the successor of R package odesolve is a package to solve initial value problems (IVP) of: ā¼ ordinary differential equations (ODE), ā¼ differential algebraic equations (DAE), ā¼ partial differential equations (PDE) and ā¼ delay differential equations (DeDE). The implementation includes stiff and nonstiff integration routines based on the ODE- PACK FORTRAN codes (BlueHindmarsh Blue1983). It also includes fixed and adaptive time-step explicit Runge-Kutta solvers and the Euler method (BluePress, Teukolsky, Vet- terling, and Flannery Blue1992), and the implicit Runge-Kutta method RADAU (Blue- Hairer and Wanner Blue2010). In this vignette we outline how to implement differential equations as R -functions. Another vignette (ā€œcompiledCodeā€) (BlueSoetaert, Petzoldt, and Setzer Blue2008), deals with differential equations implemented in lower-level languages such as FORTRAN, C, or C++, which are compiled into a dynamically linked library (DLL) and loaded into R (BlueR Development Core Team Blue2008). Note that another package, bvpSolve provides methods to solve boundary value prob- lems (BlueSoetaert, Cash, and Mazzia Blue2010a).

Keywords: differential equations, ordinary differential equations, differential algebraic equa- tions, partial differential equations, initial value problems, R.

1. A simple ODE: chaos in the atmosphere

The Lorenz equations (Lorenz, 1963) were the first chaotic dynamic system to be described. They consist of three differential equations that were assumed to represent idealized behavior of the earth’s atmosphere. We use this model to demonstrate how to implement and solve differential equations in R. The Lorenz model describes the dynamics of three state variables, X, Y and Z. The model equations are:

2 Package deSolve: Solving Initial Value Differential Equations in R

dX dt

= a Ā· X + Y Ā· Z dY dt = b Ā· (Y āˆ’ Z) dZ dt

= āˆ’X Ā· Y + c Ā· Y āˆ’ Z

with the initial conditions:

X(0) = Y (0) = Z(0) = 1

Where a, b and c are three parameters, with values of -8/3, -10 and 28 respectively.

Implementation of an IVP ODE in R can be separated in two parts: the model specification and the model application. Model specification consists of:

ā¼ Defining model parameters and their values,

ā¼ Defining model state variables and their initial conditions,

ā¼ Implementing the model equations that calculate the rate of change (e.g. dX/dt) of the state variables.

The model application consists of:

ā¼ Specification of the time at which model output is wanted,

ā¼ Integration of the model equations (uses R-functions from deSolve),

ā¼ Plotting of model results.

Below, we discuss the R-code for the Lorenz model.

1.1. Model specification

Model parameters

There are three model parameters: a, b, and c that are defined first. Parameters are stored as a vector with assigned names and values:

> parameters <- c(a = -8/3,

  • b = -10,
  • c = 28)

State variables

The three state variables are also created as a vector, and their initial values given:

4 Package deSolve: Solving Initial Value Differential Equations in R

required (times), the model function that returns the rate of change (func) and the parameter vector (parms).

Function ode returns an object of class deSolve with a matrix that contains the values of the state variables (columns) at the requested output times.

> library(deSolve) > out <- ode(y = state, times = times, func = Lorenz, parms = parameters) > head(out)

time X Y Z [1,] 0.00 1.0000000 1.000000 1. [2,] 0.01 0.9848912 1.012567 1. [3,] 0.02 0.9731148 1.048823 1. [4,] 0.03 0.9651593 1.107207 1. [5,] 0.04 0.9617377 1.186866 2. [6,] 0.05 0.9638068 1.287555 2.

Plotting results

Finally, the model output is plotted. We use the plot method designed for objects of class deSolve, which will neatly arrange the figures in two rows and two columns; before plotting, the size of the outer upper margin (the third margin) is increased (oma), such as to allow writing a figure heading (mtext). First all model variables are plotted versus time, and finally Z versus X:

> par(oma = c(0, 0, 3, 0)) > plot(out, xlab = "time", ylab = "-") > plot(out[, "X"], out[, "Z"], pch = ".") > mtext(outer = TRUE, side = 3, "Lorenz model", cex = 1.5)

Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer 5

0 20 40 60 80 100

0

10

20

30

40

X

time

āˆ’

0 20 40 60 80 100

āˆ’

0

10

20

Y

time

āˆ’

0 20 40 60 80 100

āˆ’

āˆ’

0

10

20

Z

time

āˆ’

0 10 20 30 40

āˆ’

āˆ’

0

10

20

out[, "X"]

out[, "Z"]

Lorenz model

Figure 1: Solution of the ordinary differential equation - see text for R-code

Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer 7

user system elapsed 0.25 0.00 0.

> print(system.time(out <- daspk (state, times, Lorenz, parameters)))

user system elapsed 0.35 0.03 0.

> print(system.time(out <- vode (state, times, Lorenz, parameters)))

user system elapsed 0.26 0.00 0.

2.1. Runge-Kutta methods and Euler

The explicit Runge-Kutta methods are de novo implementations in C, based on the Butcher tables (Butcher 1987). They comprise simple Runge-Kutta formulae (Euler’s method euler, Heun’s method rk2, the classical 4th order Runge-Kutta, rk4) and several Runge-Kutta pairs of order 3(2) to order 8(7). The embedded, explicit methods are according to Fehlberg ( 1967 ) (rk..f, ode45), Dormand and Prince ( 1980 , 1981 ) (rk..dp.), Bogacki and Shampine ( 1989 ) (rk23bs, ode23) and Cash and Karp ( 1990 ) (rk45ck), where ode23 and ode45 are aliases for the popular methods rk23bs resp. rk45dp7.

With the following statement all implemented methods are shown:

> rkMethod()

[1] "euler" "rk2" "rk4" "rk23" "rk23bs" "rk34f" [7] "rk45f" "rk45ck" "rk45e" "rk45dp6" "rk45dp7" "rk78dp" [13] "rk78f" "irk3r" "irk5r" "irk4hh" "irk6kb" "irk4l" [19] "irk6l" "ode23" "ode45"

This list also contains implicit Runge-Kutta’s (irk..), but they are not yet optimally coded. The only well-implemented implicit Runge-Kutta is the radau method (Hairer and Wanner 2010 ) that will be discussed in the section dealing with differential algebraic equations.

The properties of a Runge-Kutta method can be displayed as follows:

> rkMethod("rk23")

$ID

[1] "rk23"

$varstep [1] TRUE

$FSAL

8 Package deSolve: Solving Initial Value Differential Equations in R

[1] FALSE

$A

[,1] [,2] [,3]

[1,] 0.0 0 0

[2,] 0.5 0 0

[3,] -1.0 2 0

$b [1] 0 1 0

$b [1] 0.1666667 0.6666667 0.

$c [1] 0.0 0.5 2.

$stage [1] 3

$Qerr [1] 2

attr(,"class") [1] "list" "rkMethod"

Here varstep informs whether the method uses a variable time-step; FSAL whether the first same as last strategy is used, while stage and Qerr give the number of function evaluations needed for one step, and the order of the local truncation error. A, b1, b2, c are the coefficients of the Butcher table. Two formulae (rk45dp7, rk45ck) support dense output.

It is also possible to modify the parameters of a method (be very careful with this) or define and use a new Runge-Kutta method:

> func <- function(t, x, parms) {

  • with(as.list(c(parms, x)),{
  • dP <- a * P - b * C * P
  • dC <- b * P * C - c * C
  • res <- c(dP, dC)
  • list(res)
  • })
  • } > rKnew <- rkMethod(ID = "midpoint",
  • varstep = FALSE,
  • A = c(0, 1/2),
  • b1 = c(0, 1),
  • c = c(0, 1/2),
  • stage = 2,

10 Package deSolve: Solving Initial Value Differential Equations in R

return code (idid) = 0 Integration was successful.

INTEGER values

1 The return code : 0 2 The number of steps taken for the problem so far: 10000 3 The number of function evaluations for the problem so far: 40001 18 The order (or maximum order) of the method: 4

> diagnostics(out2)

lsode return code

return code (idid) = 2 Integration was successful.

INTEGER values

1 The return code : 2 2 The number of steps taken for the problem so far: 12778 3 The number of function evaluations for the problem so far: 16633 5 The method order last used (successfully): 5 6 The order of the method to be attempted on the next step: 5 7 If return flag =-4,-5: the largest component in error vector 0 8 The length of the real work array actually required: 58 9 The length of the integer work array actually required: 23 14 The number of Jacobian evaluations and LU decompositions so far: 721

RSTATE values

1 The step size in t last used (successfully): 0. 2 The step size to be attempted on the next step: 0. 3 The current value of the independent variable which the solver has reached: 100. 4 Tolerance scale factor > 1.0 computed when requesting too much accuracy: 0

There is also a summary method for deSolve objects. This is especially handy for multi- dimensional problems (see below)

> summary(out1)

  • Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer
  • Min. 9.617372e-01 -17.965128 -24. X Y Z
  • 1st Qu. 1.702231e+01 -7.347550 -7.
  • Median 2.305675e+01 -1.946728 -1.
  • Mean 2.368979e+01 -1.385164 -1.
  • 3rd Qu. 3.020200e+01 3.606680 2.
  • Max. 4.783395e+01 19.555041 27.
  • N 1.000100e+04 10001.000000 10001.
  • sd 8.501340e+00 7.846889 8.

Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer 13

Note that the values of state variables (here densities) are defined in the centre of boxes (i), whereas the fluxes are defined on the box interfaces. We refer to Soetaert and Herman ( 2009 ) for more information about this model and its numerical approximation.

Here is its implementation in R. First the model equations are defined:

> Aphid <- function(t, APHIDS, parameters) {

  • deltax <- c (0.5, rep(1, numboxes - 1), 0.5)
  • Flux <- -D * diff(c(0, APHIDS, 0)) / deltax
  • dAPHIDS <- -diff(Flux) / delx + APHIDS * r
  • the return value

  • list(dAPHIDS )
  • } # end

Then the model parameters and spatial grid are defined

> D <- 0.3 # m2/day diffusion rate > r <- 0.01 # /day net growth rate > delx <- 1 # m thickness of boxes > numboxes <- 60 > # distance of boxes on plant, m, 1 m intervals > Distance <- seq(from = 0.5, by = delx, length.out = numboxes)

Aphids are initially only present in two central boxes:

> # Initial conditions: # ind/m > APHIDS <- rep(0, times = numboxes) > APHIDS[30:31] <- 1 > state <- c(APHIDS = APHIDS) # initialise state variables

The model is run for 200 days, producing output every day; the time elapsed in seconds to solve this 60 state-variable model is estimated (system.time):

> times <-seq(0, 200, by = 1) > print(system.time(

  • out <- ode.1D(state, times, Aphid, parms = 0, nspec = 1, names = "Aphid")
  • ))

user system elapsed 0.02 0.01 0.

Matrix out consist of times (1st column) followed by the densities (next columns).

> head(out[,1:5])

14 Package deSolve: Solving Initial Value Differential Equations in R

time APHIDS1 APHIDS2 APHIDS3 APHIDS [1,] 0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+ [2,] 1 1.667194e-55 9.555028e-52 2.555091e-48 4.943131e- [3,] 2 3.630860e-41 4.865105e-39 5.394287e-37 5.053775e- [4,] 3 2.051210e-34 9.207997e-33 3.722714e-31 1.390691e- [5,] 4 1.307456e-30 3.718598e-29 9.635350e-28 2.360716e- [6,] 5 6.839152e-28 1.465288e-26 2.860056e-25 5.334391e-

The summary method gives the mean, min, max, ... of the entire 1-D variable:

> summary(out)

Aphid Min. 0.000000e+ 1st Qu. 1.705086e- Median 4.051383e- Mean 1.062271e- 3rd Qu. 1.931426e- Max. 1.000000e+ N 1.206000e+ sd 1.303048e-

Finally, the output is plotted. It is simplest to do this with deSolve’s S3-method image

image(out, method = "filled.contour", grid = Distance, xlab = "time, days", ylab = "Distance on plant, m", main = "Aphid density on a row of plants")

As this is a 1-D model, it is best solved with deSolve function ode.1D. A multi-species IVP example can be found in Soetaert and Herman ( 2009 ). For 2-D and 3-D problems, we refer to the help-files of functions ode.2D and ode.3D.

The output of one-dimensional models can also be plotted using S3-method plot.1D and matplot.1D. In both cases, we can simply take a subset of the output, and add observations.

> data <- cbind(dist = c(0,10, 20, 30, 40, 50, 60),

  • Aphid = c(0,0.1,0.25,0.5,0.25,0.1,0))

> par (mfrow = c(1,2)) > matplot.1D(out, grid = Distance, type = "l", mfrow = NULL,

  • subset = time %in% seq(0, 200, by = 10),
  • obs = data, obspar = list(pch = 18, cex = 2, col="red")) > plot.1D(out, grid = Distance, type = "l", mfrow = NULL,
  • subset = time == 100,
  • obs = data, obspar = list(pch = 18, cex = 2, col="red"))

16 Package deSolve: Solving Initial Value Differential Equations in R

0 10 20 30 40 50 60

Aphid

x

0 10 20 30 40 50 60

x

Aphid

Figure 3: Solution of the Aphid model - plotted with matplot.1D, plot.1D - see text for R-code

Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer 17

  1. Differential algebraic equations

Package deSolve contains two functions that solve initial value problems of differential alge- braic equations. They are:

ā¼ radau which implements the implicit Runge-Kutta RADAU5 (Hairer and Wanner 2010),

ā¼ daspk, based on the backward differentiation code DASPK (Brenan, Campbell, and Petzold 1996).

Function radau needs the input in the form M y′^ = f (t, y, y′) where M is the mass matrix. Function daspk also supports this input, but can also solve problems written in the form F (t, y, y′) = 0.

radau solves problems up to index 3; daspk solves problems of index ≤ 1.

4.1. DAEs of index maximal 1

Function daspk from package deSolve solves (relatively simple) DAEs of index^2 maximal 1.

The DAE has to be specified by the residual function instead of the rates of change (as in ODE). Consider the following simple DAE:

dy 1 dt = āˆ’y 1 + y 2 y 1 Ā· y 2 = t

where the first equation is a differential, the second an algebraic equation. To solve it, it is first rewritten as residual functions:

dy 1 dt

  • y 1 āˆ’ y 2 0 = y 1 Ā· y 2 āˆ’ t

In R we write:

> daefun <- function(t, y, dy, parameters) {

  • res1 <- dy[1] + y[1] - y[2]
  • res2 <- y[2] * y[1] - t
  • list(c(res1, res2))
  • } > library(deSolve) > yini <- c(1, 0) > dyini <- c(1, 0) > times <- seq(0, 10, 0.1) > ## solver > system.time(out <- daspk(y = yini, dy = dyini,
  • times = times, res = daefun, parms = 0)) (^2) note that many – apparently simple – DAEs are higher-index DAEs

Karline Soetaert, Thomas Petzoldt, R. Woodrow Setzer 19

A consistent set of initial conditions are:

> yini <- c(x = 1, y = 0, u = 0, v = 1, lam = 1)

and the mass matrix M :

> M <- diag(nrow = 5) > M[5, 5] <- 0 > M

[,1] [,2] [,3] [,4] [,5]

[1,] 1 0 0 0 0

[2,] 0 1 0 0 0

[3,] 0 0 1 0 0

[4,] 0 0 0 1 0

[5,] 0 0 0 0 0

Function radau requires that the index of each equation is specified; there are 2 equations of index 1, two of index 2, one of index 3:

> index <- c(2, 2, 1) > times <- seq(from = 0, to = 10, by = 0.01) > out <- radau (y = yini, func = pendulum, parms = NULL,

  • times = times, mass = M, nind = index)

> plot(out, type = "l", lwd = 2) > plot(out[, c("x", "y")], type = "l", lwd = 2)

20 Package deSolve: Solving Initial Value Differential Equations in R

0 2 4 6 8 10

āˆ’1.

āˆ’0.

x

time

0 2 4 6 8 10

āˆ’1.

āˆ’0.

āˆ’0.

āˆ’0.

āˆ’0.

y

time

0 2 4 6 8 10

āˆ’

āˆ’

0

2

4

u

time

0 2 4 6 8 10

āˆ’

āˆ’

āˆ’

0

1

2

3

v

time

0 2 4 6 8 10

0

5

10

15

20

25

30

lam

time

āˆ’1.0 0.0 0.5 1.

āˆ’1.

āˆ’0.

āˆ’0.

āˆ’0.

āˆ’0.

x

y

Figure 5: Solution of the pendulum problem, an index 3 differential algebraic equation using radau - see text for R-code