---
id: wiki-2026-0508-epidemiological-modeling
title: Epidemiological Modeling
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [SIR model, SEIR, compartmental model, disease modeling, R0, agent-based epi]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
verification_status: applied
tags: [epidemiology, modeling, sir, public-health, simulation, forecasting, covid]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: Python
  framework: scipy / NetworkX / Mesa / NumPyro
---

# Epidemiological Modeling

## 매 한 줄
> **"매 disease 의 population 의 spread 의 model"**. 매 SIR / SEIR (compartmental), 매 ABM (network), 매 statistical (R_t estimate). 매 R0, herd immunity, 매 NPI effect. 매 modern: 매 ML forecasting + 매 mobility data + 매 Bayesian inference.

## 매 핵심

### 매 compartmental
- **SIR**: Susceptible → Infected → Recovered.
- **SEIR**: + Exposed.
- **SIRS**: 매 immunity 의 wane.
- **SIRD**: + Dead.
- **MSEIR**: + Maternal immunity.

### 매 key parameter
- **R0**: 매 basic reproduction number.
- **R_t**: 매 effective (time-varying).
- **β**: 매 transmission rate.
- **γ**: 매 recovery rate.
- **R0 = β / γ**.
- **Herd immunity**: 매 1 - 1/R0.

### 매 method
- **ODE**: 매 mean-field, deterministic.
- **Stochastic** (Gillespie): 매 small population.
- **ABM**: 매 individual + network.
- **Statistical**: 매 R_t from cases.
- **ML / DL**: 매 forecasting.

### 매 응용
1. **Pandemic forecast**: 매 COVID, flu.
2. **Vaccination strategy**: 매 priority.
3. **NPI effect**: 매 lockdown, mask.
4. **Travel ban**: 매 border.
5. **Hospital capacity**: 매 ICU.
6. **Animal**: 매 livestock disease.

## 💻 패턴

### SIR (ODE)
```python
import numpy as np
from scipy.integrate import odeint

def sir(state, t, beta, gamma, N):
    S, I, R = state
    dS = -beta * S * I / N
    dI = beta * S * I / N - gamma * I
    dR = gamma * I
    return [dS, dI, dR]

t = np.linspace(0, 200, 1000)
N = 1_000_000
sol = odeint(sir, [N - 1, 1, 0], t, args=(0.4, 0.1, N))
```

### SEIR
```python
def seir(state, t, beta, sigma, gamma, N):
    S, E, I, R = state
    dS = -beta * S * I / N
    dE = beta * S * I / N - sigma * E
    dI = sigma * E - gamma * I
    dR = gamma * I
    return [dS, dE, dI, dR]
```

### Stochastic Gillespie
```python
def gillespie_sir(N, I0, beta, gamma, t_max=200):
    S, I, R = N - I0, I0, 0
    t = 0
    history = [(0, S, I, R)]
    while I > 0 and t < t_max:
        a1 = beta * S * I / N  # 매 infection rate
        a2 = gamma * I         # 매 recovery rate
        a0 = a1 + a2
        if a0 == 0: break
        tau = np.random.exponential(1 / a0)
        t += tau
        if np.random.rand() < a1 / a0:
            S -= 1; I += 1
        else:
            I -= 1; R += 1
        history.append((t, S, I, R))
    return history
```

### R_t estimation (EpiEstim-style)
```python
def estimate_rt(case_counts, gen_time=5, window=7):
    """매 simple Cori method approximation."""
    rt = []
    for t in range(window, len(case_counts)):
        recent = case_counts[t - window:t]
        infectees = sum(recent[-(window - i)] * np.exp(-(window - i) / gen_time) for i in range(window))
        rt.append(case_counts[t] / max(infectees, 1))
    return rt
```

### Network ABM (NetworkX)
```python
import networkx as nx
import random

def network_sir(G, beta=0.1, gamma=0.05, init_infected=5, steps=100):
    state = {n: 'S' for n in G.nodes()}
    for n in random.sample(list(G.nodes()), init_infected): state[n] = 'I'
    
    history = []
    for _ in range(steps):
        new_state = state.copy()
        for n in G.nodes():
            if state[n] == 'I':
                if random.random() < gamma: new_state[n] = 'R'
                for nb in G.neighbors(n):
                    if state[nb] == 'S' and random.random() < beta:
                        new_state[nb] = 'I'
        state = new_state
        history.append({'S': sum(1 for v in state.values() if v == 'S'),
                        'I': sum(1 for v in state.values() if v == 'I'),
                        'R': sum(1 for v in state.values() if v == 'R')})
    return history

G = nx.barabasi_albert_graph(1000, 3)
hist = network_sir(G)
```

