This R Markdown (.Rmd) file creates an HTML webpage
containing executable code, plots, and short interpretations. In
RStudio, open the file and select Knit → Knit to HTML.
Install rmarkdown and knitr if needed:
install.packages(c("rmarkdown", "knitr"))
The simulations use base R and illustrative parameters. They are teaching examples, not fitted empirical models. Change parameters and initial conditions to explore alternative biological assumptions.
The exponential model assumes unlimited resources: \[ \frac{dN}{dt}=rN. \] The logistic model includes carrying capacity \(K\): \[ \frac{dN}{dt}=rN\left(1-\frac{N}{K}\right). \]
time <- seq(0, 40, by = 0.1)
N0 <- 20
r <- 0.18
K <- 500
N_exp <- N0 * exp(r * time)
N_log <- K / (1 + ((K - N0) / N0) * exp(-r * time))
matplot(time, cbind(N_exp, N_log), type = "l", lty = 1, lwd = 2,
xlab = "Time", ylab = "Population size",
main = "Exponential versus logistic growth")
legend("topleft", legend = c("Exponential", "Logistic"),
lty = 1, lwd = 2, col = 1:2, bty = "n")
abline(h = K, lty = 3)
Interpretation: Exponential growth continues without a resource limit. Logistic growth slows as the population approaches \(K\).
For constant harvest \(H\), \[ \frac{dN}{dt}=rN(1-N/K)-H. \] The code below uses Euler’s method for illustration.
simulate_harvest <- function(N0, r, K, H, tmax = 40, dt = 0.02) {
tt <- seq(0, tmax, by = dt)
N <- numeric(length(tt)); N[1] <- N0
for (i in 2:length(tt)) {
N[i] <- max(0, N[i-1] + dt * (r*N[i-1]*(1-N[i-1]/K) - H))
}
data.frame(time = tt, N = N, harvest = H)
}
harvest_levels <- c(0, 15, 22, 26)
harvest_results <- lapply(harvest_levels, function(h)
simulate_harvest(N0 = 300, r = 0.4, K = 500, H = h))
ylim <- range(unlist(lapply(harvest_results, `[[`, "N")))
plot(harvest_results[[1]]$time, harvest_results[[1]]$N, type = "l",
lwd = 2, ylim = ylim, xlab = "Time", ylab = "Population size",
main = "Logistic population under different harvest rates")
for (i in 2:length(harvest_results))
lines(harvest_results[[i]]$time, harvest_results[[i]]$N,
lwd = 2, lty = i)
legend("right", legend = paste("H =", harvest_levels),
lty = seq_along(harvest_levels), lwd = 2, bty = "n")
Exercise: Which harvest levels allow persistence in this simulation? Explain why the model’s maximum sustainable yield is \(rK/4\).
A strong Allee effect can be represented by \[ \frac{dN}{dt}=rN\left(1-\frac{N}{K}\right)\left(\frac{N}{A}-1\right), \] where \(A\) is a critical population threshold. Below \(A\), the population declines; above \(A\), it can grow toward \(K\).
allee_rhs <- function(N, r, K, A) r*N*(1-N/K)*(N/A-1)
simulate_allee <- function(N0, r = 0.5, K = 500, A = 80,
tmax = 60, dt = 0.02) {
tt <- seq(0, tmax, by = dt)
N <- numeric(length(tt)); N[1] <- N0
for (i in 2:length(tt)) {
N[i] <- max(0, N[i-1] + dt*allee_rhs(N[i-1], r, K, A))
}
data.frame(time = tt, N = N, initial = N0)
}
initial_sizes <- c(30, 70, 100, 180)
allee_runs <- lapply(initial_sizes, simulate_allee)
yrange <- range(unlist(lapply(allee_runs, `[[`, "N")))
plot(allee_runs[[1]]$time, allee_runs[[1]]$N, type = "l", lwd = 2,
ylim = yrange, xlab = "Time", ylab = "Population size",
main = "Strong Allee effect: different initial population sizes")
for (i in 2:length(allee_runs))
lines(allee_runs[[i]]$time, allee_runs[[i]]$N, lwd = 2, lty = i)
abline(h = 80, lty = 3)
legend("right", legend = paste("N(0) =", initial_sizes),
lty = seq_along(initial_sizes), lwd = 2, bty = "n")
Ngrid <- seq(0, 500, length.out = 500)
plot(Ngrid, allee_rhs(Ngrid, r = 0.5, K = 500, A = 80), type = "l",
lwd = 2, xlab = "N", ylab = "dN/dt",
main = "Per-capita population dynamics with a strong Allee effect")
abline(h = 0, lty = 2)
abline(v = c(80, 500), lty = 3)
Interpretation: The equilibrium at \(N=A\) separates initial conditions that decline from those that increase, while \(K\) is the positive carrying-capacity equilibrium.
For \(dN/dt=rN(1-N/K)\), equilibria are \(N^*=0\) and \(N^*=K\). When \(r>0\), zero is unstable and \(K\) is stable for positive initial populations.
r <- 0.3; K <- 400
Ngrid <- seq(0, 500, length.out = 500)
dN <- r*Ngrid*(1-Ngrid/K)
plot(Ngrid, dN, type = "l", lwd = 2,
xlab = "N", ylab = "dN/dt",
main = "Phase-line information from the logistic growth function")
abline(h = 0, lty = 2)
abline(v = c(0, K), lty = 3)
arrows(50, 10, 130, 10, length = 0.1)
arrows(480, -10, 420, -10, length = 0.1)
t <- seq(0, 35, by = 0.1)
initials <- c(20, 100, 250, 480)
curves <- sapply(initials, function(n0) K/(1 + ((K-n0)/n0)*exp(-r*t)))
matplot(t, curves, type = "l", lty = 1, lwd = 2,
xlab = "Time", ylab = "N(t)",
main = "Logistic trajectories from different initial conditions")
abline(h = K, lty = 3)
legend("right", legend = paste("N(0) =", initials),
lty = 1, lwd = 2, col = seq_along(initials), bty = "n")
Exercise: Repeat with \(r<0\). What happens to the equilibria and trajectories?
A linear autonomous system has the form \(\mathbf{x}'=A\mathbf{x}\). Eigenvalues of \(A\) help classify the equilibrium at the origin.
A <- matrix(c(0, 1, -2, -0.6), nrow = 2, byrow = TRUE)
eigen(A)
## eigen() decomposition
## $values
## [1] -0.3+1.382027i -0.3-1.382027i
##
## $vectors
## [,1] [,2]
## [1,] -0.1224745-0.5642104i -0.1224745+0.5642104i
## [2,] 0.8164966+0.0000000i 0.8164966+0.0000000i
The next chunk numerically approximates trajectories using a simple
Euler method. For better numerical accuracy in more demanding work, use
a dedicated ODE solver such as deSolve.
simulate_linear <- function(A, x0, tmax = 20, dt = 0.01) {
tt <- seq(0, tmax, by = dt)
X <- matrix(NA_real_, nrow = length(tt), ncol = length(x0))
X[1,] <- x0
for (i in 2:length(tt)) X[i,] <- X[i-1,] + dt*as.vector(A %*% X[i-1,])
data.frame(time = tt, x1 = X[,1], x2 = X[,2])
}
starts <- list(c(2, 0), c(0, 2), c(-2, 1), c(1, -2))
traj <- lapply(starts, function(x0) simulate_linear(A, x0))
plot(traj[[1]]$x1, traj[[1]]$x2, type = "l", lwd = 2,
xlim = range(unlist(lapply(traj, `[[`, "x1"))),
ylim = range(unlist(lapply(traj, `[[`, "x2"))),
xlab = "x1", ylab = "x2", main = "Phase portrait for x' = A x")
for (i in 2:length(traj)) lines(traj[[i]]$x1, traj[[i]]$x2, lwd = 2, lty = i)
points(0, 0, pch = 19)
Try: Change A to
matrix(c(-1,0,0,-2), 2, 2) and then to
matrix(c(0,1,-1,0), 2, 2). Compare the eigenvalues and
phase portraits.
The SIR model is \[ S'=-\beta SI/N,\quad I'=\beta SI/N-\gamma I,\quad R'=\gamma I. \] The basic reproduction number in this simple closed-population model is \(R_0=\beta/\gamma\).
sir_rhs <- function(t, state, pars) {
# Explicitly restore state-variable names
names(state) <- c("S", "I", "R")
S <- state["S"]
I <- state["I"]
R <- state["R"]
beta <- pars["beta"]
gamma <- pars["gamma"]
N <- S + I + R
incidence <- beta * S * I / N
dS <- -incidence
dI <- incidence - gamma * I
dR <- gamma * I
c(S = dS, I = dI, R = dR)
}
# Base R fourth-order Runge-Kutta integrator
rk4 <- function(rhs, y0, times, pars) {
n <- length(times)
p <- length(y0)
out <- matrix(
NA_real_,
nrow = n,
ncol = p,
dimnames = list(NULL, names(y0))
)
out[1, ] <- y0
for (i in 2:n) {
h <- times[i] - times[i - 1]
ti <- times[i - 1]
yi <- out[i - 1, ]
k1 <- rhs(ti, yi, pars)
k2 <- rhs(ti + h/2, yi + h*k1/2, pars)
k3 <- rhs(ti + h/2, yi + h*k2/2, pars)
k4 <- rhs(ti + h, yi + h*k3, pars)
out[i, ] <- yi + h*(k1 + 2*k2 + 2*k3 + k4)/6
}
result <- as.data.frame(out)
result$time <- times
result
}
# Parameters and initial conditions
times <- seq(0, 160, by = 0.1)
pars <- c(beta = 0.32, gamma = 0.1)
initial_state <- c(S = 990, I = 10, R = 0)
# Run simulation
sir <- rk4(sir_rhs, initial_state, times, pars)
# Basic reproduction number
sir$R0 <- unname(pars["beta"] / pars["gamma"])
# Plot SIR trajectories
matplot(
sir$time,
sir[, c("S", "I", "R")],
type = "l",
lwd = 2,
lty = 1,
col = 1:3,
xlab = "Time",
ylab = "Number of people",
main = "SIR epidemic simulation"
)
legend(
"right",
legend = c("Susceptible", "Infectious", "Removed"),
col = 1:3,
lty = 1,
lwd = 2,
bty = "n"
)
# Peak number of infectious individuals
peak_infectious <- max(sir$I)
peak_time <- sir$time[which.max(sir$I)]
cat("Basic reproduction number:", sir$R0[1], "\n")
## Basic reproduction number: 3.2
cat("Peak infectious individuals:", round(peak_infectious, 2), "\n")
## Peak infectious individuals: 327.15
cat("Time of peak infection:", round(peak_time, 1), "days\n")
## Time of peak infection: 24.7 days
# Check population conservation
cat("Initial population:", sum(initial_state), "\n")
## Initial population: 1000
cat("Final population:", sum(sir[nrow(sir), c("S", "I", "R")]), "\n")
## Final population: 1000
# Inspect output
head(sir)
In an SIS model, recovered individuals return to susceptibility.
sis_rhs <- function(t, state, pars) {
# Restore state names
names(state) <- c("S", "I")
S <- state["S"]
I <- state["I"]
beta <- pars["beta"]
gamma <- pars["gamma"]
N <- S + I
incidence <- beta * S * I / N
dS <- -incidence + gamma * I
dI <- incidence - gamma * I
# Return a numeric vector, NOT a list
c(S = dS, I = dI)
}
# Simulation times
times <- seq(0, 160, by = 0.1)
# Parameters
pars_sis <- c(beta = 0.25, gamma = 0.1)
# Initial conditions
initial_sis <- c(S = 990, I = 10)
# Run simulation using the corrected RK4 function
sis <- rk4(
sis_rhs,
initial_sis,
times,
pars_sis
)
# Plot results
matplot(
sis$time,
sis[, c("S", "I")],
type = "l",
lwd = 2,
lty = 1,
col = 1:2,
xlab = "Time",
ylab = "Number of people",
main = "SIS Model"
)
legend(
"right",
legend = c("Susceptible", "Infectious"),
col = 1:2,
lty = 1,
lwd = 2,
bty = "n"
)
# Calculate the endemic equilibrium
N <- sum(initial_sis)
R0_SIS <- pars_sis["beta"] / pars_sis["gamma"]
if (R0_SIS > 1) {
I_star <- N * (1 - 1 / R0_SIS)
S_star <- N / R0_SIS
cat("Basic reproduction number:", R0_SIS, "\n")
cat("Endemic susceptible equilibrium:", S_star, "\n")
cat("Endemic infectious equilibrium:", I_star, "\n")
}
## Basic reproduction number: 2.5
## Endemic susceptible equilibrium: 400
## Endemic infectious equilibrium: 600
# Check conservation of population
cat("Initial population:", sum(initial_sis), "\n")
## Initial population: 1000
cat("Final population:",
sum(sis[nrow(sis), c("S", "I")]), "\n")
## Final population: 1000
The SEIR model adds an exposed (latent, not yet infectious) compartment.
seir_rhs <- function(t, state, pars) {
# Restore state names
names(state) <- c("S", "E", "I", "R")
S <- state["S"]
E <- state["E"]
I <- state["I"]
R <- state["R"]
beta <- pars["beta"]
sigma <- pars["sigma"]
gamma <- pars["gamma"]
N <- S + E + I + R
incidence <- beta * S * I / N
dS <- -incidence
dE <- incidence - sigma * E
dI <- sigma * E - gamma * I
dR <- gamma * I
# Return a numeric vector, not a list
c(S = dS, E = dE, I = dI, R = dR)
}
# Simulation times
times <- seq(0, 160, by = 0.1)
# Initial population
initial_seir <- c(S = 990, E = 0, I = 10, R = 0)
# Model parameters
pars_seir <- c(beta = 0.35, sigma = 0.2, gamma = 0.1)
# Run the simulation using the corrected RK4 function
seir <- rk4(
seir_rhs,
initial_seir,
times,
pars_seir
)
# Plot the SEIR trajectories
matplot(
seir$time,
seir[, c("S", "E", "I", "R")],
type = "l",
lwd = 2,
lty = 1,
col = 1:4,
xlab = "Time",
ylab = "Number of people",
main = "SEIR Epidemic Simulation"
)
legend(
"right",
legend = c("Susceptible", "Exposed", "Infectious", "Removed"),
col = 1:4,
lty = 1,
lwd = 2,
bty = "n"
)
# Basic reproduction number
R0 <- pars_seir["beta"] / pars_seir["gamma"]
cat("Basic reproduction number:", R0, "\n")
## Basic reproduction number: 3.5
# Peak infectious population
peak_I <- max(seir$I)
peak_time <- seir$time[which.max(seir$I)]
cat("Peak infectious population:", round(peak_I, 2), "\n")
## Peak infectious population: 233.34
cat("Time of peak infection:", round(peak_time, 1), "days\n")
## Time of peak infection: 44.8 days
# Check population conservation
cat("Initial population:", sum(initial_seir), "\n")
## Initial population: 1000
cat("Final population:",
sum(seir[nrow(seir), c("S", "E", "I", "R")]), "\n")
## Final population: 1000
This simplified illustration assumes a one-time vaccination of a fraction of susceptible people at time zero, and a reduction in the transmission rate. It is not a full vaccination programme model.
times2 <- seq(0, 120, by = 0.1)
baseline <- rk4(sir_rhs, c(S = 990, I = 10, R = 0), times2,
pars = c(beta = 0.32, gamma = 0.1))
# Vaccinate 40% of initial susceptible people and reduce beta by 30%.
vaccinated_initial <- c(S = 594, I = 10, R = 396)
intervention <- rk4(sir_rhs, vaccinated_initial, times2,
pars = c(beta = 0.224, gamma = 0.1))
plot(times2, baseline$I, type = "l", lwd = 2, xlab = "Time",
ylab = "Infectious people", main = "Illustrative intervention comparison")
lines(times2, intervention$I, lwd = 2, lty = 2)
legend("topright", legend = c("Baseline", "Vaccination + lower transmission"),
lty = c(1,2), lwd = 2, bty = "n")
c(baseline_peak = max(baseline$I), intervention_peak = max(intervention$I))
## baseline_peak intervention_peak
## 327.15191 30.07145
Interpretation: Compare peak prevalence and timing. In this simple model, vaccination reduces the susceptible pool and lower transmission reduces the force of infection. Real evaluations should incorporate vaccine effectiveness, coverage, waning, age structure, contact patterns, and uncertainty as appropriate.
For a system \(\mathbf{x}'=\mathbf{f}(\mathbf{x})\), local stability near an equilibrium is studied using the Jacobian matrix \(J\). Eigenvalues with negative real parts indicate local asymptotic stability; any positive real part indicates instability, subject to the usual caveats when eigenvalues have zero real parts.
Here is a simple two-variable system with a stable equilibrium: \[ x'=1-x,\qquad y'=2x-y. \]
J <- matrix(c(-1, 0, 2, -1), nrow = 2, byrow = TRUE)
cat("Jacobian at equilibrium:\n")
## Jacobian at equilibrium:
print(J)
## [,1] [,2]
## [1,] -1 0
## [2,] 2 -1
cat("Eigenvalues:\n")
## Eigenvalues:
print(eigen(J)$values)
## [1] -1 -1
# Linear system of differential equations
linear_rhs2 <- function(t, state, pars) {
x <- state["x"]
y <- state["y"]
dx <- 1 - x
dy <- 2*x - y
# Return a named numeric vector
c(x = dx, y = dy)
}
# Time sequence
times3 <- seq(0, 10, by = 0.05)
# Initial conditions: x(0) = 0, y(0) = 4
sol <- rk4(
linear_rhs2,
c(x = 0, y = 4),
times3,
pars = c()
)
# Plot trajectories
matplot(
sol$time,
sol[, c("x", "y")],
type = "l",
lwd = 2,
col = 1:2,
xlab = "Time",
ylab = "State",
main = "Convergence to equilibrium (1, 2)"
)
abline(h = c(1, 2), lty = 3, col = 1:2)
legend(
"right",
legend = c("x(t)", "y(t)"),
col = 1:2,
lty = 1,
lwd = 2,
bty = "n"
)
Exercise: Find the equilibrium by setting both derivatives to zero. Verify it agrees with the limiting values in the graph.
A simple predator–prey system is \[ X'=aX-bXY,\qquad Y'=dbXY-cY, \] where \(X\) is prey and \(Y\) is predator.
# Lotka-Volterra predator-prey model
predprey_rhs <- function(t, state, pars) {
names(state) <- c("X", "Y")
X <- state["X"] # Prey population
Y <- state["Y"] # Predator population
a <- pars["a"]
b <- pars["b"]
c <- pars["c"]
d <- pars["d"]
dX <- a * X - b * X * Y
dY <- d * b * X * Y - c * Y
# Return a named numeric vector, not a list
c(X = dX, Y = dY)
}
# Simulation times
pp_times <- seq(0, 80, by = 0.05)
# Parameters
pp_pars <- c(a = 0.6, b = 0.03, c = 0.4, d = 0.02)
# Initial populations
pp_initial <- c(X = 40, Y = 9)
# Run the simulation
pp <- rk4(
predprey_rhs,
pp_initial,
pp_times,
pp_pars
)
# Plot population trajectories
matplot(
pp$time,
pp[, c("X", "Y")],
type = "l",
lwd = 2,
lty = 1,
col = 1:2,
xlab = "Time",
ylab = "Population",
main = "Predator-prey oscillations"
)
legend(
"topright",
legend = c("Prey", "Predator"),
col = 1:2,
lty = 1,
lwd = 2,
bty = "n"
)
# Phase portrait
plot(
pp$X,
pp$Y,
type = "l",
lwd = 2,
xlab = "Prey X",
ylab = "Predator Y",
main = "Predator-prey phase portrait"
)
# Theoretical coexistence equilibrium
X_star <- pp_pars["c"] / (pp_pars["d"] * pp_pars["b"])
Y_star <- pp_pars["a"] / pp_pars["b"]
cat("Coexistence equilibrium:\n")
## Coexistence equilibrium:
cat("Prey X* =", X_star, "\n")
## Prey X* = 666.6667
cat("Predator Y* =", Y_star, "\n")
## Predator Y* = 20
# Check for numerical issues
cat("Minimum prey population:", min(pp$X), "\n")
## Minimum prey population: 27.02202
cat("Minimum predator population:", min(pp$Y), "\n")
## Minimum predator population: 1.800985
Interpretation: In the classical model, predator and prey populations can oscillate. The model assumes constant parameters and no density dependence, so it is a starting point rather than a complete ecological description.
A two-species Lotka–Volterra competition model is \[ X'=r_1X\left(1-\frac{X+\alpha Y}{K_1}\right),\quad Y'=r_2Y\left(1-\frac{Y+\beta X}{K_2}\right). \]
# Two-species Lotka-Volterra competition model
competition_rhs <- function(t, state, pars) {
names(state) <- c("X", "Y")
X <- state["X"]
Y <- state["Y"]
r1 <- pars["r1"]
r2 <- pars["r2"]
K1 <- pars["K1"]
K2 <- pars["K2"]
alpha <- pars["alpha"]
beta <- pars["beta"]
dX <- r1 * X * (1 - (X + alpha * Y) / K1)
dY <- r2 * Y * (1 - (Y + beta * X) / K2)
# Return a named numeric vector, not a list
c(X = dX, Y = dY)
}
# Simulation times
comp_times <- seq(0, 100, by = 0.05)
# Model parameters
comp_pars <- c(
r1 = 0.2, r2 = 0.18,
K1 = 100, K2 = 90,
alpha = 0.7, beta = 0.6
)
# Initial populations
comp_initial <- c(X = 20, Y = 15)
# Run simulation using your corrected RK4 function
comp <- rk4(
competition_rhs,
comp_initial,
comp_times,
comp_pars
)
# Plot population trajectories
matplot(
comp$time,
comp[, c("X", "Y")],
type = "l",
lwd = 2,
lty = 1,
col = 1:2,
xlab = "Time",
ylab = "Population size",
main = "Two competing species"
)
legend(
"right",
legend = c("Species X", "Species Y"),
col = 1:2,
lty = 1,
lwd = 2,
bty = "n"
)
# Phase trajectory
plot(
comp$X,
comp$Y,
type = "l",
lwd = 2,
xlab = "Species X",
ylab = "Species Y",
main = "Competition phase trajectory"
)
# Check final populations
cat("Final population of species X:",
round(tail(comp$X, 1), 2), "\n")
## Final population of species X: 63.95
cat("Final population of species Y:",
round(tail(comp$Y, 1), 2), "\n")
## Final population of species Y: 51.57
Exercise: Increase alpha and
beta. Describe how stronger interspecific competition
changes the trajectories. Test multiple initial conditions to explore
whether the final outcome depends on starting densities.