TExcelTAD
Home › Differential Equations › Mini Project: An Epidemic Simulator and Fitter

Mini Project: An Epidemic Simulator and Fitter

This project builds a small epidemic toolkit around the SEIR model, the SIR model of Epidemic Models: SIR with an extra Exposed compartment for people who are infected but not yet infectious. You will simulate it, generate realistic noisy case data, fit the model to the data, and use the fitted model to compare interventions, checking every step against the theory of the course.

What we are building:

Step Part Course topics
1. Simulate the SEIR model model systems of ODEs, solve_ivp, conservation
2. Make noisy case data data seeded randomness, observation model
3. Fit the parameters inference least squares on ODE solutions
4. Analyse the fitted model theory R0R_0, linearization, growth rate, final size
5. Compare interventions scenarios time-dependent coefficients, vaccination

Note: Each step is a complete program (the playground does not share variables between runs), so the model code is repeated at the top of each one.

The model

With σ\sigma the rate at which exposed people become infectious (mean latent period 1σ\frac{1}{\sigma}):

S′=−βSINE′=βSIN−σEI′=σE−γIR′=γI\begin{aligned} S' &= -\beta\frac{SI}{N} \\ E' &= \beta\frac{SI}{N} - \sigma E \\ I' &= \sigma E - \gamma I \\ R' &= \gamma I \end{aligned}

S+E+I+R=NS + E + I + R = N is conserved, and R0=βγR_0 = \frac{\beta}{\gamma} as in SIR: each infectious person infects β\beta people per day for 1γ\frac{1}{\gamma} days.

Step 1: Simulate the SEIR model

A town of 200,000 people, 5 initial infections, β=0.5\beta = 0.5, σ=14\sigma = \frac{1}{4}, γ=15\gamma = \frac{1}{5}, so R0=2.5R_0 = 2.5.

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

N = 200_000
def seir(t, y, beta, sigma, gamma):
    S, E, I, R = y
    inf = beta * S * I / N
    return [-inf, inf - sigma * E, sigma * E - gamma * I, gamma * I]

beta, sigma, gamma = 0.5, 0.25, 0.2
sol = solve_ivp(seir, (0, 250), [N - 5, 0, 5, 0], args=(beta, sigma, gamma),
                dense_output=True, rtol=1e-9, atol=1e-6)
t = np.arange(0, 251)
S, E, I, R = sol.sol(t)
k = np.argmax(I)
print(f"R0 = {beta / gamma}")
print(f"peak: day {t[k]}, {I[k]:,.0f} infectious at once")
print(f"final size: {R[-1] / N:.2%} of the town")
print(f"conservation check: max |S+E+I+R - N| = {np.max(np.abs(S + E + I + R - N)):.1e}")
R0 = 2.5
peak: day 83, 25,537 infectious at once
final size: 89.26% of the town
conservation check: max |S+E+I+R - N| = 1.5e-10

Step 2: Make noisy case data

Real data are daily counts of new cases, not compartment sizes, and only a fraction of cases are reported. New infectious cases per day are σE\sigma E integrated over the day; we observe a Poisson count with a reporting rate of 40 %. A seeded generator makes the "data" reproducible. We generate 100 days of reports; step 3 first pretends that only the first 60 are available.

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

N = 200_000
def seir(t, y, beta, sigma, gamma):
    S, E, I, R = y[:4]
    inf = beta * S * I / N
    return [-inf, inf - sigma * E, sigma * E - gamma * I, gamma * I, sigma * E]   # last: cumulative cases

def daily_cases(beta, sigma, gamma, days):
    sol = solve_ivp(seir, (0, days), [N - 5, 0, 5, 0, 0], args=(beta, sigma, gamma),
                    t_eval=np.arange(0, days + 1), rtol=1e-9, atol=1e-6)
    return np.diff(sol.y[4])

rng = np.random.default_rng(2026)
true_cases = 0.4 * daily_cases(0.5, 0.25, 0.2, 100)       # 100 days of reports
observed = rng.poisson(true_cases)
print("days 1-10: ", observed[:10])
print("days 51-60:", observed[50:60])
print(f"total reported in 60 days: {observed[:60].sum():,}, in 100 days: {observed.sum():,}")
days 1-10:  [0 0 0 0 0 2 1 4 2 0]
days 51-60: [244 243 296 316 364 476 440 504 592 705]
total reported in 60 days: 5,894, in 100 days: 65,743

Step 3: Fit the parameters