### Vaccination intervention
```python
def vaccinate(G, strategy='degree', frac=0.3):
    n = int(G.number_of_nodes() * frac)
    if strategy == 'degree':
        targets = sorted(G.nodes(), key=G.degree, reverse=True)[:n]
    elif strategy == 'random':
        targets = random.sample(list(G.nodes()), n)
    elif strategy == 'betweenness':
        bc = nx.betweenness_centrality(G)
        targets = sorted(bc, key=bc.get, reverse=True)[:n]
    return set(targets)
```

### Bayesian SIR (NumPyro)
```python
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist

def bayesian_sir(observed_cases, N):
    beta = numpyro.sample('beta', dist.Uniform(0.1, 1.0))
    gamma = numpyro.sample('gamma', dist.Uniform(0.05, 0.3))
    sigma_obs = numpyro.sample('sigma', dist.HalfNormal(10))
    
    # 매 simulate SIR (deterministic given params)
    predicted = simulate_sir_jax(beta, gamma, N, len(observed_cases))
    numpyro.sample('obs', dist.Normal(predicted, sigma_obs), obs=observed_cases)
```

### Mobility-aware (commute)
```python
def metapopulation_sir(populations, mobility, beta, gamma):
    """매 multi-region 의 commute matrix."""
    n = len(populations)
    S = populations.copy()
    I = np.zeros(n); I[0] = 10
    R = np.zeros(n)
    for _ in range(200):
        # 매 effective infectious in each region with commuters
        I_eff = mobility @ I
        new_I = beta * S * I_eff / populations
        new_R = gamma * I
        S -= new_I; I += new_I - new_R; R += new_R
    return S, I, R
```

### NPI effect (intervention)
```python
def sir_with_npi(t, beta, gamma, lockdown_start, lockdown_end, lockdown_factor=0.3):
    if lockdown_start <= t <= lockdown_end:
        beta = beta * lockdown_factor
    return beta, gamma
```

### Forecast (ML over compartmental)
```python
import xgboost as xgb

def forecast_cases(history, window=14, horizon=7):
    """매 ML residual on top of SIR."""
    sir_pred = sir_simulate(history)
    residuals = history - sir_pred
    
    X = sliding_window(residuals, window)
    y = residuals[window:window + len(X)]
    model = xgb.XGBRegressor().fit(X, y)
    
    return sir_pred[-horizon:] + model.predict(X[-1:])[:horizon]
```

## 매 결정 기준
| 상황 | Approach |
|---|---|
| Quick estimate | SIR ODE |
| Latency disease | SEIR |
| Small outbreak | Gillespie stochastic |
| Network spread | ABM on graph |
| Real-time R_t | Cori / EpiEstim |
| Forecast | Compartmental + ML residual |
| Spatial | Metapopulation + mobility |

**기본값**: 매 SEIR baseline + 매 Bayesian inference + 매 mobility data + 매 ML residual + 매 NPI scenario analysis.

## 🔗 Graph
- 변형: [[SEIR]] · [[Compartmental-Model]]
- Adjacent: [[Bayesian-Inference]]

## 🤖 LLM 활용
**언제**: 매 outbreak. 매 vaccination plan. 매 hospital capacity.
**언제 X**: 매 individual diagnosis (different domain).

## ❌ 안티패턴
- **R0 의 over-trust**: 매 heterogeneity 의 ignore.
- **Mean-field at small scale**: 매 stochastic 의 use.
- **No data calibration**: 매 toy.
- **Forecast far horizon**: 매 uncertainty 의 hide.
- **Single model**: 매 ensemble 의 prefer.

## 🧪 검증 / 중복
- Verified (Anderson & May, Cori 2013, COVID-19 modeling literature).
- 신뢰도 A.

## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-04-20 | Auto-reinforced |
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — SIR / SEIR / Gillespie / ABM / Bayes / NPI code |
