#########################################
## Example: Lotka-volterra model
#########################################
## Note:
## parameters are a list, names accessible via "with" statement
## (see also ode and lsoda examples)
lvmodel <- function(t, x, parms) {
S <- x[1] # substrate
P <- x[2] # producer
K <- x[3] # consumer
with(parms,{
import <- approx(signal$times, signal$import, t)$y
dS <- import - b * S * P + g * K
dP <- c * S * P - d * K * P
dK <- e * P * K - f * K
res<-c(dS, dP, dK)
list(res)
})
}
## vector of timesteps
times <- seq(0, 100, length=101)
## external signal with rectangle impulse
signal <- as.data.frame(list(times = times,
import = rep(0,length(times))))
signal$import[signal$times >= 10 & signal$times <=11] <- 0.2
## Parameters for steady state conditions
parms <- list(b=0.0, c=0.1, d=0.1, e=0.1, f=0.1, g=0.0)
## Start values for steady state
y <-xstart <- c(S=1, P=1, K=1)
## Euler method
out1 <- as.data.frame(rk(xstart, times, lvmodel, parms,
hini = 0.1, method="euler"))
## classical Runge-Kutta 4th order
out2 <- as.data.frame(rk(xstart, times, lvmodel, parms,
hini = 1, method="rk4"))
## Dormand-Prince method of order 5(4)
out3 <- as.data.frame(rk(xstart, times, lvmodel, parms,
hmax=1, method = "rk45dp7"))
mf <- par(mfrow=c(2,2))
plot (out1$time, out1$S, type="l", ylab="Substrate")
lines(out2$time, out2$S, col="red", lty="dotted", lwd=2)
lines(out3$time, out3$S, col="green", lty="dotted")
plot (out1$time, out1$P, type="l", ylab="Producer")
lines(out2$time, out2$P, col="red", lty="dotted")
lines(out3$time, out3$P, col="green", lty="dotted")
plot (out1$time, out1$K, type="l", ylab="Consumer")
lines(out2$time, out2$K, col="red", lty="dotted", lwd=2)
lines(out3$time, out3$K, col="green", lty="dotted")
plot (out1$P, out1$K, type="l", xlab="Producer",ylab="Consumer")
lines(out2$P, out2$K, col="red", lty="dotted", lwd=2)
lines(out3$P, out3$K, col="green", lty="dotted")
legend("center",legend=c("euler","rk4","rk45dp7"),lty=c(1,3,3),
lwd=c(1,2,1),col=c("black","red","green"))
par(mfrow=mf)
Run the code above in your browser using DataLab