Skip to content

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.

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 / N
dI/dt = beta * S * I / N - gamma * I
dR/dt = gamma * I

One 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.

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.

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"]]) / population
s_end <- uniroot(FinalSizeEquation, c(1e-6, 1 / r_zero), r_zero = r_zero,
s_start = s_start, tol = 1e-12)$root
long_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 people
Susceptible fraction at the peak 0.500, 1 / R0 = 0.500
Final size from the equation 0.7969, from the solver 0.7969
Herd immunity threshold 1 - 1 / R0 = 0.50
Immune 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

Line plot drawn with ggplot2 of the susceptible, infectious and recovered people over 100 days. The susceptible curve falls from 20,000 and levels off near 4,000. The infectious curve peaks near 3,100 people on about day 33, at the moment the susceptible curve crosses a dashed line at 10,000. The recovered curve rises to about 16,000.

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.

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_expected
cat(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 29
Poisson likelihood of the daily cases:
estimate lower upper se_log truth
beta 0.5075 0.4920 0.5236 0.0159 0.50
gamma 0.2585 0.2413 0.2769 0.0351 0.25
R0 1.9637 1.8903 2.0400 0.0195 2.00
Least squares on the cumulative cases:
estimate lower upper se_log truth
beta 0.5113 0.5104 0.5123 0.0010 0.50
gamma 0.2630 0.2622 0.2639 0.0016 0.25
R0 1.9441 1.9414 1.9468 0.0007 2.00
Standard error, daily fit over cumulative fit: beta 16 gamma 22 R0 27
Lag-1 correlation of the cumulative residuals 0.70

The 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.

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 cases
gamma 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.59
All 70 days, reporting fraction estimated:
estimate lower upper se_log truth
beta 0.4697 0.4271 0.5167 0.0486 0.50
gamma 0.2149 0.1693 0.2729 0.1218 0.25
R0 2.1856 1.8931 2.5232 0.0733 2.00
Reporting fraction 0.279, 95% CI [0.257, 0.302], truth 0.3

The 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.

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.5
seir_rate <- (-(sigma + gamma) +
sqrt((sigma - gamma)^2 + 4 * beta * sigma)) / 2
cat(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.140
Doubling 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_size
SIR 32.61 3071.028 0.797
SEIR 57.00 2032.661 0.797
SEIR, beta x 0.6 from day 40 45.90 801.739 0.445

The 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.

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.

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.

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.

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.