library(odin)
library(tidyr)
library(ggplot2)
library(RColorBrewer)
library(patchwork)
2 SEIR
2.1 Code
Let reuse the deterministic SIR model code from Listing 1.1 and write code for the deterministic SEIR model.
<- odin::odin({
odin_seir # Derivatives
deriv(S) <- -beta * S * I
deriv(E) <- beta * S * I - sigma * E
deriv(I) <- sigma * E - gamma * I
deriv(R) <- gamma * I
deriv(CInc) <- sigma * E
# Initial conditions
initial(S) <- S_init
initial(E) <- E_init
initial(I) <- I_init
initial(R) <- R_init
initial(CInc) <- CInc_init
# Parameters and initial values
<- user(0.004)
beta <- user(0.5)
sigma <- user(0.5)
gamma <- user(369)
S_init <- user(0)
E_init <- user(1)
I_init <- user(0)
R_init <- user(0)
CInc_init
})
<- function(beta, sigma, gamma, S0, E0, I0, R0, times) {
seir_mod # Set values for a new run
<- odin_seir$new(beta = beta, sigma = sigma, gamma = gamma, S_init = S0, E_init = E0, I_init = I0, R_init = R0)
odin_run
# Run the model
<- data.frame(odin_run$run(times))
out
# Compute incidence from cumulative incidence
$Inc <- c(I0, diff(out$CInc))
out$CInc <- NULL
out
out }
Code
<- sir_mod(beta = 0.004, gamma = 0.5, S0 = 999, I0 = 1, R0 = 0, times = 1:20)
pred1 <- seir_mod(beta = 0.004, sigma = 0.5, gamma = 0.5, S0 = 999, E0 = 0, I0 = 1, R0 = 0, times = 1:20)
pred2
<- pivot_longer(pred1, cols = S:Inc, names_to = "comp", values_to = "n")
df_plot
<- brewer.pal(11, "PuOr")[c(10, 4, 3, 8)]
my_palette
<- ggplot(df_plot, aes(x = t, y = n, color = comp)) +
p1 geom_line(linewidth = 1.2) +
scale_color_manual(values = my_palette, breaks = c("S", "Inc", "I", "R")) +
labs(color = NULL, y = NULL, x = NULL) +
theme_minimal() +
theme(legend.position = "none")
<- pivot_longer(pred2, cols = S:Inc, names_to = "comp", values_to = "n")
df_plot
<- brewer.pal(11, "PuOr")[c(10, 1, 4, 3, 8)]
my_palette
<- ggplot(df_plot, aes(x = t, y = n, color = comp)) +
p2 geom_line(linewidth = 1.2) +
scale_color_manual(values = my_palette, breaks = c("S", "E", "Inc", "I", "R")) +
labs(color = NULL, y = NULL, x = "Time") +
theme_minimal() +
theme(legend.position = "bottom")
/ p2 p1