Debian Codegraph @

man/ode.1D.Rd

raw
1 \name{ode.1D}
2 \alias{ode.1D}
3 \title{Solver For Multicomponent 1-D Ordinary Differential Equations}
4 \description{
5 Solves a system of ordinary differential equations
6 resulting from 1-Dimensional partial differential equations
7 that have been converted to ODEs by numerical differencing.
8 }
9 \usage{ode.1D(y, times, func, parms, nspec = NULL, dimens = NULL,
10 method= c("lsoda", "lsode", "lsodes", "lsodar", "vode", "daspk",
11 "euler", "rk4", "ode23", "ode45", "radau", "bdf", "adams", "impAdams",
12 "iteration"),
13 names = NULL, bandwidth = 1, restructure = FALSE, ...)
14 }
15 \arguments{
16 \item{y }{the initial (state) values for the ODE system, a vector. If
17 \code{y} has a name attribute, the names will be used to label the
18 output matrix.
19 }
20 \item{times }{time sequence for which output is wanted; the first
21 value of \code{times} must be the initial time.
22 }
23 \item{func }{either an \R-function that computes the values of the
24 derivatives in the ODE system (the model definition) at time
25 \code{t}, or a character string giving the name of a compiled
26 function in a dynamically loaded shared library.
27
28 If \code{func} is an \R-function, it must be defined as:
29 \code{func <- function(t, y, parms, ...)}. \code{t} is the current time
30 point in the integration, \code{y} is the current estimate of the
31 variables in the ODE system. If the initial values \code{y} has a
32 \code{names} attribute, the names will be available inside \code{func}.
33 \code{parms} is a vector or list of parameters; \code{...} (optional) are
34 any other arguments passed to the function.
35
36 The return value of \code{func} should be a list, whose first
37 element is a vector containing the derivatives of \code{y} with
38 respect to \code{time}, and whose next elements are global values
39 that are required at each point in \code{times}. The derivatives
40 must be specified in the \bold{same order} as the state variables \code{y}.
41
42 If \code{func} is a character string then integrator \code{lsodes}
43 will be used. See details.
44 }
45 \item{parms }{parameters passed to \code{func}.}
46 \item{nspec }{the number of \bold{species} (components) in the model. If
47 \code{NULL}, then \code{dimens} should be specified.
48 }
49 \item{dimens}{the number of \bold{boxes} in the model. If \code{NULL}, then
50 \code{nspec} should be specified.
51 }
52 \item{method }{the integrator. Use \code{"vode", "lsode", "lsoda",
53 "lsodar", "daspk"}, or \code{"lsodes"} if the model is very stiff;
54 \code{"impAdams"} or \code{"radau"} may be best suited for mildly stiff problems;
55 \code{"euler", "rk4", "ode23", "ode45", "adams"} are most
56 efficient for non-stiff problems. Also allowed is to pass an integrator
57 \code{function}. Use one of the other Runge-Kutta methods via
58 \code{rkMethod}. For instance, \code{method = rkMethod("ode45ck")} will
59 trigger the Cash-Karp method of order 4(5).
60
61 Method \code{"iteration"} is special in that here the function \code{func} should
62 return the new value of the state variables rather than the rate of change.
63 This can be used for individual based models, for difference equations,
64 or in those cases where the integration is performed within \code{func})
65
66 }
67 \item{names }{the names of the components; used for plotting.
68 }
69 \item{bandwidth }{the number of adjacent boxes over which transport occurs.
70 Normally equal to 1 (box i only interacts with box i-1, and i+1).
71 Values larger than 1 will not work with \code{method = "lsodes"}.
72 Ignored if the method is explicit.
73 }
74 \item{restructure }{whether or not the Jacobian should be restructured.
75 Only used if the \code{method} is an integrator function. Should be
76 \code{TRUE} if the method is implicit, \code{FALSE} if explicit.
77 }
78 \item{... }{additional arguments passed to the integrator.}
79 }
80 \value{
81
82 A matrix of class \code{deSolve} with up to as many rows as elements in times and as many
83 columns as elements in \code{y} plus the number of "global" values
84 returned in the second element of the return from \code{func}, plus an
85 additional column (the first) for the time value. There will be one
86 row for each element in \code{times} unless the integrator returns
87 with an unrecoverable error. If \code{y} has a names attribute, it
88 will be used to label the columns of the output value.
89
90 The output will have the attributes \code{istate}, and \code{rstate},
91 two vectors with several useful elements. The first element of istate
92 returns the conditions under which the last call to the integrator
93 returned. Normal is \code{istate = 2}. If \code{verbose = TRUE}, the
94 settings of istate and rstate will be written to the screen. See the
95 help for the selected integrator for details.
96
97 }
98 \note{
99 It is advisable though not mandatory to specify \bold{both}
100 \code{nspec} and \code{dimens}. In this case, the solver can check
101 whether the input makes sense (i.e. if \code{nspec * dimens ==
102 length(y)}).
103 }
104
105 \author{Karline Soetaert <[email protected]>}
106 \examples{
107
108 ## =======================================================================
109 ## example 1
110 ## a predator and its prey diffusing on a flat surface
111 ## in concentric circles
112 ## 1-D model with using cylindrical coordinates
113 ## Lotka-Volterra type biology
114 ## =======================================================================
115
116 ## ================
117 ## Model equations
118 ## ================
119
120 lvmod <- function (time, state, parms, N, rr, ri, dr, dri) {
121 with (as.list(parms), {
122 PREY <- state[1:N]
123 PRED <- state[(N+1):(2*N)]
124
125 ## Fluxes due to diffusion
126 ## at internal and external boundaries: zero gradient
127 FluxPrey <- -Da * diff(c(PREY[1], PREY, PREY[N]))/dri
128 FluxPred <- -Da * diff(c(PRED[1], PRED, PRED[N]))/dri
129
130 ## Biology: Lotka-Volterra model
131 Ingestion <- rIng * PREY * PRED
132 GrowthPrey <- rGrow * PREY * (1-PREY/cap)
133 MortPredator <- rMort * PRED
134
135 ## Rate of change = Flux gradient + Biology
136 dPREY <- -diff(ri * FluxPrey)/rr/dr +
137 GrowthPrey - Ingestion
138 dPRED <- -diff(ri * FluxPred)/rr/dr +
139 Ingestion * assEff - MortPredator
140
141 return (list(c(dPREY, dPRED)))
142 })
143 }
144
145 ## ==================
146 ## Model application
147 ## ==================
148
149 ## model parameters:
150
151 R <- 20 # total radius of surface, m
152 N <- 100 # 100 concentric circles
153 dr <- R/N # thickness of each layer
154 r <- seq(dr/2,by = dr,len = N) # distance of center to mid-layer
155 ri <- seq(0,by = dr,len = N+1) # distance to layer interface
156 dri <- dr # dispersion distances
157
158 parms <- c(Da = 0.05, # m2/d, dispersion coefficient
159 rIng = 0.2, # /day, rate of ingestion
160 rGrow = 1.0, # /day, growth rate of prey
161 rMort = 0.2 , # /day, mortality rate of pred
162 assEff = 0.5, # -, assimilation efficiency
163 cap = 10) # density, carrying capacity
164
165 ## Initial conditions: both present in central circle (box 1) only
166 state <- rep(0, 2 * N)
167 state[1] <- state[N + 1] <- 10
168
169 ## RUNNING the model:
170 times <- seq(0, 200, by = 1) # output wanted at these time intervals
171
172 ## the model is solved by the two implemented methods:
173 ## 1. Default: banded reformulation
174 print(system.time(
175 out <- ode.1D(y = state, times = times, func = lvmod, parms = parms,
176 nspec = 2, names = c("PREY", "PRED"),
177 N = N, rr = r, ri = ri, dr = dr, dri = dri)
178 ))
179
180 ## 2. Using sparse method
181 print(system.time(
182 out2 <- ode.1D(y = state, times = times, func = lvmod, parms = parms,
183 nspec = 2, names = c("PREY","PRED"),
184 N = N, rr = r, ri = ri, dr = dr, dri = dri,
185 method = "lsodes")
186 ))
187
188 ## ================
189 ## Plotting output
190 ## ================
191 # the data in 'out' consist of: 1st col times, 2-N+1: the prey
192 # N+2:2*N+1: predators
193
194 PREY <- out[, 2:(N + 1)]
195
196 filled.contour(x = times, y = r, PREY, color = topo.colors,
197 xlab = "time, days", ylab = "Distance, m",
198 main = "Prey density")
199 # similar:
200 image(out, which = "PREY", grid = r, xlab = "time, days",
201 legend = TRUE, ylab = "Distance, m", main = "Prey density")
202
203 image(out2, grid = r)
204
205 # summaries of 1-D variables
206 summary(out)
207
208 # 1-D plots:
209 matplot.1D(out, type = "l", subset = time == 10)
210 matplot.1D(out, type = "l", subset = time > 10 & time < 20)
211
212 ## =======================================================================
213 ## Example 2.
214 ## Biochemical Oxygen Demand (BOD) and oxygen (O2) dynamics
215 ## in a river
216 ## =======================================================================
217
218 ## ================
219 ## Model equations
220 ## ================
221 O2BOD <- function(t, state, pars) {
222 BOD <- state[1:N]
223 O2 <- state[(N+1):(2*N)]
224
225 ## BOD dynamics
226 FluxBOD <- v * c(BOD_0, BOD) # fluxes due to water transport
227 FluxO2 <- v * c(O2_0, O2)
228
229 BODrate <- r * BOD # 1-st order consumption
230
231 ## rate of change = flux gradient - consumption + reaeration (O2)
232 dBOD <- -diff(FluxBOD)/dx - BODrate
233 dO2 <- -diff(FluxO2)/dx - BODrate + p * (O2sat-O2)
234
235 return(list(c(dBOD = dBOD, dO2 = dO2)))
236 }
237
238
239 ## ==================
240 ## Model application
241 ## ==================
242 ## parameters
243 dx <- 25 # grid size of 25 meters
244 v <- 1e3 # velocity, m/day
245 x <- seq(dx/2, 5000, by = dx) # m, distance from river
246 N <- length(x)
247 r <- 0.05 # /day, first-order decay of BOD
248 p <- 0.5 # /day, air-sea exchange rate
249 O2sat <- 300 # mmol/m3 saturated oxygen conc
250 O2_0 <- 200 # mmol/m3 riverine oxygen conc
251 BOD_0 <- 1000 # mmol/m3 riverine BOD concentration
252
253 ## initial conditions:
254 state <- c(rep(200, N), rep(200, N))
255 times <- seq(0, 20, by = 0.1)
256
257 ## running the model
258 ## step 1 : model spinup
259 out <- ode.1D(y = state, times, O2BOD, parms = NULL,
260 nspec = 2, names = c("BOD", "O2"))
261
262 ## ================
263 ## Plotting output
264 ## ================
265 ## select oxygen (first column of out:time, then BOD, then O2
266 O2 <- out[, (N + 2):(2 * N + 1)]
267 color = topo.colors
268
269 filled.contour(x = times, y = x, O2, color = color, nlevels = 50,
270 xlab = "time, days", ylab = "Distance from river, m",
271 main = "Oxygen")
272
273 ## or quicker plotting:
274 image(out, grid = x, xlab = "time, days", ylab = "Distance from river, m")
275 }
276 \details{
277
278 This is the method of choice for multi-species 1-dimensional models,
279 that are only subjected to transport between adjacent layers.
280
281 More specifically, this method is to be used if the state variables
282 are arranged per species:
283
284 A[1], A[2], A[3],.... B[1], B[2], B[3],.... (for species A, B))
285
286 Two methods are implemented.
287 \itemize{
288 \item The default method rearranges the state variables as
289 A[1], B[1], ... A[2], B[2], ... A[3], B[3], .... This reformulation leads
290 to a banded Jacobian with (upper and lower) half bandwidth =
291 number of species.
292
293 Then the selected integrator solves the banded problem.
294
295 \item The second method uses \code{lsodes}. Based on the dimension
296 of the problem, the method first calculates the sparsity pattern
297 of the Jacobian, under the assumption that transport is only
298 occurring between adjacent layers. Then \code{lsodes} is called to
299 solve the problem.
300
301 As \code{lsodes} is used to integrate, it may be necessary to
302 specify the length of the real work array, \code{lrw}.
303
304 Although a reasonable guess of \code{lrw} is made, it is possible
305 that this will be too low. In this case, \code{ode.1D} will
306 return with an error message telling the size of the work array
307 actually needed. In the second try then, set \code{lrw} equal to
308 this number.
309
310 For instance, if you get the error:
311 \preformatted{
312 DLSODES- RWORK length is insufficient to proceed.
313 Length needed is .ge. LENRW (=I1), exceeds LRW (=I2)
314 In above message, I1 = 27627 I2 = 25932
315 }
316 set \code{lrw} equal to 27627 or a higher value
317
318 }
319 If the model is specified in compiled code (in a DLL), then option 2,
320 based on \code{lsodes} is the only solution method.
321
322 For single-species 1-D models, you may also use \code{\link{ode.band}}.
323
324 See the selected integrator for the additional options.
325 }
326 \seealso{
327 \itemize{
328 \item \code{\link{ode}} for a general interface to most of the ODE solvers,
329 \item \code{\link{ode.band}} for integrating models with a banded Jacobian
330 \item \code{\link{ode.2D}} for integrating 2-D models
331 \item \code{\link{ode.3D}} for integrating 3-D models
332 \item \code{\link{lsodes}},\code{\link{lsode}}, \code{\link{lsoda}},
333 \code{\link{lsodar}},\code{\link{vode}} for the integration options.
334 }
335 \code{\link{diagnostics}} to print diagnostic messages.
336 }
337 \keyword{math}
338