SIR & SEIR Models
A compartmental model divides a closed population into people who are susceptible, infectious and recovered, and moves them between the compartments at fixed rates. This page solves the SIR model and checks three results that follow from its equations. It then fits the model to the daily reported cases of an invented outbreak, shows two ways in which the fit misleads, and adds a latent period and one intervention scenario.
The SIR model
Section titled “The SIR model”A susceptible person becomes infected at the rate beta × I / N per day, where beta is the transmission rate and I / N is the infectious fraction of the population. An infectious person recovers, with lasting immunity, at the recovery rate gamma per day, so the mean infectious period is 1 / gamma days. With S, I and R people in a population of N, the equations are:
dS/dt = -beta * S * I / NdI/dt = beta * S * I / N - gamma * IdR/dt = gamma * IOne infectious person in a fully susceptible population infects beta people per day for 1 / gamma days, so the basic reproduction number is R0 = beta / gamma. The number of infectious people grows while beta × S / N exceeds gamma. It therefore peaks when the susceptible fraction S / N falls to 1 / R0, and no outbreak can grow when a fraction of at least 1 − 1 / R0 is immune, which is the herd immunity threshold. The susceptible fraction s_end that is left at the end solves the final size equation, log(s_end / s_start) = −R0 × (1 − s_end), when nobody is immune at the start. With an immune fraction at the start, 1 − s_end becomes 1 − immune − s_end.
Get the data
Section titled “Get the data”Download town_outbreak.csv into your working directory. The invented table has 70 rows, one per day, and two columns: day and cases, the new cases that surveillance reported for that day. The day is the unit of observation. The counts come from an SIR model with known values. The town has 20,000 people, and 5 of them are infectious on day 0. The transmission rate is 0.5 per day and the recovery rate is 0.25 per day, so R0 is 2 and the mean infectious period is 4 days. Surveillance reports 30% of the new infections of each day, and each daily count is a Poisson draw around that expected number. The page solves the model with these true values first and fits it to the counts after that.
Solve the equations and check the results
Section titled “Solve the equations and check the results”deSolve::ode() in R and scipy.integrate.solve_ivp() in Python both take a function that returns the derivatives. Both calls use the LSODA method with relative and absolute tolerances of 1e-10. The defaults differ: deSolve 1.42 uses LSODA with 1e-6 for both tolerances, and scipy 1.18 uses RK45 with a relative tolerance of 1e-3. With the shared setting the two tabs agree to every printed digit. The code solves the model on a grid of 0.01 days, reads the peak, solves the final size equation with a root finder, and starts the outbreak again with 40%, 50% and 60% of the town immune. For each of those runs it prints the infections by day 400 and the final size from the equation.
library(deSolve)library(ggplot2)
#' Compute the time derivatives of the SIR model.#'#' @param time Time in days. The model does not use it.#' @param state Named vector with the people in S, I and R.#' @param parameters Named vector with beta, gamma and the population N.#' @return A list that holds the three derivatives, as deSolve expects.SirDerivative <- function(time, state, parameters) { infection <- parameters[["beta"]] * state[["S"]] * state[["I"]] / parameters[["N"]] recovery <- parameters[["gamma"]] * state[["I"]] list(c(-infection, infection - recovery, recovery))}
#' Solve the SIR model at the requested times.#'#' @param parameters Named vector with beta, gamma, the population N and#' the number of people who are infectious at time 0.#' @param times Times in days, starting at 0.#' @param immune People who are immune at time 0.#' @return A data frame with the columns time, S, I and R.SolveSir <- function(parameters, times, immune = 0) { start <- c(S = parameters[["N"]] - parameters[["infected"]] - immune, I = parameters[["infected"]], R = immune) as.data.frame(ode(y = start, times = times, func = SirDerivative, parms = parameters, rtol = 1e-10, atol = 1e-10))}
#' Evaluate the final size equation of the SIR model.#'#' @param s_end Candidate susceptible fraction at the end.#' @param r_zero Basic reproduction number.#' @param s_start Susceptible fraction at time 0.#' @param immune Immune fraction at time 0.#' @return The value of the equation, zero at the solution.FinalSizeEquation <- function(s_end, r_zero, s_start, immune = 0) { log(s_end / s_start) + r_zero * (1 - immune - s_end)}
dir.create("outputs", showWarnings = FALSE)truth <- c(beta = 0.5, gamma = 0.25, N = 20000, infected = 5)population <- truth[["N"]]r_zero <- truth[["beta"]] / truth[["gamma"]]sir <- SolveSir(truth, seq(0, 100, 0.01))peak <- sir[which.max(sir$I), ]cat(sprintf("R0 = %.1f. Peak on day %.2f with %.0f infectious people\n", r_zero, peak$time, peak$I))cat(sprintf("Susceptible fraction at the peak %.3f, 1 / R0 = %.3f\n", peak$S / population, 1 / r_zero))s_start <- (population - truth[["infected"]]) / populations_end <- uniroot(FinalSizeEquation, c(1e-6, 1 / r_zero), r_zero = r_zero, s_start = s_start, tol = 1e-12)$rootlong_run <- SolveSir(truth, c(0, 400))cat(sprintf("Final size from the equation %.4f, from the solver %.4f\n", 1 - s_end, 1 - long_run$S[2] / population))cat(sprintf("Herd immunity threshold 1 - 1 / R0 = %.2f\n", 1 - 1 / r_zero))cat("Immune R_eff peak I infected by day 400 infected in the end\n")for (immune_share in c(0.4, 0.5, 0.6)) { run <- SolveSir(truth, 0:400, immune_share * population) s_zero <- run$S[1] / population s_final <- uniroot(FinalSizeEquation, c(1e-6, s_zero), r_zero = r_zero, s_start = s_zero, immune = immune_share, tol = 1e-12)$root cat(sprintf("%5.0f%% %5.2f %6.0f %19.1f %19.1f\n", 100 * immune_share, r_zero * s_zero, max(run$I), run$S[1] - run$S[401], population * (s_zero - s_final)))}
compartments <- cbind(time = sir$time, stack(sir[c("S", "I", "R")]))sir_plot <- ggplot(compartments, aes(time, values, color = ind)) + geom_line(linewidth = 0.9) + geom_hline(yintercept = population / r_zero, linetype = "dashed", color = "gray50") + scale_color_manual(values = c(S = "#4c72b0", I = "#c44e52", R = "#55a868"), labels = c("Susceptible", "Infectious", "Recovered")) + labs(x = "Day", y = "People", color = NULL) + theme_classic(base_size = 12)ggsave("outputs/sir-curves-r.png", sir_plot, width = 7, height = 3.5, dpi = 150)R0 = 2.0. Peak on day 32.61 with 3071 infectious peopleSusceptible fraction at the peak 0.500, 1 / R0 = 0.500Final size from the equation 0.7969, from the solver 0.7969Herd immunity threshold 1 - 1 / R0 = 0.50Immune R_eff peak I infected by day 400 infected in the end 40% 1.20 181 3778.7 3778.7 50% 1.00 5 283.1 307.9 60% 0.80 5 19.8 19.8
from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import optimizefrom scipy import specialfrom scipy import statsfrom scipy.integrate import solve_ivpfrom statsmodels.tools.numdiff import approx_hess3
def sir_derivative(time, state, parameters): """Compute the time derivatives of the SIR model.
Args: time: Time in days. The model does not use it. state: The people in S, I and R. parameters: A dictionary with beta, gamma and the population.
Returns: A list with the three derivatives. """ susceptible, infectious, _ = state infection = (parameters["beta"] * susceptible * infectious / parameters["population"]) recovery = parameters["gamma"] * infectious return [-infection, infection - recovery, recovery]
def solve_sir(parameters, times, immune=0): """Solve the SIR model at the requested times.
Args: parameters: A dictionary with beta, gamma, the population and the number of people who are infectious at time 0. times: Times in days, starting at 0. immune: People who are immune at time 0.
Returns: A data frame with the columns time, S, I and R. """ start = [parameters["population"] - parameters["infected"] - immune, parameters["infected"], immune] solution = solve_ivp(sir_derivative, (times[0], times[-1]), start, t_eval=times, method="LSODA", rtol=1e-10, atol=1e-10, args=(parameters,)) return pd.DataFrame({"time": solution.t, "S": solution.y[0], "I": solution.y[1], "R": solution.y[2]})
def final_size_equation(s_end, r_zero, s_start, immune=0.0): """Evaluate the final size equation of the SIR model.
Args: s_end: Candidate susceptible fraction at the end. r_zero: Basic reproduction number. s_start: Susceptible fraction at time 0. immune: Immune fraction at time 0.
Returns: The value of the equation, zero at the solution. """ return np.log(s_end / s_start) + r_zero * (1 - immune - s_end)
output = Path("outputs")output.mkdir(exist_ok=True)truth = {"beta": 0.5, "gamma": 0.25, "population": 20000, "infected": 5}population = truth["population"]r_zero = truth["beta"] / truth["gamma"]sir = solve_sir(truth, np.linspace(0, 100, 10001))peak = sir.loc[sir["I"].idxmax()]print(f"R0 = {r_zero:.1f}. Peak on day {peak['time']:.2f} with " f"{peak['I']:.0f} infectious people")print(f"Susceptible fraction at the peak {peak['S'] / population:.3f}, " f"1 / R0 = {1 / r_zero:.3f}")s_start = (population - truth["infected"]) / populations_end = optimize.brentq(final_size_equation, 1e-6, 1 / r_zero, args=(r_zero, s_start), xtol=1e-12)long_run = solve_sir(truth, np.array([0, 400]))print(f"Final size from the equation {1 - s_end:.4f}, from the solver " f"{1 - long_run['S'].iloc[-1] / population:.4f}")print(f"Herd immunity threshold 1 - 1 / R0 = {1 - 1 / r_zero:.2f}")print("Immune R_eff peak I infected by day 400 infected in the end")for immune_share in (0.4, 0.5, 0.6): run = solve_sir(truth, np.arange(0, 401), immune_share * population) s_zero = run["S"].iloc[0] / population s_final = optimize.brentq(final_size_equation, 1e-6, s_zero, args=(r_zero, s_zero, immune_share), xtol=1e-12) print(f"{100 * immune_share:5.0f}% {r_zero * s_zero:5.2f} " f"{run['I'].max():6.0f} " f"{run['S'].iloc[0] - run['S'].iloc[-1]:19.1f} " f"{population * (s_zero - s_final):19.1f}")
figure, axes = plt.subplots(figsize=(7, 3.5))axes.plot(sir["time"], sir["S"], color="#4c72b0", label="Susceptible")axes.plot(sir["time"], sir["I"], color="#c44e52", label="Infectious")axes.plot(sir["time"], sir["R"], color="#55a868", label="Recovered")axes.axhline(population / r_zero, color="0.5", linestyle="--")axes.set_xlabel("Day")axes.set_ylabel("People")axes.legend(frameon=False, loc="center left", bbox_to_anchor=(1, 0.5))axes.spines[["top", "right"]].set_visible(False)figure.tight_layout()figure.savefig(output / "sir-curves-python.png", dpi=150)plt.close(figure)R0 = 2.0. Peak on day 32.61 with 3071 infectious peopleSusceptible fraction at the peak 0.500, 1 / R0 = 0.500Final size from the equation 0.7969, from the solver 0.7969Herd immunity threshold 1 - 1 / R0 = 0.50Immune R_eff peak I infected by day 400 infected in the end 40% 1.20 181 3778.7 3778.7 50% 1.00 5 283.1 307.9 60% 0.80 5 19.8 19.8
The epidemic peaks on day 32.61 with 3,071 infectious people. At that moment the susceptible fraction is 0.500, which is 1 / R0, and the figure shows the susceptible curve cross the dashed line at 10,000 people as the infectious curve turns. The peak comes at the threshold and not at the end, so infections continue after it. The final size equation gives 0.7969 of the town infected, and the solver, run to day 400, gives the same four digits. One in five people is never infected, because transmission stops once the susceptible fraction is too small to replace the people who recover.
The herd immunity threshold is 0.50. With 40% immune at the start, the effective reproduction number is 1.20 and the outbreak still reaches a peak of 181 infectious people and 3,778.7 infections, the same number by day 400 and from the equation. At 50% the effective number prints as 1.00 and the 5 first cases are the peak. By day 400, 283.1 people are infected, while the equation gives 307.9 in the end. So close to the threshold each chain of transmission fades out so slowly that the outbreak has not ended after 400 days. At 60%, 19.8 people are infected. The threshold marks where growth stops, and infections still occur close to it.
Fit incidence, not cumulative counts
Section titled “Fit incidence, not cumulative counts”The fit asks which beta and gamma make the observed counts most probable. For given rates, the model gives the expected reported cases of day t as 0.3 × (S(t − 1) − S(t)), and each observed count is Poisson around it. The code minimizes the negative log-likelihood over log(beta) and log(gamma) with the Nelder-Mead method: optim() in R and scipy.optimize.minimize() in Python. The log scale keeps both rates positive. The reporting fraction, the population and the 5 first cases are fixed at their true values. The likelihood page explains the likelihood, and the optimization page explains how a minimizer searches.
The intervals are Wald intervals from the Hessian, the matrix of second derivatives of the negative log-likelihood at the minimum, whose inverse estimates the covariance of the two log rates. optim() computes the Hessian by finite differences when hessian = TRUE, and Python uses approx_hess3() of statsmodels with the same step of 0.001. The interval of R0 comes from the variance of log(beta) − log(gamma), which includes the covariance of the two rates. The same code then fits the cumulative curve by least squares, a standard practice in outbreak analysis, with intervals from the Hessian of the sum of squares and the residual variance.
#' Compute the expected reported cases of each day under the SIR model.#'#' @param parameters Named vector for SolveSir().#' @param reporting Fraction of infections that surveillance reports.#' @param n_days Number of days of data, from day 1.#' @return A vector with the expected reported cases of days 1 to n_days.ExpectedCases <- function(parameters, reporting, n_days) { reporting * -diff(SolveSir(parameters, 0:n_days)$S)}
#' Compute the loss of the SIR model for the reported cases.#'#' @param log_rates log(beta) and log(gamma), and optionally the logit of#' the reporting fraction as a third element.#' @param cases Reported cases of each day, from day 1.#' @param setting Named vector with N and infected.#' @param reporting Reporting fraction when log_rates has two elements.#' @param loss "poisson" for the negative Poisson log-likelihood of the#' daily cases, "cumulative" for the sum of squares of the cumulative#' cases.#' @return The value of the loss.SirLoss <- function(log_rates, cases, setting, reporting, loss = "poisson") { if (length(log_rates) == 3) { reporting <- plogis(log_rates[3]) } parameters <- c(beta = exp(log_rates[[1]]), gamma = exp(log_rates[[2]]), setting) expected <- ExpectedCases(parameters, reporting, length(cases)) if (loss == "cumulative") { return(sum((cumsum(cases) - cumsum(expected))^2)) } -sum(dpois(cases, expected, log = TRUE))}
#' Summarize a fit on the log scale as estimates with 95% Wald limits.#'#' @param log_estimate log(beta) and log(gamma) at the optimum.#' @param covariance Covariance matrix of the two log parameters.#' @return A data frame with the rows beta, gamma and R0.SummarizeFit <- function(log_estimate, covariance) { log_value <- c(log_estimate[1:2], log_estimate[1] - log_estimate[2]) se <- sqrt(c(covariance[1, 1], covariance[2, 2], covariance[1, 1] + covariance[2, 2] - 2 * covariance[1, 2])) z <- qnorm(0.975) data.frame(row.names = c("beta", "gamma", "R0"), estimate = exp(log_value), lower = exp(log_value - z * se), upper = exp(log_value + z * se), se_log = se, truth = c(0.5, 0.25, 2))}
town <- read.csv("town_outbreak.csv")cat(sprintf("%d days, %d reported cases, largest count %d on day %d\n", nrow(town), sum(town$cases), max(town$cases), which.max(town$cases)))setting <- truth[c("N", "infected")]start_values <- log(c(0.6, 0.3))tight <- list(reltol = 1e-12, maxit = 5000)incidence_fit <- optim(start_values, SirLoss, cases = town$cases, setting = setting, reporting = 0.3, hessian = TRUE, control = tight)incidence_summary <- SummarizeFit(incidence_fit$par, solve(incidence_fit$hessian))cumulative_fit <- optim(start_values, SirLoss, cases = town$cases, setting = setting, reporting = 0.3, loss = "cumulative", hessian = TRUE, control = tight)residual_variance <- cumulative_fit$value / (nrow(town) - 2)cumulative_summary <- SummarizeFit( cumulative_fit$par, 2 * residual_variance * solve(cumulative_fit$hessian))cat("Poisson likelihood of the daily cases:\n")print(round(incidence_summary, 4))cat("Least squares on the cumulative cases:\n")print(round(cumulative_summary, 4))cat("Standard error, daily fit over cumulative fit:", sprintf("%s %.0f", rownames(incidence_summary), incidence_summary$se_log / cumulative_summary$se_log), "\n")cumulative_expected <- cumsum(ExpectedCases( c(beta = exp(cumulative_fit$par[[1]]), gamma = exp(cumulative_fit$par[[2]]), setting), 0.3, nrow(town)))residual <- cumsum(town$cases) - cumulative_expectedcat(sprintf("Lag-1 correlation of the cumulative residuals %.2f\n", cor(residual[-1], residual[-nrow(town)])))70 days, 4678 reported cases, largest count 272 on day 29Poisson likelihood of the daily cases: estimate lower upper se_log truthbeta 0.5075 0.4920 0.5236 0.0159 0.50gamma 0.2585 0.2413 0.2769 0.0351 0.25R0 1.9637 1.8903 2.0400 0.0195 2.00Least squares on the cumulative cases: estimate lower upper se_log truthbeta 0.5113 0.5104 0.5123 0.0010 0.50gamma 0.2630 0.2622 0.2639 0.0016 0.25R0 1.9441 1.9414 1.9468 0.0007 2.00Standard error, daily fit over cumulative fit: beta 16 gamma 22 R0 27Lag-1 correlation of the cumulative residuals 0.70def expected_cases(parameters, reporting, n_days): """Compute the expected reported cases of each day under the SIR model.
Args: parameters: A dictionary for solve_sir(). reporting: Fraction of infections that surveillance reports. n_days: Number of days of data, from day 1.
Returns: An array with the expected reported cases of days 1 to n_days. """ solution = solve_sir(parameters, np.arange(0, n_days + 1)) return reporting * -np.diff(solution["S"].to_numpy())
def sir_loss(log_rates, cases, setting, reporting, loss="poisson"): """Compute the loss of the SIR model for the reported cases.
Args: log_rates: log(beta) and log(gamma), and optionally the logit of the reporting fraction as a third element. cases: Reported cases of each day, from day 1. setting: A dictionary with the population and infected. reporting: Reporting fraction when log_rates has two elements. loss: "poisson" for the negative Poisson log-likelihood of the daily cases, "cumulative" for the sum of squares of the cumulative cases.
Returns: The value of the loss. """ if len(log_rates) == 3: reporting = special.expit(log_rates[2]) parameters = {"beta": np.exp(log_rates[0]), "gamma": np.exp(log_rates[1]), **setting} expected = expected_cases(parameters, reporting, len(cases)) if loss == "cumulative": return np.sum((np.cumsum(cases) - np.cumsum(expected)) ** 2) return -np.sum(stats.poisson.logpmf(cases, expected))
def summarize_fit(log_estimate, covariance): """Summarize a fit on the log scale as estimates with 95% Wald limits.
Args: log_estimate: log(beta) and log(gamma) at the optimum. covariance: Covariance matrix of the two log parameters.
Returns: A data frame with the rows beta, gamma and R0. """ log_value = np.array([log_estimate[0], log_estimate[1], log_estimate[0] - log_estimate[1]]) se = np.sqrt([covariance[0, 0], covariance[1, 1], covariance[0, 0] + covariance[1, 1] - 2 * covariance[0, 1]]) z = stats.norm.ppf(0.975) return pd.DataFrame( {"estimate": np.exp(log_value), "lower": np.exp(log_value - z * se), "upper": np.exp(log_value + z * se), "se_log": se, "truth": [0.5, 0.25, 2.0]}, index=["beta", "gamma", "R0"])
town = pd.read_csv("town_outbreak.csv")cases = town["cases"].to_numpy()print(f"{len(town)} days, {cases.sum()} reported cases, largest count " f"{cases.max()} on day {town.loc[town['cases'].idxmax(), 'day']}")setting = {"population": population, "infected": truth["infected"]}start_values = np.log([0.6, 0.3])tight = {"xatol": 1e-6, "fatol": 1e-4, "maxiter": 2000}fixed = (cases, setting, 0.3)incidence_fit = optimize.minimize(sir_loss, start_values, args=fixed, method="Nelder-Mead", options=tight)incidence_summary = summarize_fit(incidence_fit.x, np.linalg.inv( approx_hess3(incidence_fit.x, sir_loss, epsilon=1e-3, args=fixed)))cumulative = (*fixed, "cumulative")cumulative_fit = optimize.minimize(sir_loss, start_values, args=cumulative, method="Nelder-Mead", options=tight)residual_variance = cumulative_fit.fun / (len(town) - 2)cumulative_summary = summarize_fit( cumulative_fit.x, 2 * residual_variance * np.linalg.inv( approx_hess3(cumulative_fit.x, sir_loss, epsilon=1e-3, args=cumulative)))print("Poisson likelihood of the daily cases:")print(incidence_summary.round(4))print("Least squares on the cumulative cases:")print(cumulative_summary.round(4))ratio = incidence_summary["se_log"] / cumulative_summary["se_log"]print("Standard error, daily fit over cumulative fit:", *(f"{name} {value:.0f}" for name, value in ratio.items()))cumulative_expected = np.cumsum(expected_cases( {"beta": np.exp(cumulative_fit.x[0]), "gamma": np.exp(cumulative_fit.x[1]), **setting}, 0.3, len(town)))residual = np.cumsum(cases) - cumulative_expectedprint(f"Lag-1 correlation of the cumulative residuals " f"{np.corrcoef(residual[1:], residual[:-1])[0, 1]:.2f}")70 days, 4678 reported cases, largest count 272 on day 29Poisson likelihood of the daily cases: estimate lower upper se_log truthbeta 0.5075 0.4920 0.5236 0.0159 0.50gamma 0.2585 0.2413 0.2769 0.0351 0.25R0 1.9637 1.8903 2.0400 0.0195 2.00Least squares on the cumulative cases: estimate lower upper se_log truthbeta 0.5113 0.5104 0.5123 0.0010 0.50gamma 0.2630 0.2622 0.2639 0.0016 0.25R0 1.9441 1.9414 1.9468 0.0007 2.00Standard error, daily fit over cumulative fit: beta 16 gamma 22 R0 27Lag-1 correlation of the cumulative residuals 0.70The town reported 4,678 cases, with the largest count, 272, on day 29. The Poisson fit returns beta 0.5075 with an interval from 0.4920 to 0.5236 and gamma 0.2585 with an interval from 0.2413 to 0.2769. Both contain the truth. R0 is 1.964, with an interval from 1.890 to 2.040 that contains 2. On the log scale the standard error is 0.0159 for beta, 0.0351 for gamma and 0.0195 for R0.
The cumulative fit gives estimates close to these, beta 0.5113 and gamma 0.2630, with standard errors 16 to 27 times smaller. Its R0 interval runs from 1.941 to 1.947, and it excludes the true 2. The counts are the same, and only the method changed. A cumulative count on day t is the sum of all the daily counts up to t, so the error of day 10 is inside every later point. Consecutive residuals of the cumulative fit have a correlation of 0.70. Least squares treats the 70 points as 70 independent pieces of information, while they repeat the same errors. King and colleagues show that this practice can make the confidence in the estimates far too high. Fit the daily counts, or the weekly counts, with a count distribution.
Identifiability before the peak
Section titled “Identifiability before the peak”Early in an outbreak, analysts have only the rising part of the curve. The first block of code below uses days 1 to 21, which hold 476 reported cases, and fixes gamma at six values. For each, it finds the beta with the highest likelihood and prints that log-likelihood, the growth rate beta − gamma and R0. This is a profile of the likelihood along gamma. The second block returns to all 70 days and estimates the reporting fraction as a third parameter, on the logit scale, with the Hessian of all three.
#' Compute the negative log-likelihood of log(beta) at a fixed gamma.#'#' @param log_beta Log of the transmission rate.#' @param gamma Recovery rate per day, held fixed.#' @param cases Reported cases of each day, from day 1.#' @param setting Named vector with N and infected.#' @param reporting Reporting fraction.#' @return The negative log-likelihood.ProfileObjective <- function(log_beta, gamma, cases, setting, reporting) { SirLoss(c(log_beta, log(gamma)), cases, setting, reporting)}
early_cases <- town$cases[1:21]cat(sprintf("Days 1 to 21: %d reported cases\n", sum(early_cases)))cat(sprintf("%5s %6s %14s %11s %5s\n", "gamma", "beta", "log-likelihood", "growth rate", "R0"))for (fixed_gamma in c(0.05, 0.10, 0.20, 0.25, 0.30, 0.40)) { best <- optimize(ProfileObjective, c(log(fixed_gamma), log(fixed_gamma + 1)), gamma = fixed_gamma, cases = early_cases, setting = setting, reporting = 0.3, tol = 1e-10) best_beta <- exp(best$minimum) cat(sprintf("%5.2f %6.3f %14.2f %11.3f %5.2f\n", fixed_gamma, best_beta, -best$objective, best_beta - fixed_gamma, best_beta / fixed_gamma))}
free_fit <- optim(c(start_values, qlogis(0.4)), SirLoss, cases = town$cases, setting = setting, reporting = NULL, hessian = TRUE, control = tight)free_covariance <- solve(free_fit$hessian)free_summary <- SummarizeFit(free_fit$par, free_covariance)logit_limits <- free_fit$par[3] + c(-1, 1) * qnorm(0.975) * sqrt(free_covariance[3, 3])cat("All 70 days, reporting fraction estimated:\n")print(round(free_summary, 4))cat(sprintf("Reporting fraction %.3f, 95%% CI [%.3f, %.3f], truth 0.3\n", plogis(free_fit$par[3]), plogis(logit_limits[1]), plogis(logit_limits[2])))Days 1 to 21: 476 reported casesgamma beta log-likelihood growth rate R0 0.05 0.320 -52.59 0.270 6.41 0.10 0.364 -52.40 0.264 3.64 0.20 0.453 -53.03 0.253 2.26 0.25 0.498 -53.74 0.248 1.99 0.30 0.543 -54.64 0.243 1.81 0.40 0.636 -56.95 0.236 1.59All 70 days, reporting fraction estimated: estimate lower upper se_log truthbeta 0.4697 0.4271 0.5167 0.0486 0.50gamma 0.2149 0.1693 0.2729 0.1218 0.25R0 2.1856 1.8931 2.5232 0.0733 2.00Reporting fraction 0.279, 95% CI [0.257, 0.302], truth 0.3def profile_objective(log_beta, gamma, cases, setting, reporting): """Compute the negative log-likelihood of log(beta) at a fixed gamma.
Args: log_beta: Log of the transmission rate. gamma: Recovery rate per day, held fixed. cases: Reported cases of each day, from day 1. setting: A dictionary with the population and infected. reporting: Reporting fraction.
Returns: The negative log-likelihood. """ return sir_loss(np.array([log_beta, np.log(gamma)]), cases, setting, reporting)
early_cases = cases[:21]print(f"Days 1 to 21: {early_cases.sum()} reported cases")print(f"{'gamma':>5} {'beta':>6} {'log-likelihood':>14} " f"{'growth rate':>11} {'R0':>5}")for fixed_gamma in (0.05, 0.10, 0.20, 0.25, 0.30, 0.40): best = optimize.minimize_scalar( profile_objective, method="bounded", bounds=(np.log(fixed_gamma), np.log(fixed_gamma + 1)), args=(fixed_gamma, early_cases, setting, 0.3), options={"xatol": 1e-10}) best_beta = np.exp(best.x) print(f"{fixed_gamma:5.2f} {best_beta:6.3f} {-best.fun:14.2f} " f"{best_beta - fixed_gamma:11.3f} " f"{best_beta / fixed_gamma:5.2f}")
free = (cases, setting, None)free_fit = optimize.minimize(sir_loss, np.append(start_values, special.logit(0.4)), args=free, method="Nelder-Mead", options=tight)free_covariance = np.linalg.inv(approx_hess3(free_fit.x, sir_loss, epsilon=1e-3, args=free))free_summary = summarize_fit(free_fit.x, free_covariance)logit_limits = (free_fit.x[2] + np.array([-1, 1]) * stats.norm.ppf(0.975) * np.sqrt(free_covariance[2, 2]))print("All 70 days, reporting fraction estimated:")print(free_summary.round(4))print(f"Reporting fraction {special.expit(free_fit.x[2]):.3f}, 95% CI " f"[{special.expit(logit_limits[0]):.3f}, " f"{special.expit(logit_limits[1]):.3f}], truth 0.3")Days 1 to 21: 476 reported casesgamma beta log-likelihood growth rate R0 0.05 0.320 -52.59 0.270 6.41 0.10 0.364 -52.40 0.264 3.64 0.20 0.453 -53.03 0.253 2.26 0.25 0.498 -53.74 0.248 1.99 0.30 0.543 -54.64 0.243 1.81 0.40 0.636 -56.95 0.236 1.59All 70 days, reporting fraction estimated: estimate lower upper se_log truthbeta 0.4697 0.4271 0.5167 0.0486 0.50gamma 0.2149 0.1693 0.2729 0.1218 0.25R0 2.1856 1.8931 2.5232 0.0733 2.00Reporting fraction 0.279, 95% CI [0.257, 0.302], truth 0.3The first 21 days fix the growth rate and not the two rates. Along the table, gamma changes eightfold and the growth rate stays between 0.236 and 0.270 per day, the slope of the early curve. The best log-likelihood in the table is −52.40, at gamma 0.10 and R0 3.64. The true gamma of 0.25 gives −53.74, and gamma 0.05 gives −52.59. A 95% profile likelihood interval holds every value within 1.92 of the best, which is down to about −54.32. Every row from gamma 0.05 to 0.25 is inside it, so the data allow at least the infectious periods from 4 to 20 days and the values of R0 from 1.99 to 6.41. The row for gamma 0.30, at −54.64, is just outside.
With all 70 days and the reporting fraction free, the fit returns 0.279 for the reporting fraction, with an interval from 0.257 to 0.302, and the three rates move together. Beta and gamma go down, and R0 goes up to 2.186. A smaller reporting fraction needs more infections behind the same 4,678 reported cases, so the epidemic must be larger and R0 higher. Every interval still contains the truth. The standard error of log(beta) grows from 0.0159 to 0.0486, about three times, and that of log(R0) from 0.0195 to 0.0733.
Outside information resolves both problems. A known infectious period, from studies that measure how long patients stay infectious, fixes gamma and turns the early ridge into a single estimate. A serological survey after the outbreak measures the fraction of the town that was infected. That fraction fixes the reporting fraction, as reported cases over infections, and the final size equation turns it into R0.
Add a latent period: the SEIR model
Section titled “Add a latent period: the SEIR model”Many infections have a latent period between infection and infectiousness. The SEIR model adds an exposed compartment E between S and I. New infections enter E at the rate beta × S × I / N, and people move from E to I at the rate sigma × E. Each infection still causes beta / gamma new infections in a susceptible population, so R0 stays at 2. The code sets sigma to 0.5, a mean latent period of 2 days. The early growth rate is the largest root of r² + (sigma + gamma) × r + sigma × gamma − beta × sigma = 0. The scenario keeps the SEIR model and multiplies beta by 0.6 from day 40 on.
#' Compute the time derivatives of the SEIR model.#'#' @param time Time in days.#' @param state Named vector with the people in S, E, I and R.#' @param parameters Named vector with beta, sigma, gamma, N, change_day#' and beta_factor. beta is multiplied by beta_factor from change_day on.#' @return A list that holds the four derivatives, as deSolve expects.SeirDerivative <- function(time, state, parameters) { beta <- parameters[["beta"]] if (time >= parameters[["change_day"]]) { beta <- beta * parameters[["beta_factor"]] } infection <- beta * state[["S"]] * state[["I"]] / parameters[["N"]] onset <- parameters[["sigma"]] * state[["E"]] recovery <- parameters[["gamma"]] * state[["I"]] list(c(-infection, infection - onset, onset - recovery, recovery))}
#' Solve the SEIR model and summarize the epidemic.#'#' @param parameters Named vector for SeirDerivative(), with infected.#' @return A named vector with the day and the size of the peak of I and#' the fraction of the population infected by day 400.SummarizeSeir <- function(parameters) { start <- c(S = parameters[["N"]] - parameters[["infected"]], E = 0, I = parameters[["infected"]], R = 0) solution <- as.data.frame(ode(y = start, times = seq(0, 400, 0.1), func = SeirDerivative, parms = parameters, rtol = 1e-10, atol = 1e-10)) at_peak <- which.max(solution$I) c(peak_day = solution$time[at_peak], peak_infectious = solution$I[at_peak], final_size = 1 - solution$S[nrow(solution)] / parameters[["N"]])}
beta <- truth[["beta"]]gamma <- truth[["gamma"]]sigma <- 0.5seir_rate <- (-(sigma + gamma) + sqrt((sigma - gamma)^2 + 4 * beta * sigma)) / 2cat(sprintf("Growth rate per day: SIR %.3f, SEIR %.3f\n", beta - gamma, seir_rate))cat(sprintf("Doubling time in days: SIR %.1f, SEIR %.1f\n", log(2) / (beta - gamma), log(2) / seir_rate))cat(sprintf("(1 + r / sigma) * (1 + r / gamma) at the SEIR rate: %.3f\n", (1 + seir_rate / sigma) * (1 + seir_rate / gamma)))no_change <- c(truth, sigma = sigma, change_day = Inf, beta_factor = 1)with_change <- replace(no_change, c("change_day", "beta_factor"), c(40, 0.6))scenarios <- rbind( "SIR" = c(peak_day = peak$time, peak_infectious = peak$I, final_size = 1 - s_end), "SEIR" = SummarizeSeir(no_change), "SEIR, beta x 0.6 from day 40" = SummarizeSeir(with_change))print(round(scenarios, 3))Growth rate per day: SIR 0.250, SEIR 0.140Doubling time in days: SIR 2.8, SEIR 4.9(1 + r / sigma) * (1 + r / gamma) at the SEIR rate: 2.000 peak_day peak_infectious final_sizeSIR 32.61 3071.028 0.797SEIR 57.00 2032.661 0.797SEIR, beta x 0.6 from day 40 45.90 801.739 0.445def seir_derivative(time, state, parameters): """Compute the time derivatives of the SEIR model.
Args: time: Time in days. state: The people in S, E, I and R. parameters: A dictionary with beta, sigma, gamma, population, change_day and beta_factor. beta is multiplied by beta_factor from change_day on.
Returns: A list with the four derivatives. """ susceptible, exposed, infectious, _ = state beta = parameters["beta"] if time >= parameters["change_day"]: beta = beta * parameters["beta_factor"] infection = beta * susceptible * infectious / parameters["population"] onset = parameters["sigma"] * exposed recovery = parameters["gamma"] * infectious return [-infection, infection - onset, onset - recovery, recovery]
def summarize_seir(parameters): """Solve the SEIR model and summarize the epidemic.
Args: parameters: A dictionary for seir_derivative(), with infected.
Returns: A dictionary with the day and the size of the peak of I and the fraction of the population infected by day 400. """ start = [parameters["population"] - parameters["infected"], 0, parameters["infected"], 0] solution = solve_ivp(seir_derivative, (0, 400), start, t_eval=np.linspace(0, 400, 4001), method="LSODA", rtol=1e-10, atol=1e-10, args=(parameters,)) at_peak = np.argmax(solution.y[2]) return {"peak_day": solution.t[at_peak], "peak_infectious": solution.y[2][at_peak], "final_size": 1 - solution.y[0][-1] / parameters["population"]}
beta = truth["beta"]gamma = truth["gamma"]sigma = 0.5seir_rate = (-(sigma + gamma) + np.sqrt((sigma - gamma) ** 2 + 4 * beta * sigma)) / 2print(f"Growth rate per day: SIR {beta - gamma:.3f}, SEIR {seir_rate:.3f}")print(f"Doubling time in days: SIR {np.log(2) / (beta - gamma):.1f}, " f"SEIR {np.log(2) / seir_rate:.1f}")print(f"(1 + r / sigma) * (1 + r / gamma) at the SEIR rate: " f"{(1 + seir_rate / sigma) * (1 + seir_rate / gamma):.3f}")no_change = {**truth, "sigma": sigma, "change_day": np.inf, "beta_factor": 1.0}with_change = {**no_change, "change_day": 40, "beta_factor": 0.6}scenarios = pd.DataFrame({ "SIR": {"peak_day": peak["time"], "peak_infectious": peak["I"], "final_size": 1 - s_end}, "SEIR": summarize_seir(no_change), "SEIR, beta x 0.6 from day 40": summarize_seir(with_change)}).Tprint(scenarios.round(3))Growth rate per day: SIR 0.250, SEIR 0.140Doubling time in days: SIR 2.8, SEIR 4.9(1 + r / sigma) * (1 + r / gamma) at the SEIR rate: 2.000 peak_day peak_infectious final_sizeSIR 32.61 3071.028 0.797SEIR 57.00 2032.661 0.797SEIR, beta x 0.6 from day 40 45.90 801.739 0.445The latent period slows growth from 0.250 to 0.140 per day, and the doubling time grows from 2.8 to 4.9 days. The peak moves from day 32.61 to day 57.00 and falls from 3,071 to 2,033 infectious people. The final size stays at 0.797, because it depends on R0 alone. The third line puts the SEIR growth rate into (1 + r / sigma) × (1 + r / gamma) and returns 2.000. That is the relation between growth rate and reproduction number of the reproduction number page, for a generation interval made of a latent and an infectious period. The same growth rate would imply a different R0 under a different latent period.
The scenario cuts transmission by 40% on day 40, before the SEIR peak. The peak comes on day 45.90 with 802 infectious people, and the final size falls from 0.797 to 0.445.
What the deterministic model leaves out
Section titled “What the deterministic model leaves out”The equations leave out chance. They produce an outbreak from any number of first cases when R0 exceeds 1. In a real town each first case may recover before it infects anyone. In the stochastic SIR model with the same rates and a large population, the chain from one case dies out with probability 1 / R0, so 5 first cases all fail with probability (1/2)^5, about 3%.
The model gives everyone the same contact rate. People with many contacts are infected early and leave the susceptible pool first. For the same R0, an outbreak among people who differ in this way stops at a smaller final size than 0.797, and immunity from infection stops growth below the threshold of 0.50.
The model has no age structure, while contact rates differ between and within age groups. An age-structured model replaces beta with a matrix of contact rates, and R0 becomes a property of that matrix, so the immune fraction that stops growth depends on which ages are immune.
Mistakes to avoid
Section titled “Mistakes to avoid”Do not fit the cumulative curve. On these data, least squares on the cumulative cases gave R0 a standard error 27 times smaller than the Poisson fit of the daily counts did, and its interval, 1.941 to 1.947, missed the true 2.
Do not report an R0 from early data as an estimate when the recovery rate was assumed. On the first 21 days an assumed gamma of 0.25 gives R0 1.99, and an assumed gamma of 0.10 gives 3.64 with a higher likelihood. State the infectious period that you assumed and its source, and show how R0 changes with it.
Do not read a scenario as a forecast. The final size of 0.445 follows from a cut of exactly 40% on day 40 that lasts to the end, with no other change in behavior. The model computes what that assumption implies, and it does not say that the assumption will hold.
Scientific references
Section titled “Scientific references”Kermack and McKendrick, 1927 study how a contagious infection spreads from a few infected people through a susceptible community in which each case is removed by recovery or death, the problem that the SIR model formalizes.
Soetaert, Petzoldt, and Setzer, 2010 describe the deSolve package for solving differential equations in R.
King and colleagues, 2015 use a simulation study to show the pitfalls of fitting deterministic models to cumulative incidence data, including confidence in the parameter estimates that is far overestimated.
Further reading
Section titled “Further reading”The deSolve vignette explains how to write a derivative function, pass parameters, and choose a solver and its tolerances. The scipy documentation of solve_ivp() lists the methods, the tolerances and the args argument that the Python code uses.
The reproduction number page estimates the growth rate and the time-varying reproduction number from an epidemic curve without a compartmental model. The likelihood page and the optimization page cover the two ideas that the fit on this page combines.