Assume σ=14\sigma = \frac{1}{4} is known from clinical studies and the reporting rate is 40 %, and estimate β\beta and γ\gamma by least squares: solve the ODE for trial parameters, compare predicted and observed daily cases, and let scipy.optimize.least_squares adjust the parameters. Fitting the square roots of the counts keeps the large late counts from dominating (Poisson noise grows like mean\sqrt{\text{mean}}).

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import least_squares

N = 200_000
def seir(t, y, beta, sigma, gamma):
    S, E, I, R = y[:4]
    inf = beta * S * I / N
    return [-inf, inf - sigma * E, sigma * E - gamma * I, gamma * I, sigma * E]

def daily_cases(beta, sigma, gamma, days):
    sol = solve_ivp(seir, (0, days), [N - 5, 0, 5, 0, 0], args=(beta, sigma, gamma),
                    t_eval=np.arange(0, days + 1), rtol=1e-9, atol=1e-6)
    return np.diff(sol.y[4])

rng = np.random.default_rng(2026)
observed = rng.poisson(0.4 * daily_cases(0.5, 0.25, 0.2, 100))

def growth_rate(beta, gamma, sigma=0.25):
    return np.max(np.linalg.eigvals([[-sigma, beta], [sigma, -gamma]]).real)

for days in (60, 100):
    res = lambda p: np.sqrt(0.4 * daily_cases(p[0], 0.25, p[1], days)) - np.sqrt(observed[:days])
    beta_hat, gamma_hat = least_squares(res, x0=[0.3, 0.3], bounds=([0.01, 0.01], [3, 3])).x
    print(f"{days:3d} days: beta = {beta_hat:.4f}, gamma = {gamma_hat:.4f}, R0 = {beta_hat / gamma_hat:.3f}, "
          f"growth rate = {growth_rate(beta_hat, gamma_hat):.4f}")
print(f"truth:    beta = 0.5000, gamma = 0.2000, R0 = 2.500, growth rate = {growth_rate(0.5, 0.2):.4f}")
 60 days: beta = 0.3984, gamma = 0.1291, R0 = 3.087, growth rate = 0.1318
100 days: beta = 0.5029, gamma = 0.2018, R0 = 2.492, growth rate = 0.1295
truth:    beta = 0.5000, gamma = 0.2000, R0 = 2.500, growth rate = 0.1294

With 60 days of data, all from the growth phase, β\beta, γ\gamma and even R0R_0 come out noticeably wrong, yet the growth rate they imply (step 4 explains how it is computed) is close to the truth: the early phase of an epidemic mostly reveals that one number, and many (β,γ)(\beta, \gamma) pairs produce nearly the same exponential rise. Once the data include the peak, the parameters are pinned down much better. This is why forecasts made early in an outbreak carry wide error bars.

Step 4: Analyse the fitted model

Three predictions follow from the theory of the course, and each can be checked against a simulation:

  1. Early growth rate. Linearize the EE, II equations at the disease-free state S=NS = N (Critical Points and Linearization): the Jacobian [−σβσ−γ]\begin{bmatrix} -\sigma & \beta \\ \sigma & -\gamma \end{bmatrix} has a positive eigenvalue rr when R0>1R_0 > 1, and cases grow like erte^{rt}.
  2. Peak timing. For SIR the number infectious peaks exactly when SN=1R0\frac{S}{N} = \frac{1}{R_0}. For SEIR the peak of II comes somewhat later, when SN\frac{S}{N} is already below 1R0\frac{1}{R_0}: people exposed before that moment still become infectious afterwards.
  3. Final size. The SIR final-size equation 1−z=e−R0z1 - z = e^{-R_0z} also holds for SEIR, because the latent stage delays infections without changing how many each case causes.
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp
from scipy.optimize import brentq

N, beta, sigma, gamma = 200_000, 0.5, 0.25, 0.2    # use the fitted values from step 3 to see the forecast instead
J = np.array([[-sigma, beta], [sigma, -gamma]])
r = np.max(np.linalg.eigvals(J).real)
print(f"growth rate r = {r:.4f}/day, doubling time {np.log(2) / r:.2f} days")

def seir(t, y):
    S, E, I, R = y
    inf = beta * S * I / N
    return [-inf, inf - sigma * E, sigma * E - gamma * I, gamma * I]
