Create an SIR/SEIR fitting suite: identifiability, observation, and intervention effects.
- User
Create an SIR/SEIR fitting suite: identifiability, observation, and intervention effects.
Assistant
Create an SIR/SEIR fitting suite: identifiability, observation, and intervention effects.
The user wants an "SIR/SEIR fitting suite" that covers three key aspects:
This is a significant software engineering and mathematical modeling task. I need to provide a structured solution, likely in Python, that demonstrates these concepts. A single script might be too messy, so I should structure it as a modular suite or a comprehensive Jupyter Notebook-style explanation.
Key Components:
The Model (SIR/SEIR):
scipy.integrate.odeint or solve_ivp).Observation Model:
Parameter Estimation (Fitting):
emcee or pymc). This is best for "Identifiability" because it gives posterior distributions (correlations = non-identifiability).scipy.optimize.minimize for simplicity in a standalone script, but maybe add a note about Bayesian methods for identifiability analysis. Actually, for a "suite", showing MCMC is much better for identifiability. I will use a simple Metropolis-Hastings sampler or emcee if I assume the user can install it. To keep it self-contained and robust, I'll write a basic MLE approach first, but to truly demonstrate identifiability (structural vs. practical), I need to look at the Hessian or profile likelihoods.Decision: I will implement a class-based structure.
SIRModelObservationModelFitterIdentifiability Analysis:
Intervention Effects:
Structure of the Code:
numpy, scipy, matplotlib.dS/dt = -beta * S * I / NdI/dt = beta * S * I / N - gamma * IdR/dt = gamma * IRefining the Scope: Creating a production-ready suite is too big for one response. I will create a "Scientific Prototype" script. It will be a single, comprehensive Python file that acts as a tutorial and a functional tool.
Detailed Plan:
EpidemiologicalModel:
scipy.integrate.odeint.ScenarioGenerator:
ModelFitter:
scipy.optimize to find best params.Specific Code Details:
solve_ivp.Self-Correction during drafting:
Output Format: I will provide a complete, copy-pasteable Python script. I will organize it logically with comments explaining the math.
Drafting the "Identifiability" section: I need to explicitly mention that without good priors or fixing some parameters (like N), SIR models are often practically unidentifiable. I will show a covariance matrix.
Drafting the "Intervention" section: I will model as:
Let's assemble the response.
Dependencies: numpy, scipy, matplotlib.
Let's write the code mentally to check for bugs.
neg_log_likelihood(y_pred, y_obs):
If y_pred is 0, log explodes. Add epsilon.
fit():
Bounds are crucial. .
identifiability:
Compute Hessian inverse (Covariance matrix). Visualize correlation between and .
Okay, ready to generate. This is a complete Python suite designed for SIR/SEIR model fitting, specifically addressing the three pillars you requested: Structural Identifiability, Observation Noise/Models, and Intervention Effects (Time-Varying Parameters).
You can copy and paste this code into a single Python file (e.g., sir_suite.py) or a Jupyter Notebook.
You will need numpy, scipy, and matplotlib.
pip install numpy scipy matplotlib
In epidemiological models, Identifiability asks: "Given perfect data, can we uniquely recover the parameters?"
IdentifiabilityAnalyzer class performs a Sensitivity Analysis. It perturbs parameters by 1% and plots the change in the output curve. If a parameter changes and the output doesn't, that parameter is practically unidentifiable.Raw ODEs output continuous numbers (real numbers). Real-world data is discrete and noisy.
extract_incidence: Converts cumulative ODE states () into daily new cases (Incidence), which is what we actually report.poisson_neg_log_likelihood: A robust cost function that assumes the data represents counts. This results in better fits for the "tails" of the epidemic where case numbers are low.This is critical for policy making.
lockdown_intervention(t, beta). This function modifies the transmission rate at a specific time step ().import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.optimize import minimize, differential_evolution
from scipy.stats import poisson, nbinom
import warnings
# Suppress optional optimization warnings for cleaner output
warnings.filterwarnings("ignore")
# ==================================================
# 1. MODEL DEFINITION (SIR & SEIR + Interventions)
# ==================================================
class EpidemiologicalModel:
"""
A flexible class for SIR/SEIR models with time-varying transmission (interventions).
"""
def __init__(self, model_type='SIR'):
self.model_type = model_type
self.params_ = None
def _odes(self, y, t, params, intervention_fn=None):
S, I = y[0], y[1]
R = y[-1] # Works for both SIR (y[2]) and SEIR (y[3])
N = S + I + R # Assuming y has N components, simple sum here assumes no births/deaths
# Unpack params (optimized)
beta = params[0]
gamma = params[1]
# Handle Intervention: Modify Beta based on time
if intervention_fn is not None:
beta = intervention_fn(t, beta)
dSdt = -beta * S * I / N
if self.model_type == 'SIR':
dIdt = beta * S * I / N - gamma * I
dRdt = gamma * I
return [dSdt, dIdt, dRdt]
elif self.model_type == 'SEIR':
E = y[2]
sigma = params[2] # Incubation rate
dEdt = beta * S * I / N - sigma * E
dIdt = sigma * E - gamma * I
dRdt = gamma * I
return [dSdt, dEdt, dIdt, dRdt]
def simulate(self, t, initial_conditions, params, intervention_fn=None):
solution = odeint(self._odes, initial_conditions, t, args=(params, intervention_fn))
return solution
# ==================================================
# 2. OBSERVATION MODELS (Likelihoods)
# ==================================================
class ObservationModel:
"""
Handles how we map true states to observed data and calculate likelihoods.
"""
@staticmethod
def extract_incidence(solution, model_type):
""" Calculate daily new infections (incidence) from state solution. """
# Incidence is roughly beta * S * I / N.
# However, for fitting, we often use (S_t - S_{t-1}) if assuming no vital dynamics.
# Here we take the derivative of S (which is negative, so we flip it).
incidence = -np.diff(solution[:, 0])
# Add a 0 at start to match time vector length
return np.insert(incidence, 0, 0)
@staticmethod
def poisson_neg_log_likelihood(params, model, t, y_obs, initial_conditions, intervention_fn=None):
"""
Standard Poisson likelihood for count data.
Addresses 'Observation' component.
"""
try:
sol = model.simulate(t, initial_conditions, params, intervention_fn)
y_pred = ObservationModel.extract_incidence(sol, model.model_type)
# Enforce positivity to avoid log(0)
y_pred = np.maximum(y_pred, 1e-6)
# Poisson NLL: sum( y_pred - y_obs * log(y_pred) )
nll = np.sum(y_pred - y_obs * np.log(y_pred))
return nll
except Exception:
return 1e9 # Return large value if integration fails
@staticmethod
def gaussian_neg_log_likelihood(params, model, t, y_obs, initial_conditions, sigma=10, intervention_fn=None):
"""
Gaussian likelihood (Least Squares).
"""
try:
sol = model.simulate(t, initial_conditions, params, intervention_fn)
y_pred = ObservationModel.extract_incidence(sol, model.model_type)
# Gaussian NLL
residuals = (y_obs - y_pred)**2
nll = np.sum(residuals / (2 * sigma**2))
return nll
except Exception:
return 1e9
# ==================================================
# 3. IDENTIFIABILITY ANALYSIS
# ==================================================
class IdentifiabilityAnalyzer:
"""
Tools to check if parameters can be uniquely determined from data.
"""
@staticmethod
def check_sensitivity(model, t, params_true, initial_conditions, param_names, intervention_fn=None):
"""
Finite Difference Sensitivity Analysis.
Shows how much a small change in a parameter changes the model output.
If sensitivity is near 0 for a parameter, it is likely unidentifiable.
"""
print("\n--- Identifiability: Sensitivity Analysis ---")
# Get baseline incidence
sol_base = model.simulate(t, initial_conditions, params_true, intervention_fn)
inc_base = ObservationModel.extract_incidence(sol_base, model.model_type)
delta = 0.01 # 1% perturbation
results = {}
plt.figure(figsize=(10, 6))
plt.plot(t, inc_base, 'k--', label='Baseline', linewidth=2)
for i, name in enumerate(param_names):
params_perturbed = np.array(params_true, copy=True)
params_perturbed[i] = params_perturbed[i] * (1 + delta)
sol_pert = model.simulate(t, initial_conditions, params_perturbed, intervention_fn)
inc_pert = ObservationModel.extract_incidence(sol_pert, model.model_type)
# Calculate L2 norm of change
l2_change = np.linalg.norm(inc_pert - inc_base)
results[name] = l2_change
plt.plot(t, inc_pert, label=f'{name} +{delta*100}%')
plt.title('Identifiability: Parameter Perturbation Effect on Incidence')
plt.xlabel('Time')
plt.ylabel('Daily Incidence')
plt.legend()
plt.show()
# Print interpretability
print("Sensitivity Scores (L2 norm of output change):")
for k, v in results.items():
status = "IDENTIFIABLE" if v > 10 else "WEAK/UNIDENTIFIABLE"
print(f" {k}: {v:.2f} [{status}]")
# ==================================================
# 4. MAIN EXECUTION SUITE
# ==================================================
def run_fitting_suite():
# --- Configuration ---
N = 10000 # Population
days = 100 # Time horizon
t = np.linspace(0, days, days)
# True parameters (What nature knows, but we try to find)
# beta, gamma
true_params_sir = [0.4, 0.1]
# Initial conditions: S, I, R
I0 = 10
S0 = N - I0
R0 = 0
y0_sir = [S0, I0, R0]
# ---------------------------------------------------------
# PART A: Identifiability (Can we distinguish beta vs gamma?)
# ---------------------------------------------------------
print("*" * 60)
print("SECTION A: IDENTIFIABILITY ANALYSIS")
print("**"*20)
model_sir = EpidemiologicalModel('SIR')
analyzer = IdentifiabilityAnalyzer()
analyzer.check_sensitivity(
model=model_sir,
t=t,
params_true=true_params_sir,
initial_conditions=y0_sir,
param_names=['Beta', 'Gamma']
)
# ---------------------------------------------------------
# PART B: Observation Effects (Fitting with Noise)
# ---------------------------------------------------------
print("\n" + "*"*60)
print("SECTION B: OBSERVATION MODELS & FITTING")
print("**"*20)
# 1. Generate Synthetic Data (Nature)
true_sol = model_sir.simulate(t, y0_sir, true_params_sir)
true_incidence = ObservationModel.extract_incidence(true_sol, 'SIR')
# Add Observation Noise (Poisson noise on counts)
# This simulates imperfect reporting
np.random.seed(42)
observed_incidence = poisson.rvs(true_incidence)
plt.figure(figsize=(10, 5))
plt.plot(t, true_incidence, label='True Incidence (Hidden)', color='blue', alpha=0.5)
plt.scatter(t, observed_incidence, label='Observed Incidence (Data)', color='red', s=10, alpha=0.6)
plt.title("Synthetic Data Generation (Observation Process)")
plt.legend()
plt.show()
# 2. Fitting (Optimization)
# We define an intervention function (null for now) to pass
def no_intervention(t, beta): return beta
print("Fitting SIR model to noisy data...")
# Bounds for optimization: beta (0, 1), gamma (0, 1)
bounds = [(0.01, 1.0), (0.01, 0.5)]
result = differential_evolution(
ObservationModel.poisson_neg_log_likelihood,
bounds,
args=(model_sir, t, observed_incidence, y0_sir, no_intervention),
strategy='best1bin',
maxiter=200,
polish=True
)
fitted_params = result.x
print(f"True Params: Beta={true_params_sir[0]:.4f}, Gamma={true_params_sir[1]:.4f}")
print(f"Fitted Params: Beta={fitted_params[0]:.4f}, Gamma={fitted_params[1]:.4f}")
# Visualize Fit
fitted_sol = model_sir.simulate(t, y0_sir, fitted_params)
fitted_inc = ObservationModel.extract_incidence(fitted_sol, 'SIR')
plt.figure(figsize=(10, 5))
plt.scatter(t, observed_incidence, label='Data', color='red', s=10, alpha=0.3)
plt.plot(t, true_incidence, label='True Curve', color='green', linewidth=2)
plt.plot(t, fitted_inc, label='Fitted Curve', color='black', linestyle='--', linewidth=2)
plt.title("Maximum Likelihood Fit (Poisson Likelihood)")
plt.legend()
plt.show()
# ---------------------------------------------------------
# PART C: Intervention Effects (Time-Varying Beta)
# ---------------------------------------------------------
print("\n" + "*"*60)
print("SECTION C: INTERVENTION EFFECTS (Lockdown)")
print("**"*20)
# 1. Define an Intervention: Beta drops by 50% after day 30
lockdown_day = 30
reduction_factor = 0.5
def lockdown_intervention(t, beta):
if t < lockdown_day:
return beta
else:
return beta * reduction_factor
# 2. Simulate "Real" Scenario with Intervention
int_sol = model_sir.simulate(t, y0_sir, true_params_sir, intervention_fn=lockdown_intervention)
int_incidence = ObservationModel.extract_incidence(int_sol, 'SIR')
observed_int_incidence = poisson.rvs(int_incidence) # Add noise
# 3. The Trap: Fit a STANDARD model (no intervention logic) to this data
# If we ignore the intervention, our parameter estimates will be garbage averages.
print("Fitting standard SIR to data with unmodeled intervention...")
result_bad = differential_evolution(
ObservationModel.poisson_neg_log_likelihood,
bounds,
args=(model_sir, t, observed_int_incidence, y0_sir, no_intervention), # Note: No intervention in model
maxiter=200
)
bad_params = result_bad.x
# 4. Fit the CORRECT model (with intervention logic)
# We need to optimize Beta, Gamma, AND Lockdown_Day/Strength (or assume known day)
print("Fitting Intervention-Aware SIR...")
# We wrap the optimizer to include the intervention parameters
def fit_with_intervention(params_core):
# Assume we know lockdown day (30) and strength (0.5), or fit them.
# Here we just reuse the lockdown_intervention fn.
return ObservationModel.poisson_neg_log_likelihood(params_core, model_sir, t, observed_int_incidence, y0_sir, lockdown_intervention)
result_good = differential_evolution(fit_with_intervention, bounds, maxiter=200)
good_params = result_good.x
print(f"True Params: Beta={true_params_sir[0]:.3f}, Gamma={true_params_sir[1]:.3f}")
print(f"Naive Fit: Beta={bad_params[0]:.3f}, Gamma={bad_params[1]:.3f} (Biased)")
print(f"Intervention Fit: Beta={good_params[0]:.3f}, Gamma={good_params[1]:.3f} (Recovered)")
# Visualize
bad_sol = model_sir.simulate(t, y0_sir, bad_params, no_intervention)
bad_inc = ObservationModel.extract_incidence(bad_sol, 'SIR')
good_sol = model_sir.simulate(t, y0_sir, good_params, lockdown_intervention)
good_inc = ObservationModel.extract_incidence(good_sol, 'SIR')
plt.figure(figsize=(12, 6))
plt.scatter(t, observed_int_incidence, label='Observed Data (with Lockdown)', color='gray', s=10, alpha=0.5)
plt.axvline(x=lockdown_day, color='red', linestyle=':', label='Intervention Start')
plt.plot(t, int_incidence, label='True Dynamics', color='Green', linewidth=3, alpha=0.5)
plt.plot(t, bad_inc, label='Naive Fit (Single Beta)', color='Blue', linestyle='--')
plt.plot(t, good_inc, label='Intervention Fit', color='Orange', linestyle='-', linewidth=2)
plt.title("Impact of Ignoring Interventions on Parameter Fitting")
plt.legend()
plt.show()
if __name__ == "__main__":
run_fitting_suite()