# The SIR epidemic model
# https://tidyecology.com/posts/the-sir-epidemic-model/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-07-05

## ---- setup ----
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE,
                      dev = "png", dpi = 120, fig.path = "figures/",
                      fig.width = 7, fig.height = 4.4)
library(ggplot2)
theme_te <- theme_minimal(base_size = 12) +
  theme(panel.background = element_rect(fill = "#f5f4ee", colour = NA),
        plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
        panel.grid.minor = element_blank(),
        plot.title = element_text(face = "bold", size = 12))
theme_set(theme_te)
col_S <- "#3a6b52"; col_I <- "#b5651d"; col_R <- "#8aa29e"; col_ref <- "#555555"

sir <- function(beta, gamma, I0 = 1e-3, Tn = 200, dt = 0.01) {
  S <- 1 - I0; I <- I0; R <- 0; out <- data.frame(t = 0, S = S, I = I, R = R)
  for (k in 1:(Tn/dt)) {
    dS <- -beta*S*I; dI <- beta*S*I - gamma*I; dR <- gamma*I
    S <- S + dS*dt; I <- I + dI*dt; R <- R + dR*dt
    if (k %% round(1/dt) == 0) out <- rbind(out, data.frame(t = k*dt, S = S, I = I, R = R))
  }
  out
}
beta <- 0.4; gamma <- 0.1; R0 <- beta/gamma
ep <- sir(beta, gamma)
peak_prev <- max(ep$I); peak_time <- ep$t[which.max(ep$I)]
final_size <- tail(ep$R, 1)
fs_eqn <- function(R0) { z <- 0.5; for (i in 1:200) z <- 1 - exp(-R0*z); z }

## ---- sir ----
sir_step <- function(S, I, R, beta, gamma, dt) {
  dS <- -beta*S*I                 # susceptibles become infected on contact
  dI <-  beta*S*I - gamma*I       # infecteds arrive, and recover at rate gamma
  dR <-  gamma*I                  # recovered accumulate
  c(S + dS*dt, I + dI*dt, R + dR*dt)
}
beta <- 0.4; gamma <- 0.1        # transmission rate and recovery rate (per day)
state <- c(1 - 1e-3, 1e-3, 0)    # start almost all susceptible, a seed of infection
for (k in 1:20000) state <- sir_step(state[1], state[2], state[3], beta, gamma, 0.01)
round(state, 3)                  # S, I, R at the end

## ---- fig-curves ----
dl <- rbind(data.frame(t = ep$t, frac = ep$S, comp = "susceptible"),
            data.frame(t = ep$t, frac = ep$I, comp = "infected"),
            data.frame(t = ep$t, frac = ep$R, comp = "recovered"))
ggplot(dl, aes(t, frac, colour = comp)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("susceptible" = col_S, "infected" = col_I, "recovered" = col_R)) +
  labs(x = "Time (days)", y = "Fraction of population", colour = NULL,
       title = "One epidemic, three compartments")

## ---- r0 ----
c(R0 = beta/gamma, mean_infectious_period_days = 1/gamma)

## ---- fig-final ----
R0g <- seq(0.2, 5, 0.05)
dg <- data.frame(R0 = R0g, size = sapply(R0g, fs_eqn))
ggplot(dg, aes(R0, size)) +
  geom_vline(xintercept = 1, colour = col_ref, linetype = "dotted") +
  geom_line(colour = col_I, linewidth = 1) +
  annotate("text", x = 1.05, y = 0.9, label = "threshold at R0 = 1", hjust = 0, colour = col_ref, size = 3.4) +
  labs(x = "Basic reproduction number", y = "Final epidemic size",
       title = "Below one nothing happens, above one it spreads")