sol = solve_ivp(seir, (0, 300), [N - 5, 0, 5, 0], dense_output=True, rtol=1e-10, atol=1e-6)
t = np.linspace(0, 300, 30001)
S, E, I, R = sol.sol(t)
early = (t > 15) & (t < 30)
slope = np.polyfit(t[early], np.log(I[early]), 1)[0]
print(f"simulated early slope of log I: {slope:.4f}")
k = np.argmax(I)
print(f"S/N at the peak: {S[k] / N:.3f} (1/R0 = {gamma / beta:.3f})")
z = brentq(lambda z: 1 - z - np.exp(-beta / gamma * z), 1e-9, 1)
print(f"final size: equation {z:.4f}, simulation {R[-1] / N:.4f}")
growth rate r = 0.1294/day, doubling time 5.36 days
simulated early slope of log I: 0.1293
S/N at the peak: 0.348 (1/R0 = 0.400)
final size: equation 0.8926, simulation 0.8926

Step 5: Compare interventions

Two policies, each started on day 40 (when the epidemic is detected):

  • Distancing: contacts reduced by 40 % (β→0.6β\beta \to 0.6\beta) for 60 days, then lifted.
  • Vaccination: 1 % of the susceptibles vaccinated per day from day 40 on (a flow S→RS \to R of 0.01S0.01S).
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

N, sigma, gamma = 200_000, 0.25, 0.2
def make(beta_t, vacc):
    def f(t, y):
        S, E, I, R = y
        inf = beta_t(t) * S * I / N
        v = vacc * S if t >= 40 else 0.0
        return [-inf - v, inf - sigma * E, sigma * E - gamma * I, gamma * I + v]
    return f

scenarios = {
    "no intervention":  make(lambda t: 0.5, 0.0),
    "distancing 40-100": make(lambda t: 0.3 if 40 <= t < 100 else 0.5, 0.0),
    "vaccination 1%/day": make(lambda t: 0.5, 0.01),
}
t = np.arange(0, 401)
for name, f in scenarios.items():
    sol = solve_ivp(f, (0, 400), [N - 5, 0, 5, 0], t_eval=t, max_step=0.5, rtol=1e-8, atol=1e-6)
    S, E, I, R = sol.y

    print(f"{name:19s}: peak {I.max():7,.0f} on day {t[np.argmax(I)]:3d}")
no intervention    : peak  25,537 on day  83
distancing 40-100  : peak  18,905 on day 124
vaccination 1%/day : peak  11,461 on day  82

The vaccination run moves people from SS to RR without infection, so to compare final sizes we track infections separately. A cumulative-infections compartment does that:

python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

N, sigma, gamma = 200_000, 0.25, 0.2
def make(beta_t, vacc):
    def f(t, y):
        S, E, I, R, C = y
        inf = beta_t(t) * S * I / N
        v = vacc * S if t >= 40 else 0.0
        return [-inf - v, inf - sigma * E, sigma * E - gamma * I, gamma * I + v, inf]
    return f

for name, f in (("no intervention", make(lambda t: 0.5, 0.0)),
                ("distancing 40-100", make(lambda t: 0.3 if 40 <= t < 100 else 0.5, 0.0)),
                ("vaccination 1%/day", make(lambda t: 0.5, 0.01))):
    sol = solve_ivp(f, (0, 400), [N - 5, 0, 5, 0, 5], max_step=0.5, rtol=1e-8, atol=1e-6)
    print(f"{name:19s}: {sol.y[4][-1] / N:6.1%} of the town infected in total")
no intervention    :  89.3% of the town infected in total
distancing 40-100  :  86.6% of the town infected in total
vaccination 1%/day :  48.7% of the town infected in total

Distancing mainly delays and flattens the peak (useful for hospitals) but, once lifted, the epidemic resumes among the many remaining susceptibles. Vaccination reduces both the peak and the total, because it permanently lowers the susceptible fraction below the threshold 1R0\frac{1}{R_0} sooner.

Where to go next

  • Replace the deterministic model with a stochastic one (random infection events) and see how often a 5-case outbreak dies out by chance.
  • Add age groups: SS, EE, II, RR become vectors and β\beta a contact matrix, an SEIR system of linear-algebra size.
  • Estimate uncertainty: refit on many resampled data sets (a parametric bootstrap) and look at the spread of R0R_0.
  • Learn how solve_ivp itself works in Numerical Methods.

Test yourself

Why is a separate cumulative-infections variable needed to compare final sizes with vaccination?

  1. Because vaccination also moves people from SS to RR, so RR no longer counts only infections
  2. Because the model is stochastic
  3. Because NN changes
  4. It is not needed

Early in an outbreak, case counts mainly reveal…

  1. the final size
  2. the exponential growth rate
  3. the reporting rate
  4. the population size

Why are square roots of the counts fitted instead of the counts?

  1. To make the numbers smaller for printing
  2. Poisson noise grows like the square root of the mean, so this roughly equalizes the noise
  3. Square roots are required by least_squares
  4. To avoid negative counts