# Individual-based SARS-CoV-2 transmission model, practical 1
library(ggplot2)
## Model parameters
<- 0.5 # Transmission parameter
beta <- 1 / 2.5 # Rate of transitioning out of latent state
delta <- 1 / 5 # Rate of transitioning out of infectious state
gamma <- 1 / 180 # Rate of waning immunity
omega
<- 1 # Time step of simulation (1 day)
dt <- 365 # Duration of simulation (365 days)
days <- days / dt # Total number of time steps
steps <- 1000 # Population size
n
## Data frame to store simulation results
<- data.frame(ts = 1:steps, S = 0, E = 0, I = 0, R = 0)
results
## Initialize simulation
# Set the seed for the pseudorandom number generator, for reproducibility
set.seed(12345)
# Since this is an individual-based model, we track the properties of all n
# individuals in the simulation. One kind of property we can track is a state,
# such as S (susceptible), E (exposed), I (infectious), or R (recovered). We
# will store each individual's state as a string, either "S", "E", "I", or "R".
<- rep("S", n) # Each individual's state: start with all susceptible
state 1:10] <- "E" # Start 10 individuals in the "exposed" state
state[
## Run simulation
# We'll use the built-in function txtProgressBar to track the simulation's
# progress. Really helps for planning coffee breaks! It needs to know the
# minimum and maximum values to expect, and style = 3 tells it to report the
# percentage complete.
<- txtProgressBar(min = 1, max = steps, style = 3)
bar
# Loop over each time step . . .
for (ts in 1:steps) {
# Calculate the force of infection
<- beta * sum(state == "I") / n
lambda
# Loop through each individual . . .
for (i in 1:n) {
if (state[i] == "S") {
# Transition S -> E (infection) at rate lambda
if (runif(1) < 1 - exp(-lambda * dt)) {
<- "E"
state[i]
}else if (state[i] == "E") {
} # Transition E -> I (latent to infectious) at rate delta
if (runif(1) < 1 - exp(-delta * dt)) {
<- "I"
state[i]
}else if (state[i] == "I") {
} # Transition I -> R (infectious to recovered) at rate gamma
if (runif(1) < 1 - exp(-gamma * dt)) {
<- "R"
state[i]
}else if (state[i] == "R") {
} # Transition R -> S (waning of immunity) at rate omega
if (runif(1) < 1 - exp(-omega * dt)) {
<- "S"
state[i]
}
}
}
# Save population state for this time step
"S"] <- sum(state == "S")
results[ts, "E"] <- sum(state == "E")
results[ts, "I"] <- sum(state == "I")
results[ts, "R"] <- sum(state == "R")
results[ts,
# Update progress bar; close progress bar if we are finished
setTxtProgressBar(bar, ts)
if (ts == steps) {
close(bar)
}
}
## Plot simulation results
ggplot(results) +
geom_line(aes(x = ts, y = S, colour = "S")) +
geom_line(aes(x = ts, y = E, colour = "E")) +
geom_line(aes(x = ts, y = I, colour = "I")) +
geom_line(aes(x = ts, y = R, colour = "R"))
08. Stochastic individual-based models (solutions)
Practical 1. An individual-based SEIR model of SARS-CoV-2 transmission
Practical 2. Adding more complex dynamics to the model
# Individual-based SARS-CoV-2 transmission model, practical 2
library(ggplot2)
## Model parameters
<- 0.5 # Transmission parameter
beta <- 1e-5 # Importation rate
iota <- 0.05 # Rate of antibody waning
wane
<- 1 # Time step of simulation (1 day)
dt <- 365 * 2 # Duration of simulation (2 years)
days <- days / dt # Total number of time steps
steps <- 1000 # Population size
n
## Some helper functions
# Calculates infectiousness as a function of state and age: zero if state is
# not "I"; nonzero if state is "I", and slightly decreasing with age
<- function(state, age) {
infectiousness ifelse(state == "I", 1.25 - age / 160, 0)
}
# Calculates susceptibility of individuals with antibody level(s) ab
<- function(ab) {
susceptibility pnorm(ab, 5, 1, lower.tail = FALSE)
}
# Generates n random delays from the latent-period distribution
# (approximately 2 days, on average)
<- function(n) {
latent_delay rlnorm(n, meanlog = 0.5, sdlog = 0.6)
}
# Generates n random delays from the infectious-period distribution
# (approximately 5 days, on average)
<- function(n) {
infectious_delay rlnorm(n, meanlog = 1.5, sdlog = 0.5)
}
# Generates n random increments to antibody levels following recovery
<- function(n) {
ab_increment rnorm(n, mean = 12, sd = 2)
}
## Data frame to store simulation results
<- data.frame(ts = 1:steps, S = 0, E = 0, I = 0, AMeanU = 0, AMeanV = 0)
results
## Initialize simulation
# Set the seed for the pseudorandom number generator, for reproducibility
set.seed(12345)
# Initialize state variables
<- rep("S", n) # Each individual's state: start with all susceptible
state <- runif(n, 0, 80) # Each individual's age: random distribution from 0 to 80
age <- rep(0, n) # Delay for latent and infectious periods
delay <- rep(0, n) # Antibody concentration for each individual
antib <- rep(FALSE, n) # Vaccinated status
vacc
1:10] <- "E" # Start 10 individuals in the "exposed" state
state[
## Run simulation
# Initialize progress bar
<- txtProgressBar(min = 1, max = steps, style = 3)
bar
# Loop over each time step . . .
for (ts in 1:steps) {
# Calculate the force of infection
<- beta * sum(infectiousness(state, age)) / n + iota
lambda
# Loop through each individual . . .
for (i in 1:n) {
# Update individual i's non-state variables
# Time remaining in latent/infectious periods
<- delay[i] - dt
delay[i] # Antibody waning
<- antib[i] - wane * dt
antib[i] # Vaccination at time step 300 for over-40s
if ((ts == 300) && (age[i] >= 40)) {
<- TRUE
vacc[i] <- antib[i] + 2 * ab_increment(1)
antib[i]
}
# Update individual i's state
if (state[i] == "S") {
# Transition S -> E (infection) at rate lambda
if (runif(1) < 1 - exp(-lambda * dt)) {
if (runif(1) < susceptibility(antib[i])) {
<- "E"
state[i] <- latent_delay(1)
delay[i]
}
}else if (state[i] == "E") {
} # Transition E -> I (latent to infectious)
if (delay[i] < 0) {
<- "I"
state[i] <- infectious_delay(1)
delay[i]
}else if (state[i] == "I") {
} # Transition I -> S (infectious to susceptible)
if (delay[i] < 0) {
<- "S"
state[i] <- antib[i] + ab_increment(1)
antib[i]
}
}
}
# Save population state for this time step
"S"] <- sum(state == "S")
results[ts, "E"] <- sum(state == "E")
results[ts, "I"] <- sum(state == "I")
results[ts, "AMeanU"] <- mean(antib[!vacc])
results[ts, "AMeanV"] <- mean(antib[vacc])
results[ts,
# Update progress bar; close progress bar if we are finished
setTxtProgressBar(bar, ts)
if (ts == steps) {
close(bar)
}
}
## Plot simulation results
ggplot(results) +
geom_line(aes(x = ts, y = S, colour = "S")) +
geom_line(aes(x = ts, y = E, colour = "E")) +
geom_line(aes(x = ts, y = I, colour = "I"))
ggplot(results) +
geom_line(aes(x = ts, y = AMeanU, colour = "Unvaccinated")) +
geom_line(aes(x = ts, y = AMeanV, colour = "Vaccinated")) +
labs(x = "Time step", y = "Mean antibody level")
Practical 3. Optimizing the model to run faster
# Individual-based SARS-CoV-2 transmission model, practical 3
library(ggplot2)
## Model parameters
<- 0.5 # Transmission parameter
beta <- 1e-5 # Importation rate
iota <- 0.05 # Rate of antibody waning
wane
<- 1 # Time step of simulation (1 day)
dt <- 365 * 4 # Duration of simulation (4 years)
days <- days / dt # Total number of time steps
steps <- 5000 # Population size
n
## Some helper functions
# Calculates infectiousness as a function of state and age: zero if state is
# not "I"; nonzero if state is "I", and slightly decreasing with age
<- function(state, age) {
infectiousness ifelse(state == "I", 1.25 - age / 160, 0)
}
# Calculates susceptibility of individuals with antibody level(s) ab
<- function(ab) {
susceptibility pnorm(ab, 5, 1, lower.tail = FALSE)
}
# Generates n random delays from the latent-period distribution
# (approximately 2 days, on average)
<- function(n) {
latent_delay rlnorm(n, meanlog = 0.5, sdlog = 0.6)
}
# Generates n random delays from the infectious-period distribution
# (approximately 5 days, on average)
<- function(n) {
infectious_delay rlnorm(n, meanlog = 1.5, sdlog = 0.5)
}
# Generates n random increments to antibody levels following recovery
<- function(n) {
ab_increment rnorm(n, mean = 12, sd = 2)
}
## Data frame to store simulation results
<- data.frame(ts = 1:steps, S = 0, E = 0, I = 0, AMeanU = 0, AMeanV = 0)
results
## Initialize simulation
# Set the seed for the pseudorandom number generator, for reproducibility
set.seed(12345)
# Initialize state variables
<- rep("S", n) # Each individual's state: start with all susceptible
state <- runif(n, 0, 80) # Each individual's age: random distribution from 0 to 80
age <- rep(0, n) # Delay for latent and infectious periods
delay <- rep(0, n) # Antibody concentration for each individual
antib <- rep(FALSE, n) # Vaccinated status
vacc
1:10] <- "E" # Start 10 individuals in the "exposed" state
state[
## Run simulation
# Initialize progress bar
<- txtProgressBar(min = 1, max = steps, style = 3)
bar
# Loop over each time step . . .
for (ts in 1:steps) {
# Calculate the force of infection
<- beta * sum(infectiousness(state, age)) / n + iota
lambda
##### NOTE - There is no inner loop over individuals anymore!
# Update non-state variables (for all individuals simultaneously)
# Time remaining in latent/infectious periods
<- delay - dt
delay # Antibody waning
<- antib - wane * dt
antib # Vaccination at time step 300 for over-40s
if (ts == 300) {
>= 40] <- TRUE
vacc[age <- antib[vacc] + 2 * ab_increment(sum(vacc))
antib[vacc]
}
# Update state variables (for all individuals simultaneously)
##### trE selects all individuals who will transition states from S to E.
<- (state == "S") & (runif(n) < 1 - exp(-lambda * dt)) &
trE runif(n) < susceptibility(antib))
(<- (state == "E") & (delay < 0)
trI <- (state == "I") & (delay < 0)
trS
# Do state transitions
# transition S -> E
<- "E"
state[trE] <- latent_delay(sum(trE))
delay[trE]
# transition E -> I
<- "I"
state[trI] <- infectious_delay(sum(trI))
delay[trI]
# transition I -> S
<- "S"
state[trS] <- antib[trS] + ab_increment(sum(trS))
antib[trS]
# Save population state for this time step
"S"] <- sum(state == "S")
results[ts, "E"] <- sum(state == "E")
results[ts, "I"] <- sum(state == "I")
results[ts, "AMeanU"] <- mean(antib[!vacc])
results[ts, "AMeanV"] <- mean(antib[vacc])
results[ts,
# Update progress bar; close progress bar if we are finished
setTxtProgressBar(bar, ts)
if (ts == steps) {
close(bar)
}
}
## Plot simulation results
ggplot(results) +
geom_line(aes(x = ts, y = S, colour = "S")) +
geom_line(aes(x = ts, y = E, colour = "E")) +
geom_line(aes(x = ts, y = I, colour = "I"))
ggplot(results) +
geom_line(aes(x = ts, y = AMeanU, colour = "Unvaccinated")) +
geom_line(aes(x = ts, y = AMeanV, colour = "Vaccinated")) +
labs(x = "Time step", y = "Mean antibody level")
Return to the practical here.