Develop a climate model emulation framework using deep operator networks to accelerate…
- User
Develop a climate model emulation framework using deep operator networks to accelerate scenario ensembles with uncertainty quantification.
Assistant
Develop a climate model emulation framework using deep operator networks to accelerate scenario ensembles with uncertainty quantification.
The user wants me to develop a Climate Model Emulation Framework using Deep Operator Networks (DeepONet). The goal is to accelerate scenario ensembles and include Uncertainty Quantification (UQ).
Key Components:
Drafting the Content:
Revised Plan for Code:
Detailed Steps for the Response:
Self-Correction during drafting:
Final Polish of the Code Structure:
class BranchNet(nn.Module)class TrunkNet(nn.Module)class DeepONetEmulator(nn.Module) -> combines them. Outputs [mean, log_var].loss_function: Gaussian NLL.main: Generate data (Heat equation with variable diffusion), Train ensemble, Plot results with uncertainty bands.Structure of the Explanation:
Let's write the response following this logic. This is a comprehensive framework for building a Climate Model Emulator using Deep Operator Networks (DeepONets).
This framework addresses the core requirements of modern climate emulation: handling spatiotemporal chaos, running ensembles instantly, and quantifying both Aleatoric (data noise) and Epistemic (model) uncertainty.
Traditional neural networks learn mappings between fixed vectors. Climate models, however, are operators that map functional inputs (like a time-series of CO2 emissions) to spatiotemporal states.
The DeepONet Architecture: The DeepONet approximates the operator .
We implement a Heteroscedastic Deep Ensemble approach:
This code simulates a climate model (via a simplified reaction-diffusion PDE), trains a DeepONet emulator with UQ, and runs an ensemble analysis.
Prerequisites: torch, numpy, matplotlib
BayesianLinear layer class.BranchNet and TrunkNet using these layers.DeepONet wrapper.ClimateEmulatorDeepONet.import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
# ==========================================
# 1. Framework Components
# ==========================================
class TrunkNet(nn.Module):
"""
Encodes spatiotemporal coordinates (x, y, t).
"""
def __init__(self, coord_dim, hidden_dim, output_dim):
super(TrunkNet, self).__init__()
self.net = nn.Sequential(
nn.Linear(coord_dim, hidden_dim),
nn.Tanh(),
nn.Linear(hidden_dim, hidden_dim),
nn.Tanh(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, coords):
return self.net(coords)
class BranchNet(nn.Module):
"""
Encodes the input scenario (e.g., CO2 forcing time series).
Uses a 1D CNN to extract features from the signal.
"""
def __init__(self, signal_len, hidden_dim, output_dim):
super(BranchNet, self).__init__()
self.net = nn.Sequential(
nn.Conv1d(1, 16, kernel_size=3, padding=1),
nn.ReLU(),
nn.MaxPool1d(2),
nn.Conv1d(16, 32, kernel_size=3, padding=1),
nn.ReLU(),
nn.Flatten(),
nn.Linear(32 * (signal_len // 2), hidden_dim),
nn.Tanh(),
nn.Linear(hidden_dim, output_dim)
)
def forward(self, signal):
# signal shape: [Batch, Length] -> [Batch, 1, Length]
return self.net(signal.unsqueeze(1))
class ClimateDeepONet(nn.Module):
"""
Operator Network with Heteroscedastic Uncertainty Quantification.
Outputs both Mean and Log-Variance.
"""
def __init__(self, coord_dim, signal_len, hidden_dim=64, trunk_dim=50):
super(ClimateDeepONet, self).__init__()
self.branch = BranchNet(signal_len, hidden_dim, trunk_dim)
self.trunk = TrunkNet(coord_dim, hidden_dim, trunk_dim)
# Heads for Mean and Variance
# We project the dot product to 2 outputs: Mean and Log(Var)
self.head = nn.Linear(trunk_dim, 2)
def forward(self, signal, coords):
"""
signal: [Batch, Signal_Length]
coords: [Batch * N_points, Coord_Dim] (Broadcasting happens here)
"""
B = signal.shape[0]
N = coords.shape[0]
# Branch: [B, Trunk_Dim]
b_out = self.branch(signal)
# Trunk: [N, Trunk_Dim]
t_out = self.trunk(coords)
# Combine via Dot Product
# We want to evaluate every scenario (B) at every coordinate (N)
# Result shape: [B, N, Trunk_Dim]
combined = torch.einsum('bi,ni->bn', b_out, t_out)
# Project to Mean and LogVar
out = self.head(combined) # [B, N, 2]
mean = out[..., 0]
log_var = out[..., 1]
return mean, log_var
# ==========================================
# 2. Loss Function (NLL for UQ)
# ==========================================
def heteroscedastic_nll_loss(y_true, y_pred_mean, y_pred_log_var):
"""
Negative Log Likelihood assuming Gaussian distribution.
Penalizes uncertainty when error is low, and forces high uncertainty
only when error is unavoidable.
"""
precision = torch.exp(-y_pred_log_var)
loss = 0.5 * precision * (y_true - y_pred_mean)**2 + 0.5 * y_pred_log_var
return torch.mean(loss)
# ==========================================
# 3. Data Generation (Synthetic Climate Simulator)
# ==========================================
def generate_synthetic_climate_data(n_samples=100, t_steps=50, grid_res=16):
"""
Simulates a 'slow' climate model (e.g., simplified reaction-diffusion).
Input: Forcing amplitude (Scenario).
Output: Spatiotemporal field (Temperature).
"""
print("Generating synthetic climate data...")
x = np.linspace(0, 1, grid_res)
y = np.linspace(0, 1, grid_res)
t = np.linspace(0, 1, t_steps)
# Meshgrid
xx, yy = np.meshgrid(x, y)
signals = []
outputs = []
coords_list = []
for i in range(n_samples):
# Random Forcing Scenario (e.g., CO2 curve)
# A random increasing function
base_amp = np.random.uniform(0.5, 2.0)
signal = base_amp * (1 + 0.5 * t + 0.2 * np.sin(10*t))
# Physics Simulation (Approximated here for speed)
# In real life, this is the 'Expensive Model'
# T(x,y,t) = (signal_t) * sin(x) * cos(y) + noise
field = []
for t_val in signal:
spatial = t_val * np.sin(3 * xx) * np.cos(3 * yy)
field.append(spatial)
field = np.array(field) # Shape: [Time, X, Y]
# Flatten for DeepONet training
# We sample points randomly for efficiency (Stochastic Gradient Descent)
signals.append(signal)
outputs.append(field)
# Coordinate tensor: [t, x, y]
T, X, Y = np.meshgrid(t, x, y, indexing='ij')
coords = np.stack([T.flatten(), X.flatten(), Y.flatten()], axis=1)
return (torch.FloatTensor(signals),
torch.FloatTensor(coords),
torch.FloatTensor(outputs))
# ==========================================
# 4. Main Execution Framework
# ==========================================
def train_emulator():
# Config
N_ENSEMBLE = 3 # Number of DeepONets for Epistemic UQ
EPOCHS = 200
BATCH_SIZE = 10
# 1. Generate Data
signals, coords, fields = generate_synthetic_climate_data(n_samples=100)
N_POINTS = coords.shape[0]
# 2. Initialize Ensemble
ensemble = []
optimizers = []
print(f"Initializing Ensemble of {N_ENSEMBLE} models...")
for i in range(N_ENSEMBLE):
model = ClimateDeepONet(coord_dim=3, signal_len=signals.shape[1])
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
ensemble.append(model)
optimizers.append(opt)
# 3. Training Loop
print("Training...")
losses = []
for epoch in range(EPOCHS):
epoch_loss = 0
# Shuffle data
perm = torch.randperm(signals.size(0))
signals = signals[perm]
fields = fields[perm]
for i in range(0, signals.size(0), BATCH_SIZE):
batch_sig = signals[i:i+BATCH_SIZE]
batch_out = fields[i:i+BATCH_SIZE]
# Flatten output to match model: [Batch, N_Points]
batch_out_flat = batch_out.view(batch_out.size(0), -1)
# Train each member of the ensemble
for idx, model in enumerate(ensemble):
optimizers[idx].zero_grad()
pred_mean, pred_log_var = model(batch_sig, coords)
loss = heteroscedastic_nll_loss(batch_out_flat, pred_mean, pred_log_var)
loss.backward()
optimizers[idx].step()
epoch_loss += loss.item()
losses.append(epoch_loss / (N_ENSEMBLE * (signals.size(0)/BATCH_SIZE)))
if epoch % 20 == 0:
print(f"Epoch {epoch}: Avg Loss = {losses[-1]:.4f}")
print("Training Complete.")
return ensemble, signals, coords, fields
# ==========================================
# 5. Ensemble Inference & Visualization
# ==========================================
def visualize_uncertainty(ensemble, signals, coords, fields, scenario_idx=0):
"""
Runs the ensemble on a test scenario and visualizes:
1. The Mean Prediction
2. Aleatoric Uncertainty (Inherent noise)
3. Epistemic Uncertainty (Model disagreement)
"""
model_device = next(ensemble[0].parameters()).device
# Select one scenario
test_sig = signals[scenario_idx].unsqueeze(0)
true_field = fields[scenario_idx].numpy()
# Gather predictions
preds_means = []
preds_aleatoric = []
with torch.no_grad():
for model in ensemble:
mean, log_var = model(test_sig, coords)
preds_means.append(mean.squeeze().numpy())
preds_aleatoric.append(torch.exp(log_var).squeeze().numpy())
preds_means = np.array(preds_means) # [N_models, N_points]
# Calculate Statistics
# 1. Ensemble Mean
final_mean = np.mean(preds_means, axis=0)
# 2. Epistemic Uncertainty (Standard Deviation across models)
epistemic_std = np.std(preds_means, axis=0)
# Reshape for plotting (assuming 16x16 grid, 50 timesteps)
# We visualize the last timestep
grid_size = 16
t_idx = -1 # Last time step
true_map = true_field[t_idx]
pred_map = final_mean.reshape(50, grid_size, grid_size)[t_idx]
epi_map = epistemic_std.reshape(50, grid_size, grid_size)[t_idx]
# Plotting
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
# True
im0 = axes[0].imshow(true_map, cmap='viridis')
axes[0].set_title("Ground Truth (Expensive Model)")
plt.colorbar(im0, ax=axes[0])
# Prediction
im1 = axes[1].imshow(pred_map, cmap='viridis')
axes[1].set_title("DeepONet Ensemble Mean")
plt.colorbar(im1, ax=axes[1])
# Epistemic Uncertainty
im2 = axes[2].imshow(epi_map, cmap='hot')
axes[2].set_title("Epistemic Uncertainty (Model Disagreement)")
plt.colorbar(im2, ax=axes[2])
plt.tight_layout()
plt.show()
# Run the pipeline
if __name__ == "__main__":
ensemble, signals, coords, fields = train_emulator()
visualize_uncertainty(ensemble, signals, coords, fields)