Modelcore
Stochastic SIR model
Also called general stochastic epidemic.
The continuous-time Markov chain version of SIR, with infection rate beta S I / N and recovery rate gamma I, simulated exactly by Gillespie.
The stochastic SIR model, also called the general stochastic epidemic, is the SIR epidemic as a Markov chain in continuous time. The state counts the susceptible, infectious and removed people of a closed population. Each infectious person meets others at random times, and each such meeting with a susceptible is a new infection. Each infectious person recovers after an exponential time. The model keeps the chance events that the Kermack-McKendrick equations average away. So it answers questions that the deterministic model cannot: the probability that one case starts a large outbreak, the spread of the final size, and the chance that the disease dies out early. Gillespie's direct method simulates it exactly.
The machine
The state. , the numbers of susceptible and infectious people, in a population of fixed size . The number of removed people is . The state space is , and every state with is absorbing.
The parameters. The contact rate and the recovery rate . The basic reproduction number is : a case is infectious for a mean time and makes contacts at rate , each with a person chosen uniformly from the population.
The transitions. From the state :
| event | change | rate |
|---|---|---|
| infection | ||
| recovery |
This is the frequency-dependent form: the rate of contacts per case does not grow with . The holding time in a state is exponential with the total rate , and the next event is an infection with probability
The assumptions. The population is closed and mixes homogeneously. A recovered person is immune for good. The infectious period is exponential with rate , so a case has no memory of how long it has been infectious. There is no latent period. Each of these can be changed, but then the process is no longer a Markov chain on alone.
A simulation. The direct method draws the time to the next event and then the type of the event.
SIR-DIRECT(N, S0, I0, β, γ, T)- 1
t ← 0, S ← S0, I ← I0 - 2
while I > 0 do - 3
a_inf ← β S I / N, a_rec ← γ I, a0 ← a_inf + a_rec - 4
t ← t + Exponential(a0) - 5
if t > T then stop - 6
if Uniform(0, a0) < a_inf then S ← S - 1, I ← I + 1 - 7
else I ← I - 1 - 8
record (t, S, I)
Each event lowers by one, so a run has at most events and costs time. The implementation draws its random numbers in the same order as the generic ssa_direct of the shared helper, and with the same seed both give the same path.
A worked example: three people. Take , one case, two susceptibles and . The first event is an infection with probability . If it is a recovery, no one else is infected. If it is an infection, the state is , and the next event is an infection with probability . Going on in this way gives the exact final size law , and .
A worked example: twenty people. With , one case and , the probability that the first case recovers before it infects anyone is . The exact final size law falls to at 8 infections and rises again to a second peak of at 15. With seed 4, the implementation draws a run whose first events are infections at times 0.115, 0.229 and 0.240, and 9 people are infected in total. With seeds 1, 2 and 5 the first case recovers first. In a population of with and seed 4, the run infects 794 people, the number of cases peaks at 143, and the last recovery is at time 19.5 (in units of the mean infectious period).
What it counts
- The final size, . Its exact law follows from the embedded jump chain above, by a pass over the states in decreasing order of .
- The probability of a minor outbreak in a large population, about when .
- The epidemic curve , its peak, and the duration of the outbreak.
- The likelihood of an observed epidemic. For a fully observed path, the likelihood is a product of the event rates times . This is the basis of data augmentation MCMC when the infection times are not observed.
Relation to other models
- Kermack-McKendrick SIR model. If with and fixed, the fractions and converge on any finite time interval to the solution of , . This is Kurtz's law of large numbers for density dependent jump Markov processes (Andersson and Britton, chapter 5). The fluctuations around the limit are of order .
- Birth-death process and Galton-Watson process. While , each case infects at rate and recovers at rate , independently of the others. That is a linear birth-death process, and counted by generations it is a Galton-Watson process with geometric offspring of mean . Andersson and Britton (chapter 3) couple the two processes so that they agree until a number of cases that grows with .
- Reed-Frost model. The same model with a fixed infectious period in place of the exponential one. Its final size law is that of a continuous-time SIR model with a fixed infectious period.
- Chemical master equation. The forward equation of the chain is the master equation of the reaction network , . Methods for reaction networks, such as tau-leaping, apply to the model without change.
- Other compartments. The SIS and SEIR models have stochastic versions built in the same way. In the SIS version there are no removed people, and in a finite population the disease always dies out in the end, but the expected time to extinction grows exponentially with when .
Known results in the model
The threshold theorem. Let with fixed. If , the number of infections stays bounded in probability: every outbreak is minor. If , the probability of a minor outbreak tends to , the extinction probability of the birth-death process that starts with individuals. Whittle (1955) gave this result through a comparison with birth-death processes, and Andersson and Britton (chapter 4) prove it as the threshold limit theorem. For , the exact probability of at most 100 infections is for and one case (limit ), for three cases (limit ), and for and one case (limit ).
Exponential and fixed infectious periods differ. The probability of a minor outbreak from one case is for an exponential infectious period. For a fixed infectious period, the offspring law is Poisson(), and the probability is the smallest root of , which is at , against here. So the variance of the infectious period matters for the early phase. It does not matter for the deterministic final size.
The size of a major outbreak. Given a major outbreak, the final fraction infected tends to the root of the final size relation , for any law of the infectious period with mean . For , . The number infected is approximately normal around , with a variance of order that depends on the variance of the infectious period (Andersson and Britton, chapter 4).
The Sellke construction. Give each susceptible an independent threshold , exponential with mean 1, and order the people by their thresholds. Person is infected when the total infection pressure first passes . This builds the same process, and it shows that the final size depends on the infectious periods only through their sum over the people infected. The final size is then the smallest for which the -th smallest threshold is larger than times the total infectious time of the first cases plus the initial ones. The construction gives the final size law without the timing (Andersson and Britton, chapter 2).
The duration. A major outbreak lasts a time of order : about to grow, and another time of order to fade out at the end. A minor outbreak lasts a time of order 1.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the biology pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Random variates, exact probability mass functions and test helpers for
the stochastic pages of the biology area.
Every sampler takes a random.Random object as its first argument and never
uses the module-level random functions. Each sampler draws its random
numbers in the order that its docstring gives, so two runs with the same
seed give the same output.
Conventions:
- A reaction network with n species and m reactions is given by `stoich`, a
list of the m change vectors nu_1, ..., nu_m. So stoich[j][i] is the entry
S[i][j] of the n by m stoichiometric matrix S.
- `propensity(x)` takes the state as a tuple of n integer counts and returns
the m propensities a_1(x), ..., a_m(x) as a sequence of floats >= 0.
- nbinom_pmf uses the mean mu and the dispersion alpha, with
Var = mu + alpha mu^2. The size is r = 1 / alpha; alpha = 0 is Poisson.
- hypergeom_pmf(k, total, good, draws) is the probability of k good items
in `draws` draws without replacement from `total` items of which `good`
are good.
Requires Python 3.12 or later (random.Random.binomialvariate).
"""
from __future__ import annotations
import math
from statistics import NormalDist
from typing import Callable, List, Sequence, Tuple
State = Tuple[int, ...]
_POISSON_PART = 30.0
# Random variates
def poisson(rng, lam: float) -> int:
"""A Poisson(lam) variate.
For lam <= 30, inversion of the cumulative distribution with one
rng.random() draw. For lam > 30, the sum of p = ceil(lam / 30)
independent Poisson(lam / p) variates, drawn one after the other by
inversion (one rng.random() draw each).
"""
if lam < 0 or math.isnan(lam):
raise ValueError("lam must be >= 0")
if lam == 0:
return 0
if lam > _POISSON_PART:
parts = math.ceil(lam / _POISSON_PART)
part = lam / parts
return sum(_poisson_inversion(rng, part) for _ in range(parts))
return _poisson_inversion(rng, lam)
def _poisson_inversion(rng, lam: float) -> int:
u = rng.random()
k = 0
p = math.exp(-lam)
cdf = p
while u >= cdf:
k += 1
p *= lam / k
if p == 0.0:
# Rounding left u above the computed total mass; stop at the tail.
break
cdf += p
return k
def binomial(rng, n: int, p: float) -> int:
"""A Binomial(n, p) variate by rng.binomialvariate (one call)."""
if n < 0 or not 0.0 <= p <= 1.0:
raise ValueError("need n >= 0 and 0 <= p <= 1")
if n == 0 or p == 0.0:
return 0
if p == 1.0:
return n
return rng.binomialvariate(n, p)
def multinomial(rng, n: int, probs: Sequence[float]) -> List[int]:
"""A Multinomial(n, probs) vector by conditional binomials.
probs are weights >= 0 with a positive sum; they need not sum to 1. Cell
i gets Binomial(rest of n, probs[i] / rest of the weight), for i in
order; the last cell with positive weight gets the rest.
"""
if n < 0:
raise ValueError("n must be >= 0")
w = [float(q) for q in probs]
if any(q < 0 for q in w):
raise ValueError("weights must be >= 0")
total = sum(w)
if total <= 0:
raise ValueError("weights must have a positive sum")
last = max(i for i, q in enumerate(w) if q > 0)
out = [0] * len(w)
left = n
rest = total
for i in range(last):
if left == 0:
break
if w[i] == 0:
continue
x = binomial(rng, left, min(1.0, w[i] / rest))
out[i] = x
left -= x
rest -= w[i]
out[last] += left
return out
def categorical(rng, weights: Sequence[float]) -> int:
"""An index i with probability weights[i] / sum(weights).
One draw u = rng.random() * sum(weights), then a cumulative search from
index 0. Indices with weight 0 are never returned.
"""
total = 0.0
for w in weights:
if w < 0:
raise ValueError("weights must be >= 0")
total += w
if total <= 0:
raise ValueError("weights must have a positive sum")
u = rng.random() * total
acc = 0.0
last = -1
for i, w in enumerate(weights):
if w > 0:
acc += w
last = i
if u < acc:
return i
return last
def ssa_direct(rng, x0: Sequence[int], stoich: Sequence[Sequence[int]],
propensity: Callable[[State], Sequence[float]], t_end: float,
max_events: int = 10 ** 6):
"""Gillespie's direct method from state x0 at time 0 up to time t_end.
Each step computes a = propensity(x) and a0 = sum(a). If a0 = 0 the run
stops. Otherwise it draws tau = rng.expovariate(a0) first. If
t + tau > t_end the run stops, and no second number is drawn. Else it
draws u = rng.random() * a0 and fires the first reaction j with
a_1 + ... + a_j > u (a linear search), then adds stoich[j] to x.
Returns (times, states, complete). times[0] = 0.0 and states[0] =
tuple(x0); entry k > 0 is the time and the state just after event k.
The state at t_end is states[-1]. complete is False only when the run
stopped because max_events events had fired before t_end.
"""
x = tuple(int(v) for v in x0)
times = [0.0]
states = [x]
t = 0.0
m = len(stoich)
for _ in range(max_events):
a = propensity(x)
a0 = 0.0
for v in a:
if v < 0:
raise ValueError("propensities must be >= 0")
a0 += v
if a0 <= 0.0:
return times, states, True
t += rng.expovariate(a0)
if t > t_end:
return times, states, True
u = rng.random() * a0
acc = 0.0
j = -1
for i in range(m):
if a[i] > 0:
acc += a[i]
j = i
if u < acc:
break
nu = stoich[j]
x = tuple(x[i] + nu[i] for i in range(len(x)))
times.append(t)
states.append(x)
return times, states, False
# Sample statistics and test helpers
def mean_var(xs) -> Tuple[float, float]:
"""The mean and the unbiased sample variance (divisor n - 1) by the
Welford method. The variance is 0.0 for fewer than two values."""
n = 0
mean = 0.0
m2 = 0.0
for x in xs:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
if n == 0:
raise ValueError("empty sample")
return mean, (m2 / (n - 1) if n > 1 else 0.0)
def check_mean(m: float, mu: float, var: float, n: int, z: float = 4.0) -> bool:
"""True when |m - mu| <= z sqrt(var / n): a sample mean m of n
independent values with exact mean mu and exact variance var."""
return abs(m - mu) <= z * math.sqrt(var / n)
# Exact probability mass functions
def log_choose(n: int, k: int) -> float:
"""ln C(n, k), or -inf when k < 0 or k > n."""
if k < 0 or k > n:
return -math.inf
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def binom_pmf(k: int, n: int, p: float) -> float:
"""P(K = k) for K ~ Binomial(n, p)."""
if k < 0 or k > n:
return 0.0
if p == 0.0:
return 1.0 if k == 0 else 0.0
if p == 1.0:
return 1.0 if k == n else 0.0
return math.exp(log_choose(n, k) + k * math.log(p) + (n - k) * math.log1p(-p))
def poisson_pmf(k: int, lam: float) -> float:
"""P(K = k) for K ~ Poisson(lam)."""
if k < 0:
return 0.0
if lam == 0:
return 1.0 if k == 0 else 0.0
return math.exp(k * math.log(lam) - lam - math.lgamma(k + 1))
def nbinom_pmf(k: int, mu: float, alpha: float) -> float:
"""P(K = k) for the negative binomial with mean mu and Var = mu + alpha mu^2."""
if k < 0:
return 0.0
if alpha == 0:
return poisson_pmf(k, mu)
if mu == 0:
return 1.0 if k == 0 else 0.0
r = 1.0 / alpha
return math.exp(math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
+ r * math.log(r / (r + mu)) + k * math.log(mu / (r + mu)))
def hypergeom_pmf(k: int, total: int, good: int, draws: int) -> float:
"""P(K = k) for k good items in `draws` draws without replacement from
`total` items of which `good` are good."""
if k < 0 or k > good or draws - k < 0 or draws - k > total - good:
return 0.0
return math.exp(log_choose(good, k) + log_choose(total - good, draws - k)
- log_choose(total, draws))
def logsumexp(xs) -> float:
"""ln(sum of exp(x)) without overflow; -inf for an empty input."""
xs = list(xs)
if not xs:
return -math.inf
top = max(xs)
if top == -math.inf:
return -math.inf
if top == math.inf:
return math.inf
return top + math.log(sum(math.exp(x - top) for x in xs))
# Tail probabilities
def _gamma_q(a: float, x: float) -> float:
"""The regularized upper incomplete gamma function Q(a, x)."""
if a <= 0:
raise ValueError("a must be > 0")
if x <= 0:
return 1.0
log_front = -x + a * math.log(x) - math.lgamma(a)
if x < a + 1.0:
# Series for P(a, x).
ap = a
term = 1.0 / a
total = term
for _ in range(100000):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * 1e-16:
break
return max(0.0, 1.0 - total * math.exp(log_front))
# Continued fraction for Q(a, x), by the modified Lentz method.
tiny = 1e-300
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 100000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < tiny:
d = tiny
c = b + an / c
if abs(c) < tiny:
c = tiny
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-16:
break
return math.exp(log_front) * h
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for X chi-squared with df degrees of freedom."""
if df <= 0:
raise ValueError("df must be > 0")
if x <= 0:
return 1.0
return _gamma_q(df / 2.0, x / 2.0)
_STD_NORMAL = NormalDist()
def normal_sf(x: float, mu: float = 0.0, sigma: float = 1.0) -> float:
"""P(X > x) for X ~ Normal(mu, sigma^2), by statistics.NormalDist."""
return _STD_NORMAL.cdf(-(x - mu) / sigma)
stochastic_sir_model.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-sir-model/. The authors are listed in prov/EFGZYZ.jsonl.
"""The general stochastic epidemic: the Markov SIR model in continuous time.
The state is (S, I) in a population of N, with R = N - S - I. Infection
(S, I) -> (S - 1, I + 1) has rate beta S I / N, and recovery
(S, I) -> (S, I - 1) has rate gamma I. R0 = beta / gamma.
simulate is Gillespie's direct method written out for this model. It draws
its random numbers in the same order as biostoch.ssa_direct with the
reactions (infection, recovery), so with the same seed both give the same
path. final_size_distribution is exact: it runs over the embedded jump
chain, where the next event is an infection with probability
R0 S / (R0 S + N).
"""
from __future__ import annotations
from typing import Dict, List, Tuple
STOICH = [(-1, 1), (0, -1)]
def propensity(beta: float, gamma: float, n: int):
"""The rates (beta S I / N, gamma I) as a function of the state (S, I)."""
return lambda x: (beta * x[0] * x[1] / n, gamma * x[1])
def simulate(rng, n: int, s0: int, i0: int, beta: float, gamma: float,
t_end: float = float("inf")) -> Tuple[List[float], List[Tuple[int, int]]]:
"""One path: the event times and the states (S, I) just after them.
Draw order: per event, rng.expovariate(a0) for the waiting time, then
rng.random() to choose the event. The run stops when I = 0 or when the
next event would come after t_end.
"""
t, s, i = 0.0, s0, i0 # @line L1
times, states = [t], [(s, i)]
while i > 0: # @line L2
a_inf = beta * s * i / n # @line L3
a_rec = gamma * i
a0 = a_inf + a_rec
t += rng.expovariate(a0) # @line L4
if t > t_end: # @line L5
break
if rng.random() * a0 < a_inf: # @line L6
s, i = s - 1, i + 1
else: # @line L7
i -= 1
times.append(t) # @line L8
states.append((s, i))
return times, states
def final_size(states: List[Tuple[int, int]]) -> int:
"""The number of infections during the run: S_0 - S_end."""
return states[0][0] - states[-1][0]
def final_size_distribution(n: int, s0: int, i0: int, r0,
max_size: int | None = None) -> Dict[int, object]:
"""The exact law of the final size by the embedded jump chain.
Each event lowers 2S + I by one, so the states are visited level by
level. With max_size set, states with more than max_size infections are
dropped, and the returned masses are P(final size = k) for k <= max_size.
With r0 a fractions.Fraction, the result is exact.
"""
if max_size is None:
max_size = s0
levels: Dict[int, Dict[Tuple[int, int], object]] = {2 * s0 + i0: {(s0, i0): 1 + 0 * r0}}
out: Dict[int, object] = {}
for level in range(2 * s0 + i0, -1, -1):
for (s, i), w in levels.pop(level, {}).items():
if i == 0:
out[s0 - s] = out.get(s0 - s, 0 * r0) + w
continue
p_inf = r0 * s / (r0 * s + n)
nxt = levels.setdefault(level - 1, {})
if s > 0 and s0 - s + 1 <= max_size:
key = (s - 1, i + 1)
nxt[key] = nxt.get(key, 0 * r0) + w * p_inf
key = (s, i - 1)
nxt[key] = nxt.get(key, 0 * r0) + w * (1 - p_inf)
return dict(sorted(out.items()))
test_stochastic_sir_model.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stochastic-sir-model/. The authors are listed in prov/EFGZYZ.jsonl.
import random
from fractions import Fraction as F
from biostoch import check_mean, chi2_sf, ssa_direct
from stochastic_sir_model import STOICH, final_size, final_size_distribution, propensity, simulate
def test_exact_final_size_small():
# N = 3, one case, R0 = 2: the first event is an infection with
# probability 2 * 2 / (2 * 2 + 3) = 4/7.
d = final_size_distribution(3, 2, 1, F(2))
assert d == {0: F(3, 7), 1: F(36, 175), 2: F(64, 175)}
def test_exact_law_sums_to_one():
for n, i0, r0 in ((6, 1, F(3, 2)), (8, 2, F(1, 2)), (10, 1, F(4))):
d = final_size_distribution(n, n - i0, i0, r0)
assert sum(d.values()) == 1
assert set(d) <= set(range(n - i0 + 1))
def test_same_path_as_ssa_direct():
for seed in (1, 4, 9):
_, ours = simulate(random.Random(seed), 50, 48, 2, 1.8, 1.0)
_, ref, complete = ssa_direct(random.Random(seed), (48, 2), STOICH,
propensity(1.8, 1.0, 50), float("inf"))
assert complete and ours == ref
def test_simulated_final_size_matches_exact_law():
rng = random.Random(20261118)
n, runs, beta, gamma = 20, 3000, 1.5, 1.0
exact = final_size_distribution(n, n - 1, 1, beta / gamma)
counts = [0] * n
for _ in range(runs):
_, states = simulate(rng, n, n - 1, 1, beta, gamma)
counts[final_size(states)] += 1
stat = sum((counts[k] - runs * exact[k]) ** 2 / (runs * exact[k]) for k in range(n))
assert chi2_sf(stat, n - 1) > 0.001
def test_minor_outbreak_probability_near_one_over_r0_power():
# Truncate at N / 10 infections: the rest of the mass is a major outbreak.
for n, r0, i0, approx in ((1000, 2.0, 1, 0.5), (1000, 2.0, 3, 0.125), (1000, 1.5, 1, 2 / 3)):
minor = sum(final_size_distribution(n, n - i0, i0, r0, max_size=n // 10).values())
assert minor > approx and minor - approx < 0.01
def test_simulated_minor_outbreak_frequency():
rng = random.Random(3)
n, runs, cut = 200, 1500, 20
exact = sum(final_size_distribution(n, n - 1, 1, 2.0, max_size=cut).values())
minor = 0
for _ in range(runs):
_, states = simulate(rng, n, n - 1, 1, 2.0, 1.0)
minor += final_size(states) <= cut
assert check_mean(minor / runs, exact, exact * (1 - exact), runs)
def test_t_end_stops_the_run():
times, states = simulate(random.Random(2), 100, 99, 1, 3.0, 1.0, t_end=1.0)
assert times[-1] <= 1.0
assert all(s + i <= 100 for s, i in states)
References
- P. Whittle, The outcome of a stochastic epidemic, a note on Bailey's paper, Biometrika 42, 1955, pages 116 to 122 (the probability of a minor outbreak through a comparison with birth-death processes)
- Hakan Andersson and Tom Britton, Stochastic Epidemic Models and Their Statistical Analysis, Lecture Notes in Statistics 151, Springer, 2000, Chapter 2 (the standard SIR epidemic model), Chapter 3 (coupling with a branching process), Chapter 4 (the threshold limit theorem) and Chapter 5 (density dependent jump Markov processes and the deterministic limit)
- Matt J. Keeling and Pejman Rohani, Modeling Infectious Diseases in Humans and Animals, Princeton University Press, 2008, the chapter on stochastic dynamics (event-driven simulation of the SIR model and the extinction of small outbreaks)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag EFGZYZ Edit this page History Report an error Markdown