Debian Codegraph @

man/ode.2D.Rd

raw
1 \name{ode.2D}
2 \alias{ode.2D}
3
4 \title{Solver for 2-Dimensional Ordinary Differential Equations}
5
6 \description{
7 Solves a system of ordinary differential equations resulting from
8 2-Dimensional partial differential equations
9 that have been converted to ODEs by numerical differencing.
10 }
11
12 \usage{
13 ode.2D(y, times, func, parms, nspec = NULL, dimens,
14 method= c("lsodes", "euler", "rk4", "ode23", "ode45", "adams", "iteration"),
15 names = NULL, cyclicBnd = NULL, ...)
16 }
17 \arguments{
18 \item{y }{the initial (state) values for the ODE system, a vector. If
19 \code{y} has a name attribute, the names will be used to label the
20 output matrix.
21 }
22 \item{times }{time sequence for which output is wanted; the first
23 value of \code{times} must be the initial time.
24 }
25 \item{func }{either an \R-function that computes the values of the
26 derivatives in the ODE system (the model definition) at time
27 \code{t}, or a character string giving the name of a compiled
28 function in a dynamically loaded shared library.
29
30 If \code{func} is an \R-function, it must be defined as:
31 \code{func <- function(t, y, parms, ...)}. \code{t} is the current time
32 point in the integration, \code{y} is the current estimate of the
33 variables in the ODE system. If the initial values \code{y} has a
34 \code{names} attribute, the names will be available inside \code{func}.
35 \code{parms} is a vector or list of parameters; \code{...} (optional) are
36 any other arguments passed to the function.
37
38 The return value of \code{func} should be a list, whose first
39 element is a vector containing the derivatives of \code{y} with
40 respect to \code{time}, and whose next elements are global values
41 that are required at each point in \code{times}. The derivatives
42 must be specified in the \bold{same order} as the state variables \code{y}.
43
44 }
45 \item{parms }{parameters passed to \code{func}.}
46 \item{nspec }{the number of \bold{species} (components) in the model.}
47 \item{dimens}{2-valued vector with the number of \bold{boxes} in two
48 dimensions in the model.
49 }
50 \item{cyclicBnd }{if not \code{NULL} then a number or a 2-valued vector
51 with the dimensions where a cyclic boundary is used - \code{1}: x-dimension,
52 \code{2}: y-dimension; see details.
53 }
54 \item{names }{the names of the components; used for plotting.
55 }
56 \item{method }{the integrator. Use \code{"lsodes"} if the model is very stiff;
57 \code{"impAdams"} may be best suited for mildly stiff problems;
58 \code{"euler", "rk4", "ode23", "ode45", "adams"} are most
59 efficient for non-stiff problems. Also allowed is to pass an integrator
60 \code{function}. Use one of the other Runge-Kutta methods via
61 \code{rkMethod}. For instance, \code{method = rkMethod("ode45ck")} will
62 trigger the Cash-Karp method of order 4(5).
63
64 If \code{"lsodes"} is used, then also the size of the work array should
65 be specified (\code{lrw}) (see \link{lsodes}).
66
67 Method \code{"iteration"} is special in that here the function \code{func} should
68 return the new value of the state variables rather than the rate of change.
69 This can be used for individual based models, for difference equations,
70 or in those cases where the integration is performed within \code{func})
71
72 }
73 \item{... }{additional arguments passed to \code{lsodes}.}
74 }
75 \value{
76
77 A matrix of class \code{deSolve} with up to as many rows as elements in times and as many
78 columns as elements in \code{y} plus the number of "global" values
79 returned in the second element of the return from \code{func}, plus an
80 additional column (the first) for the time value. There will be one
81 row for each element in \code{times} unless the integrator returns
82 with an unrecoverable error. If \code{y} has a names attribute, it
83 will be used to label the columns of the output value.
84
85 The output will have the attributes \code{istate}, and \code{rstate},
86 two vectors with several useful elements. The first element of istate
87 returns the conditions under which the last call to the integrator
88 returned. Normal is \code{istate = 2}. If \code{verbose = TRUE}, the
89 settings of istate and rstate will be written to the screen. See the
90 help for the selected integrator for details.
91
92 }
93 \note{
94 It is advisable though not mandatory to specify \bold{both}
95 \code{nspec} and \code{dimens}. In this case, the solver can check
96 whether the input makes sense (as \code{nspec * dimens[1] * dimens[2]
97 == length(y)}).
98
99 Do \bold{not} use this method for problems that are not 2D!
100 }
101 \author{Karline Soetaert <[email protected]>}
102 \examples{
103 ## =======================================================================
104 ## A Lotka-Volterra predator-prey model with predator and prey
105 ## dispersing in 2 dimensions
106 ## =======================================================================
107
108 ## ==================
109 ## Model definitions
110 ## ==================
111
112 lvmod2D <- function (time, state, pars, N, Da, dx) {
113 NN <- N*N
114 Prey <- matrix(nrow = N, ncol = N,state[1:NN])
115 Pred <- matrix(nrow = N, ncol = N,state[(NN+1):(2*NN)])
116
117 with (as.list(pars), {
118 ## Biology
119 dPrey <- rGrow * Prey * (1- Prey/K) - rIng * Prey * Pred
120 dPred <- rIng * Prey * Pred*assEff - rMort * Pred
121
122 zero <- rep(0, N)
123
124 ## 1. Fluxes in x-direction; zero fluxes near boundaries
125 FluxPrey <- -Da * rbind(zero,(Prey[2:N,] - Prey[1:(N-1),]), zero)/dx
126 FluxPred <- -Da * rbind(zero,(Pred[2:N,] - Pred[1:(N-1),]), zero)/dx
127
128 ## Add flux gradient to rate of change
129 dPrey <- dPrey - (FluxPrey[2:(N+1),] - FluxPrey[1:N,])/dx
130 dPred <- dPred - (FluxPred[2:(N+1),] - FluxPred[1:N,])/dx
131
132 ## 2. Fluxes in y-direction; zero fluxes near boundaries
133 FluxPrey <- -Da * cbind(zero,(Prey[,2:N] - Prey[,1:(N-1)]), zero)/dx
134 FluxPred <- -Da * cbind(zero,(Pred[,2:N] - Pred[,1:(N-1)]), zero)/dx
135
136 ## Add flux gradient to rate of change
137 dPrey <- dPrey - (FluxPrey[,2:(N+1)] - FluxPrey[,1:N])/dx
138 dPred <- dPred - (FluxPred[,2:(N+1)] - FluxPred[,1:N])/dx
139
140 return(list(c(as.vector(dPrey), as.vector(dPred))))
141 })
142 }
143
144
145 ## ===================
146 ## Model applications
147 ## ===================
148
149 pars <- c(rIng = 0.2, # /day, rate of ingestion
150 rGrow = 1.0, # /day, growth rate of prey
151 rMort = 0.2 , # /day, mortality rate of predator
152 assEff = 0.5, # -, assimilation efficiency
153 K = 5 ) # mmol/m3, carrying capacity
154
155 R <- 20 # total length of surface, m
156 N <- 50 # number of boxes in one direction
157 dx <- R/N # thickness of each layer
158 Da <- 0.05 # m2/d, dispersion coefficient
159
160 NN <- N*N # total number of boxes
161
162 ## initial conditions
163 yini <- rep(0, 2*N*N)
164 cc <- c((NN/2):(NN/2+1)+N/2, (NN/2):(NN/2+1)-N/2)
165 yini[cc] <- yini[NN+cc] <- 1
166
167 ## solve model (5000 state variables... use Cash-Karp Runge-Kutta method
168 times <- seq(0, 50, by = 1)
169 out <- ode.2D(y = yini, times = times, func = lvmod2D, parms = pars,
170 dimens = c(N, N), names = c("Prey", "Pred"),
171 N = N, dx = dx, Da = Da, method = rkMethod("rk45ck"))
172
173 diagnostics(out)
174 summary(out)
175
176 # Mean of prey concentration at each time step
177 Prey <- subset(out, select = "Prey", arr = TRUE)
178 dim(Prey)
179 MeanPrey <- apply(Prey, MARGIN = 3, FUN = mean)
180 plot(times, MeanPrey)
181
182 \dontrun{
183 ## plot results
184 Col <- colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan",
185 "#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
186
187 for (i in seq(1, length(times), by = 1))
188 image(Prey[ , ,i],
189 col = Col(100), xlab = , zlim = range(out[,2:(NN+1)]))
190
191 ## similar, plotting both and adding a margin text with times:
192 image(out, xlab = "x", ylab = "y", mtext = paste("time = ", times))
193 }
194
195 select <- c(1, 40)
196 image(out, xlab = "x", ylab = "y", mtext = "Lotka-Volterra in 2-D",
197 subset = select, mfrow = c(2,2), legend = TRUE)
198
199
200 # plot prey and pred at t = 10; first use subset to select data
201 prey10 <- matrix (nrow = N, ncol = N,
202 data = subset(out, select = "Prey", subset = (time == 10)))
203 pred10 <- matrix (nrow = N, ncol = N,
204 data = subset(out, select = "Pred", subset = (time == 10)))
205
206 mf <- par(mfrow = c(1, 2))
207 image(prey10)
208 image(pred10)
209 par (mfrow = mf)
210
211 # same, using deSolve's image:
212 image(out, subset = (time == 10))
213
214 ## =======================================================================
215 ## An example with a cyclic boundary condition.
216 ## Diffusion in 2-D; extra flux on 2 boundaries,
217 ## cyclic boundary in y
218 ## =======================================================================
219
220
221 diffusion2D <- function(t, Y, par) {
222 y <- matrix(nrow = nx, ncol = ny, data = Y) # vector to 2-D matrix
223 dY <- -r * y # consumption
224 BNDx <- rep(1, nx) # boundary concentration
225 BNDy <- rep(1, ny) # boundary concentration
226
227 ## diffusion in X-direction; boundaries=imposed concentration
228 Flux <- -Dx * rbind(y[1,] - BNDy, (y[2:nx,] - y[1:(nx-1),]), BNDy - y[nx,])/dx
229 dY <- dY - (Flux[2:(nx+1),] - Flux[1:nx,])/dx
230
231 ## diffusion in Y-direction
232 Flux <- -Dy * cbind(y[,1] - BNDx, (y[,2:ny]-y[,1:(ny-1)]), BNDx - y[,ny])/dy
233 dY <- dY - (Flux[,2:(ny+1)] - Flux[,1:ny])/dy
234
235 ## extra flux on two sides
236 dY[,1] <- dY[,1] + 10
237 dY[1,] <- dY[1,] + 10
238
239 ## and exchange between sides on y-direction
240 dY[,ny] <- dY[,ny] + (y[,1] - y[,ny]) * 10
241 return(list(as.vector(dY)))
242 }
243
244 ## parameters
245 dy <- dx <- 1 # grid size
246 Dy <- Dx <- 1 # diffusion coeff, X- and Y-direction
247 r <- 0.05 # consumption rate
248
249 nx <- 50
250 ny <- 100
251 y <- matrix(nrow = nx, ncol = ny, 1)
252
253 ## model most efficiently solved with lsodes - need to specify lrw
254
255 print(system.time(
256 ST3 <- ode.2D(y, times = 1:100, func = diffusion2D, parms = NULL,
257 dimens = c(nx, ny), verbose = TRUE, names = "Y",
258 lrw = 400000, atol = 1e-10, rtol = 1e-10, cyclicBnd = 2)
259 ))
260
261 # summary of 2-D variable
262 summary(ST3)
263
264 # plot output at t = 10
265 t10 <- matrix (nrow = nx, ncol = ny,
266 data = subset(ST3, select = "Y", subset = (time == 10)))
267
268 persp(t10, theta = 30, border = NA, phi = 70,
269 col = "lightblue", shade = 0.5, box = FALSE)
270
271 # image plot, using deSolve's image function
272 image(ST3, subset = time == 10, method = "persp",
273 theta = 30, border = NA, phi = 70, main = "",
274 col = "lightblue", shade = 0.5, box = FALSE)
275
276 \dontrun{
277 zlim <- range(ST3[, -1])
278 for (i in 2:nrow(ST3)) {
279 y <- matrix(nrow = nx, ncol = ny, data = ST3[i, -1])
280 filled.contour(y, zlim = zlim, main = i)
281 }
282
283 # same
284 image(ST3, method = "filled.contour")
285 }
286
287 }
288 \details{
289 This is the method of choice for 2-dimensional models, that are only
290 subjected to transport between adjacent layers.
291
292 Based on the dimension of the problem, and if \code{lsodes} is used as
293 the integrator, the method first calculates the
294 sparsity pattern of the Jacobian, under the assumption that transport
295 is only occurring between adjacent layers. Then \code{lsodes} is
296 called to solve the problem.
297
298 If the model is not stiff, then it is more efficient to use one of the
299 explicit integration routines
300
301
302 In some cases, a cyclic boundary condition exists. This is when the first
303 boxes in x-or y-direction interact with the last boxes. In this case, there
304 will be extra non-zero fringes in the Jacobian which need to be taken
305 into account. The occurrence of cyclic boundaries can be
306 toggled on by specifying argument \code{cyclicBnd}. For innstance,
307 \code{cyclicBnd = 1} indicates that a cyclic boundary is required only for
308 the x-direction, whereas \code{cyclicBnd = c(1,2)} imposes a cyclic boundary
309 for both x- and y-direction. The default is no cyclic boundaries.
310
311 If \code{lsodes} is used to integrate, it will probably be necessary
312 to specify the length of the real work array, \code{lrw}.
313
314 Although a reasonable guess of \code{lrw} is made, it is likely that
315 this will be too low. In this case, \code{ode.2D} will return with an
316 error message telling the size of the work array actually needed. In
317 the second try then, set \code{lrw} equal to this number.
318
319 For instance, if you get the error:
320
321 \preformatted{
322 DLSODES- RWORK length is insufficient to proceed.
323 Length needed is .ge. LENRW (=I1), exceeds LRW (=I2)
324 In above message, I1 = 27627 I2 = 25932
325 }
326 set \code{lrw} equal to 27627 or a higher value.
327
328 See \link{lsodes} for the additional options.
329
330 }
331 \seealso{
332 \itemize{
333 \item \code{\link{ode}} for a general interface to most of the ODE solvers,
334 \item \code{\link{ode.band}} for integrating models with a banded Jacobian
335 \item \code{\link{ode.1D}} for integrating 1-D models
336 \item \code{\link{ode.3D}} for integrating 3-D models
337 \item \code{\link{lsodes}} for the integration options.
338 }
339 \code{\link{diagnostics}} to print diagnostic messages.
340 }
341 \keyword{math}
342