Build a hydrologic model calibration: objective functions, parameter identifiability,…
- User
Build a hydrologic model calibration: objective functions, parameter identifiability, multi‑site constraints, and GLUE/Bayesian methods.
Assistant
Build a hydrologic model calibration: objective functions, parameter identifiability, multi‑site constraints, and GLUE/Bayesian methods.
The user wants to "Build a hydrologic model calibration." This is a broad request, likely asking for a conceptual framework, code examples, or a step-by-step guide on how to implement a calibration system for a hydrologic model. The specific keywords are:
Target Audience: Likely a hydrologist, water resources engineer, or student/researcher familiar with concepts but needing a practical implementation guide or a structured overview of how these pieces fit together.
Structure of the Response:
emcee or pymc), but writing a full MCMC from scratch in a single chat might be too dense. I'll provide a simplified Metropolis-Hastings implementation.Code Choice: Python is the standard. I'll use numpy, scipy, and matplotlib.
Drafting the Content - Step-by-Step:
Model: I need a dummy hydrologic model. A simple bucket model (Linear Reservoir or ABC model) is best to keep the focus on calibration, not model physics. Let's use a simple 2-parameter bucket: and .
Refining the Plan: I will structure this as a tutorial. I will write a Python script that:
Self-Correction during drafting: The prompt asks to "Build" it. Providing just equations is boring. Providing a full GUI is too hard for text. A robust Python class structure is best.
Let's create a HydroCalibrator class.
Specifics on Multi-site: Usually, users struggle with normalizing different units (e.g., Streamflow vs. Soil Moisture) or scales (Large basin vs small sub-basin). I should mention weighting.
Specifics on Identifiability: I need to explain Equifinality (Beven's concept). Different parameters give the same result. This is why GLUE exists.
Code Outline:
import numpy as np
import matplotlib.pyplot as plt
# 1. Dummy Model (Non-linear reservoir)
def model(params, precip, et):
# ... logic ...
return flow
# 2. Objective Functions
def nse(obs, sim): ...
def kge(obs, sim): ...
# 3. GLUE
# Random sampling -> Evaluate -> Sort -> Cumulative weights -> Plot bounds
# 4. Bayesian (Simple MCMC)
# Metropolis algorithm
Refining the "Multi-site" aspect: I'll simulate two sites. One upstream, one downstream. The upstream flow contributes to downstream. Or two independent buckets to show multi-variable calibration. Let's stick to two sub-catchments to show constraints.
Let's assemble the final response:
Objective class.Model.GLUE.MCMC (Basic).Identifiability.Let's ensure the code handles the "Identifiability" part visually. A scatter plot of Parameter X vs NSE is the standard way to show this.
One detailed check on Bayesian vs GLUE: GLUE uses informal likelihoods (e.g., NSE). Bayesian uses formal probability density functions (PDFs). I must make this distinction clear in the code comments. For GLUE, likelihood is often . For Bayesian, likelihood is often Gaussian .
Let's write the response. This is a comprehensive guide to building a hydrologic model calibration framework. We will move from theory to a practical Python implementation using a conceptual Tank Model structure.
This guide covers:
Before writing code, we must define the mathematical engines.
We rarely rely on a single metric.
When calibrating a basin with multiple gauges, the objective function becomes a weighted sum: : Parameter sets that improve the upstream gauge but destroy the downstream gauge performance must be rejected (Pareto dominance).
We will build a complete workflow. We use numpy for math, scipy for optimization, and matplotlib for identifiability plots.
We use a simple Non-Linear Reservoir model for demonstration.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import differential_evolution
# --- 1. The Hydrologic Model (Simple Non-Linear Tank) ---
def simple_tank_model(params, precip, pet):
"""
params: [k_rec, k_base, alpha, max_storage]
"""
k_rec, k_base, alpha, max_storage = params
n_steps = len(precip)
storage = np.zeros(n_steps)
q_sim = np.zeros(n_steps)
# Initial condition
storage[0] = max_storage * 0.5
for t in range(n_steps - 1):
# Water Balance
water_in = precip[t]
et_out = pet[t] * (storage[t] / max_storage) # Linear ET scaling
# Runoff generation (Non-linear)
q_surface = k_rec * (storage[t] / max_storage) ** alpha * precip[t]
q_base = k_base * storage[t]
# Update storage
storage[t+1] = storage[t] + water_in - et_out - q_surface - q_base
storage[t+1] = max(0, min(storage[t+1], max_storage)) # Constraints
q_sim[t] = q_surface + q_base
return q_sim
# --- 2. Generate Synthetic "Truth" Data ---
np.random.seed(42)
n_days = 365
precip = np.random.gamma(2, 2, n_days) * 5
pet = np.abs(np.sin(np.linspace(0, 6.28, n_days)) * 5) + 2
true_params = [0.6, 0.05, 2.5, 100.0] # k_rec, k_base, alpha, S_max
# Create observed flow (Truth + Noise)
q_obs = simple_tank_model(true_params, precip, pet)
noise = np.random.normal(0, 0.5, n_days)
q_obs = np.maximum(0, q_obs + noise) # Ensure non-negative
# --- 3. Objective Functions ---
def nse(obs, sim):
denominator = np.sum((obs - np.mean(obs))**2)
if denominator == 0: return -np.inf
return 1 - np.sum((obs - sim)**2) / denominator
def kge(obs, sim):
r = np.corrcoef(obs, sim)[0, 1]
alpha = np.std(sim) / np.std(obs)
beta = np.mean(sim) / np.mean(obs)
return 1 - np.sqrt((r-1)**2 + (alpha-1)**2 + (beta-1)**2)
# --- 4. Multi-Site Wrapper ---
def multi_site_objective(params, precip_list, pet_list, obs_list):
"""
Handles multiple sites. Returns negative weighted KGE for minimization.
"""
total_cost = 0
for i in range(len(precip_list)):
sim = simple_tank_model(params, precip_list[i], pet_list[i])
# Basic constraints check (e.g. no negative storage implicitly handled in model)
if np.any(np.isnan(sim)):
return 1000 # Penalty
# Weighted sum (equal weight here)
cost = 1 - kge(obs_list[i], sim)
total_cost += cost
return total_cost
# Prepare data for the solver (Single site example for simplicity)
calibration_data = {
'precip': [precip],
'pet': [pet],
'obs': [q_obs]
}
GLUE relies on massive random sampling to understand parameter identifiability.
def run_glue(n_samples=5000):
print("Running GLUE Analysis...")
# Parameter Ranges [k_rec, k_base, alpha, S_max]
bounds = [(0.1, 1.0), (0.001, 0.1), (1.0, 5.0), (50.0, 200.0)]
behavioral_params = []
likelihoods = []
for i in range(n_samples):
# 1. Random Sample (Uniform Prior)
sample = [np.random.uniform(low=b[0], high=b[1]) for b in bounds]
# 2. Run Model
sim = simple_tank_model(sample, precip, pet)
# 3. Evaluate Likelihood (Using NSE as informal likelihood)
lik = nse(q_obs, sim)
# 4. Thresholding (Define "Behavioral")
if lik > 0.5: # Only keep decent models
behavioral_params.append(sample)
likelihoods.append(lik)
return np.array(behavioral_params), np.array(likelihoods)
# Execute GLUE
params_glue, liks_glue = run_glue(2000)
# --- Visualizing Parameter Identifiability (Dotty Plots) ---
param_names = ['k_rec', 'k_base', 'alpha', 'S_max']
fig, axes = plt.subplots(1, 4, figsize=(16, 4), sharey=True)
for i, ax in enumerate(axes):
ax.scatter(params_glue[:, i], liks_glue, alpha=0.5, s=10, color='blue')
ax.set_xlabel(param_names[i])
ax.set_ylabel('Likelihood (NSE)')
ax.set_title(f'Identifiability: {param_names[i]}')
plt.suptitle("GLUE Dotty Plots: High scatter = Low Identifiability")
plt.tight_layout()
plt.show()
Interpretation: If the dotty plot shows a clear peak (an inverted "V" or curve), the parameter is identifiable. If it looks like a flat cloud, the parameter is uncertain (non-identifiable).
We will implement a basic Metropolis-Hastings algorithm. This finds the "Posterior" distribution.
def log_prior(params, bounds):
"""Uniform Prior: Returns 0 if in bounds, -inf otherwise."""
for i, p in enumerate(params):
if not (bounds[i][0] <= p <= bounds[i][1]):
return -np.inf
return 0.0
def log_likelihood(params, precip, pet, obs):
"""Assumes Gaussian errors."""
sim = simple_tank_model(params, precip, pet)
if np.any(np.isnan(sim)): return -np.inf
# Standard deviation of errors (can be calibrated, here fixed)
sigma = 1.0
residuals = obs - sim
# Log of Gaussian PDF sum
ll = -0.5 * np.sum((residuals / sigma) ** 2)
return ll
def run_mcmc(n_iterations=5000):
print("Running Bayesian MCMC...")
bounds = [(0.1, 1.0), (0.001, 0.1), (1.0, 5.0), (50.0, 200.0)]
# Initialize
current_params = [np.mean(b) for b in bounds]
current_log_post = log_prior(current_params, bounds) + log_likelihood(current_params, precip, pet, q_obs)
chain = [current_params]
# Proposal Step Size (tuned manually for this example)
step_sizes = [0.01, 0.005, 0.1, 1.0]
for i in range(n_iterations):
# 1. Propose new state (Gaussian walk)
proposed_params = [
current_params[j] + np.random.normal(0, step_sizes[j])
for j in range(len(bounds))
]
# 2. Calculate Posterior
prop_log_prior = log_prior(proposed_params, bounds)
if prop_log_prior == -np.inf:
# Auto-reject if out of bounds
chain.append(current_params) # Stay in place
continue
prop_log_like = log_likelihood(proposed_params, precip, pet, q_obs)
prop_log_post = prop_log_prior + prop_log_like
# 3. Acceptance Ratio (Metropolis)
if (prop_log_post - current_log_post) > np.log(np.random.uniform()):
current_params = proposed_params
current_log_post = prop_log_post
chain.append(current_params)
return np.array(chain)
# Execute MCMC
chain = run_mcmc(2000)
# Discard first half as "Burn-in"
burn_in = int(len(chain) / 2)
clean_chain = chain[burn_in:]
# --- Visualizing Posteriors ---
fig, axes = plt.subplots(1, 4, figsize=(16, 4))
for i, ax in enumerate(axes):
ax.hist(clean_chain[:, i], bins=30, density=True, color='orange', alpha=0.7)
ax.axvline(true_params[i], color='red', linestyle='--', label='True Param')
ax.set_title(f'Posterior: {param_names[i]}')
plt.suptitle("Bayesian Posterior Distributions (MCMC)")
plt.legend()
plt.show()
To implement multi-site constraints in the code above, you modify the Objective Function to penalize spatial inconsistency.
Scenario: You have Gauge 1 (Upstream) and Gauge 2 (Downstream). Constraint: must roughly equal .
If you calculate parameters :
Run model for Upstream: .
Run model for Downstream: .
| Feature | GLUE | Bayesian (MCMC) |
|---|---|---|
| Philosophy | "Equifinality" (Many good parameter sets exist) | "Probability Theory" (One true distribution exists) |
| Likelihood | Informal (e.g., NSE) | Formal (e.g., Gaussian PDF) |
| Output | Prediction Bounds (Percentiles of behavioral sets) | Posterior Distribution (Credible Intervals) |
| Pros | Easy to implement; robust to non-stationarity | Rigorous uncertainty propagation; efficient sampling |
| Cons | Subjective thresholds; statistically incoherent | Computationally expensive; assumes error distribution |
If you are building a production system:
scipy.optimize.differential_evolution for finding the best fit, and a custom Metropolis-Hastings loop for uncertainty.Objective Functions:
Multi-Site:
GLUE Methodology:
Bayesian (MCMC) Methodology:
Identifiability:
Penalty Logic:
Where Penalty might be: