Data assimilation I: variational methods (3D-Var and 4D-Var)
Combine an imperfect dynamical model with sparse noisy observations. Formulate 3D-Var as a Bayesian analysis and 4D-Var as a windowed inverse problem with a discrete adjoint, then implement a Lorenz-96 assimilation cycle.
After this lesson you can
- Formulate data assimilation with a background state, observations and observation operator.
- Derive 3D-Var and connect it to optimal interpolation and Kalman analysis.
- Implement strong-constraint 4D-Var with a discrete adjoint and verify the gradient.
- Explain incremental and weak-constraint 4D-Var.
- Design and evaluate a Lorenz-96 assimilation cycle using analysis and forecast errors.
Before you start
- 29Lyapunov exponentsPredictability horizonMAP-Tikhonov equivalenceAdjoint gradient for PDE problemsTaylor test for gradientsBayesian inverse problem
- 14Kalman filterKalman gainInnovations and prediction error decompositionRauch-Tung-Striebel smoother
- 06Limited-memory BFGSGauss-Newton method
- 09Reverse-mode automatic differentiationBinomial checkpointing
Initial state, model and observations
A numerical forecast needs an initial state we cannot fully measure. Data assimilation combines a prior forecast, or background, with sparse observations and their uncertainties. The analysis feeds the next forecast; the cycle repeats as new observations arrive. Historical weather-prediction improvement has several causes, including better observations, models, computers and assimilation: uniform improvement is not guaranteed in every situation.
State can contain variables over an entire grid. The observation operator maps that state to instrument space: it may interpolate to a sensor, integrate a column or convert variables. If the instrument measures , the residual has the observation’s dimension and units, not necessarily those of the state.
3D-Var: one instant
In 3D-Var, suppose independent Gaussian errors and , with positive definite matrices. MAP analysis minimizes
For linear , the normal equations give
This is optimal interpolation and Kalman analysis if is predictive covariance. With fixed , 3D-Var does not automatically propagate the full covariance as a complete Kalman filter does. Linear posterior covariance is ; implementations solve systems without forming explicit inverses.
Background error covariance describes how much one point can be corrected by observing another. A diagonal prevents that direct correction at distinct positions, although dynamics may transmit it later. Spatial covariances can be built using diffusion operators and physical balances among variables. The NMC method estimates structures from differences between forecasts at different lead times valid at the same time: these are approximations, not direct measurements of true error. Climatological state covariance is not automatically forecast-error covariance either.
To condition the problem, write , where . The background term becomes ; preconditioning can improve optimization without changing the minimum.
4D-Var: a time window
The strong constraint assumes the discrete model is exact within the window. The initial state is fitted using observations at several times:
Let , and , taking where there is no measurement. The adjoint is computed backward:
Here differentiates the complete numerical algorithm, not just the continuous ODE. An RK4-consistent adjoint backpropagates through all four stages. For linear Gaussian model and observations, the window minimum is the posterior trajectory mean and relates to the Kalman smoother; with nonlinearity one obtains a local MAP and the posterior can be multimodal.
A longer window collects information from more times, but chaotic sensitivity can make the objective very irregular. Its minimum may depend on initialization, and a longer window does not guarantee a better analysis.
Incremental 4D-Var linearizes around a reference trajectory. An inner loop approximately solves a quadratic problem with tangent and adjoint models; an outer loop updates the nonlinear trajectory and repeats. This is a Gauss–Newton-type strategy, not a global optimum guarantee.
The weak constraint introduces model errors , with penalty . The state of the entire window, or the errors, becomes part of the control. This allows an imperfect model, but choosing , separating model and observation error, and solving for more unknowns remain difficult.
Twin experiment
An OSSE generates a truth with a model, simulates sensors and compares analysis against known truth. This also measures points without sensors, though it does not reproduce every real-world uncertainty. The figure uses 20-variable Lorenz-96; the lab uses 40. Both compare methods on the same data and specify their backgrounds.
Spread requires an ensemble of states: it cannot be inferred from one deterministic trajectory. This experiment’s RMSE measures error against synthetic truth; operations also use innovations, independent observations and ensembles. ECMWF documents 4D-Var and an ensemble of assimilations to represent uncertainty, with operational details evolving with the system. This reduced example does not reproduce that system.
Lab: 3D-Var and 4D-Var in Lorenz-96
Lorenz-96 has periodic indices and forcing :
We construct from 600 states of a long synthetic trajectory with diagonal regularization 0.1. It is a regularized climatological covariance used as a teaching proxy, not actual background-error covariance. Both methods start from the same perturbed condition and receive the same noisy observations. 3D-Var uses the same static at every update; 4D-Var fits the start of each window and then propagates the analysis to its end. Compare analysis and forecast RMSE across all 40 variables.
"""Asimilación variacional con Lorenz-96 y adjunto discreto de RK4."""
import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import minimize
def l96(x, forcing=8.):
return (np.roll(x,-1)-np.roll(x,2))*np.roll(x,1)-x+forcing
def l96_tangent(x, v):
return ((np.roll(x,-1)-np.roll(x,2))*np.roll(v,1)
+np.roll(x,1)*(np.roll(v,-1)-np.roll(v,2))-v)
def l96_adjoint(x, w):
a=np.roll(x,-1)-np.roll(x,2)
b=np.roll(x,1)*w
return np.roll(a*w,-1)+np.roll(b,1)-np.roll(b,-2)-w
def rk4_cache(x, dt):
k1=l96(x)
s2=x+dt*k1/2; k2=l96(s2)
s3=x+dt*k2/2; k3=l96(s3)
s4=x+dt*k3; k4=l96(s4)
return x+dt*(k1+2*k2+2*k3+k4)/6, (x,s2,s3,s4)
def rk4_tangent(cache, v, dt):
x,s2,s3,s4=cache
dk1=l96_tangent(x,v)
dk2=l96_tangent(s2,v+dt*dk1/2)
dk3=l96_tangent(s3,v+dt*dk2/2)
dk4=l96_tangent(s4,v+dt*dk3)
return v+dt*(dk1+2*dk2+2*dk3+dk4)/6
def rk4_adjoint(cache, w, dt):
x,s2,s3,s4=cache
bx=w.copy()
b1=dt*w/6; b2=dt*w/3; b3=dt*w/3; b4=dt*w/6
bs4=l96_adjoint(s4,b4); bx+=bs4; b3+=dt*bs4
bs3=l96_adjoint(s3,b3); bx+=bs3; b2+=dt*bs3/2
bs2=l96_adjoint(s2,b2); bx+=bs2; b1+=dt*bs2/2
bx+=l96_adjoint(x,b1)
return bx
def propagate(x, steps, dt):
states=[np.asarray(x,float).copy()]; caches=[]
for _ in range(steps):
nxt,cache=rk4_cache(states[-1],dt)
states.append(nxt);caches.append(cache)
return np.array(states),caches
def analysis_3d(xb, B, indices, y, variance):
HB=B[indices,:]
S=B[np.ix_(indices,indices)]+variance*np.eye(len(indices))
return xb+HB.T@cho_solve(cho_factor(S,lower=True),y-xb[indices])
def cost_gradient(x0, xb, Bfactor, observations, dt):
"""observations: pares (paso, índices, valores, varianza)."""
steps=max(t for t,_,_,_ in observations)
states,caches=propagate(x0,steps,dt)
diff=x0-xb
bg=cho_solve(Bfactor,diff)
value=.5*diff@bg
injections=np.zeros_like(states)
for t,idx,y,variance in observations:
residual=states[t,idx]-y
value+=.5*residual@residual/variance
np.add.at(injections[t],idx,residual/variance)
adj=injections[-1].copy()
for t in range(steps-1,-1,-1):
adj=rk4_adjoint(caches[t],adj,dt)+injections[t]
return value,bg+adj
def analysis_4d(xb,B,observations,dt,maxiter=250):
factor=cho_factor(B,lower=True)
L=np.linalg.cholesky(B)
def whitened(z):
value,grad=cost_gradient(xb+L@z,xb,factor,observations,dt)
return value,L.T@grad
result=minimize(whitened,np.zeros(len(xb)),jac=True,method='L-BFGS-B',
options={'maxiter':maxiter,'ftol':1e-10})
result.x=xb+L@result.x
return result
def climatological_covariance(n=40,dt=.05,samples=600,seed=8):
"""Trayectoria larga sintética; B climatológica, no error de pronóstico."""
rng=np.random.default_rng(seed);x=8+0.1*rng.normal(size=n)
for _ in range(400):x,_=rk4_cache(x,dt)
draws=[]
for _ in range(samples):
for _ in range(4):x,_=rk4_cache(x,dt)
draws.append(x.copy())
C=np.cov(np.array(draws),rowvar=False)
# Regularización explícita para asegurar una matriz invertible.
return C+0.1*np.eye(n)
class TwinExperiment:
"""Datos idénticos; análisis al final de cada ventana y pronóstico aparte."""
def __init__(self,B,window=4,stride=4,noise=1.,dt=.05,seed=22):
self.B=B;self.window=window;self.noise=noise;self.dt=dt
self.rng=np.random.default_rng(seed);n=B.shape[0]
self.truth=8+0.1*self.rng.normal(size=n)
for _ in range(500):self.truth,_=rk4_cache(self.truth,dt)
self.x3=self.truth+self.rng.normal(0,1,n);self.x4=self.x3.copy()
self.indices=np.arange(0,n,stride);self.rows=[]
def advance(self):
B=self.B;dt=self.dt;window=self.window;idx=self.indices
real,_=propagate(self.truth,window,dt)
obs=[(t,idx,real[t,idx]+self.rng.normal(0,self.noise,len(idx)),self.noise**2)
for t in range(1,window+1)]
result=analysis_4d(self.x4,B,obs,dt)
self.x4=propagate(result.x,window,dt)[0][-1]
for _,ids,y,var in obs:
self.x3,_=rk4_cache(self.x3,dt)
self.x3=analysis_3d(self.x3,B,ids,y,var)
self.truth=real[-1]
rmse=lambda a,b:np.sqrt(np.mean((a-b)**2))
future=propagate(self.truth,window,dt)[0][-1]
row=(rmse(self.x3,self.truth),rmse(self.x4,self.truth),
rmse(propagate(self.x3,window,dt)[0][-1],future),
rmse(propagate(self.x4,window,dt)[0][-1],future),
result.success,result.nit)
self.rows.append(row)
return rowrng=np.random.default_rng(4);x=rng.normal(size=40);v=rng.normal(size=40);w=rng.normal(size=40)
dt=.05;xp,cache=rk4_cache(x,dt)
tv=rk4_tangent(cache,v,dt);aw=rk4_adjoint(cache,w,dt)
print('producto escalar, diferencia:',abs(tv@w-v@aw))
for h in [1e-3,1e-4,1e-5]:
trial,_=rk4_cache(x+h*v,dt)
print('resto Taylor paso',h,np.linalg.norm(trial-xp-h*tv))
idx=np.arange(0,40,4);obs=[(0,idx,rng.normal(size=len(idx)),1.),
(4,idx,rng.normal(size=len(idx)),1.)]
bfactor=cho_factor(np.eye(40),lower=True);xb=.9*x
J,g=cost_gradient(x,xb,bfactor,obs,dt)
for h in [1e-3,1e-4,1e-5]:
print('resto Taylor coste',h,abs(cost_gradient(x+h*v,xb,bfactor,obs,dt)[0]-J-h*g@v))
assert abs(tv@w-v@aw)<1e-12Reducing tenfold should reduce quadratic remainders about one hundredfold until rounding dominates. The two tests check different things: the dot product tests whether tangent and adjoint are transposes; Taylor connects that derivative to the actual model and cost.
B=climatological_covariance();experiment=TwinExperiment(B)
print('Autovalores extremos de B:',np.linalg.eigvalsh(B)[[0,-1]])print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())rows=np.array([r[:4] for r in experiment.rows])
print('Media RMSE análisis 3D/4D:',rows[:,:2].mean(axis=0))
print('Media RMSE pronóstico 3D/4D:',rows[:,2:].mean(axis=0))
print('Optimizaciones convergidas:',sum(r[4] for r in experiment.rows),'de',len(experiment.rows))
assert len(rows)==8Run preparation before repeating the eight windows. Covariance and truth use seeds 8 and 22. In the Pyodide run, mean 3D/4D analysis RMSEs are about 2.496/1.717 and forecast RMSEs 2.837/2.371; the optimizer reports convergence in all eight windows. Exact iterations may vary across numerical implementations and convergence does not prove absence of local minima. Comparison depends on the window, static and sensor design.
To distinguish error and spread, also generate 30 Gaussian perturbations around the last 4D analysis with the same example climatological covariance and propagate them four steps. Spread is the square root of mean sample variance per component. This artificial cloud is neither a 4D-Var posterior sample nor a calibrated ensemble; it computes the metric without claiming to represent its uncertainty.
rng_spread=np.random.default_rng(81)
members=experiment.x4+rng_spread.multivariate_normal(np.zeros(40),B,size=30)
forecast=np.array([propagate(member,4,.05)[0][-1] for member in members])
truth_forecast=propagate(experiment.truth,4,.05)[0][-1]
spread=np.sqrt(np.var(forecast,axis=0,ddof=1).mean())
mean_error=np.sqrt(np.mean((forecast.mean(axis=0)-truth_forecast)**2))
print('Dispersión y RMSE de la media del conjunto:',spread,mean_error)The local cell compares the manual gradient with PyTorch on CPU and runs a 1000-variable window on GPU if available, with per-step checkpointing. Time and memory depend on hardware; without CUDA it reports that part pending. GPU measurement includes startup and is not a controlled speed comparison with CPU.
"""Asimilación variacional con Lorenz-96 y adjunto discreto de RK4."""
import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import minimize
def l96(x, forcing=8.):
return (np.roll(x,-1)-np.roll(x,2))*np.roll(x,1)-x+forcing
def l96_tangent(x, v):
return ((np.roll(x,-1)-np.roll(x,2))*np.roll(v,1)
+np.roll(x,1)*(np.roll(v,-1)-np.roll(v,2))-v)
def l96_adjoint(x, w):
a=np.roll(x,-1)-np.roll(x,2)
b=np.roll(x,1)*w
return np.roll(a*w,-1)+np.roll(b,1)-np.roll(b,-2)-w
def rk4_cache(x, dt):
k1=l96(x)
s2=x+dt*k1/2; k2=l96(s2)
s3=x+dt*k2/2; k3=l96(s3)
s4=x+dt*k3; k4=l96(s4)
return x+dt*(k1+2*k2+2*k3+k4)/6, (x,s2,s3,s4)
def rk4_tangent(cache, v, dt):
x,s2,s3,s4=cache
dk1=l96_tangent(x,v)
dk2=l96_tangent(s2,v+dt*dk1/2)
dk3=l96_tangent(s3,v+dt*dk2/2)
dk4=l96_tangent(s4,v+dt*dk3)
return v+dt*(dk1+2*dk2+2*dk3+dk4)/6
def rk4_adjoint(cache, w, dt):
x,s2,s3,s4=cache
bx=w.copy()
b1=dt*w/6; b2=dt*w/3; b3=dt*w/3; b4=dt*w/6
bs4=l96_adjoint(s4,b4); bx+=bs4; b3+=dt*bs4
bs3=l96_adjoint(s3,b3); bx+=bs3; b2+=dt*bs3/2
bs2=l96_adjoint(s2,b2); bx+=bs2; b1+=dt*bs2/2
bx+=l96_adjoint(x,b1)
return bx
def propagate(x, steps, dt):
states=[np.asarray(x,float).copy()]; caches=[]
for _ in range(steps):
nxt,cache=rk4_cache(states[-1],dt)
states.append(nxt);caches.append(cache)
return np.array(states),caches
def analysis_3d(xb, B, indices, y, variance):
HB=B[indices,:]
S=B[np.ix_(indices,indices)]+variance*np.eye(len(indices))
return xb+HB.T@cho_solve(cho_factor(S,lower=True),y-xb[indices])
def cost_gradient(x0, xb, Bfactor, observations, dt):
"""observations: pares (paso, índices, valores, varianza)."""
steps=max(t for t,_,_,_ in observations)
states,caches=propagate(x0,steps,dt)
diff=x0-xb
bg=cho_solve(Bfactor,diff)
value=.5*diff@bg
injections=np.zeros_like(states)
for t,idx,y,variance in observations:
residual=states[t,idx]-y
value+=.5*residual@residual/variance
np.add.at(injections[t],idx,residual/variance)
adj=injections[-1].copy()
for t in range(steps-1,-1,-1):
adj=rk4_adjoint(caches[t],adj,dt)+injections[t]
return value,bg+adj
def analysis_4d(xb,B,observations,dt,maxiter=250):
factor=cho_factor(B,lower=True)
L=np.linalg.cholesky(B)
def whitened(z):
value,grad=cost_gradient(xb+L@z,xb,factor,observations,dt)
return value,L.T@grad
result=minimize(whitened,np.zeros(len(xb)),jac=True,method='L-BFGS-B',
options={'maxiter':maxiter,'ftol':1e-10})
result.x=xb+L@result.x
return result
def climatological_covariance(n=40,dt=.05,samples=600,seed=8):
"""Trayectoria larga sintética; B climatológica, no error de pronóstico."""
rng=np.random.default_rng(seed);x=8+0.1*rng.normal(size=n)
for _ in range(400):x,_=rk4_cache(x,dt)
draws=[]
for _ in range(samples):
for _ in range(4):x,_=rk4_cache(x,dt)
draws.append(x.copy())
C=np.cov(np.array(draws),rowvar=False)
# Regularización explícita para asegurar una matriz invertible.
return C+0.1*np.eye(n)
class TwinExperiment:
"""Datos idénticos; análisis al final de cada ventana y pronóstico aparte."""
def __init__(self,B,window=4,stride=4,noise=1.,dt=.05,seed=22):
self.B=B;self.window=window;self.noise=noise;self.dt=dt
self.rng=np.random.default_rng(seed);n=B.shape[0]
self.truth=8+0.1*self.rng.normal(size=n)
for _ in range(500):self.truth,_=rk4_cache(self.truth,dt)
self.x3=self.truth+self.rng.normal(0,1,n);self.x4=self.x3.copy()
self.indices=np.arange(0,n,stride);self.rows=[]
def advance(self):
B=self.B;dt=self.dt;window=self.window;idx=self.indices
real,_=propagate(self.truth,window,dt)
obs=[(t,idx,real[t,idx]+self.rng.normal(0,self.noise,len(idx)),self.noise**2)
for t in range(1,window+1)]
result=analysis_4d(self.x4,B,obs,dt)
self.x4=propagate(result.x,window,dt)[0][-1]
for _,ids,y,var in obs:
self.x3,_=rk4_cache(self.x3,dt)
self.x3=analysis_3d(self.x3,B,ids,y,var)
self.truth=real[-1]
rmse=lambda a,b:np.sqrt(np.mean((a-b)**2))
future=propagate(self.truth,window,dt)[0][-1]
row=(rmse(self.x3,self.truth),rmse(self.x4,self.truth),
rmse(propagate(self.x3,window,dt)[0][-1],future),
rmse(propagate(self.x4,window,dt)[0][-1],future),
result.success,result.nit)
self.rows.append(row)
return row
"""Gradiente automático, comparación y ventana con checkpointing en GPU."""
import time
import torch
from torch.utils.checkpoint import checkpoint
torch.set_default_dtype(torch.float64)
def torch_l96(x):
return (torch.roll(x,-1)-torch.roll(x,2))*torch.roll(x,1)-x+8
def torch_rk4(x,dt):
k1=torch_l96(x);k2=torch_l96(x+dt*k1/2)
k3=torch_l96(x+dt*k2/2);k4=torch_l96(x+dt*k3)
return x+dt*(k1+2*k2+2*k3+k4)/6
def torch_cost(x,xb,B,obs,dt,checkpointed=False):
L=torch.linalg.cholesky(B)
z=torch.linalg.solve_triangular(L,(x-xb)[:,None],upper=False)
val=.5*torch.sum(z*z);state=x;step=0
for t,idx,y,var in obs:
while step<t:
state=(checkpoint(torch_rk4,state,dt,use_reentrant=False)
if checkpointed else torch_rk4(state,dt))
step+=1
val=val+.5*torch.sum((state[idx]-y)**2)/var
return val
rng=np.random.default_rng(3);n=40;dt=.05
xb=rng.normal(size=n);x0=xb+rng.normal(0,.1,n);B=np.eye(n)*2
idx=np.arange(0,n,4);obs=[(2,idx,rng.normal(size=len(idx)),1.),(5,idx,rng.normal(size=len(idx)),1.)]
start=time.perf_counter()
manual_value,manual_gradient=cost_gradient(x0,xb,cho_factor(B),obs,dt)
manual_time=time.perf_counter()-start
tobs=[(t,torch.tensor(i),torch.tensor(y),v) for t,i,y,v in obs]
x=torch.tensor(x0,requires_grad=True)
start=time.perf_counter()
loss=torch_cost(x,torch.tensor(xb),torch.tensor(B),tobs,dt)
loss.backward();auto_time=time.perf_counter()-start
print('diferencia valor y gradiente:',abs(loss.item()-manual_value),
np.max(abs(x.grad.detach().numpy()-manual_gradient)))
print('tiempos manual y autograd CPU (s):',manual_time,auto_time)
assert np.allclose(x.grad.detach().numpy(),manual_gradient,atol=1e-9)
if torch.cuda.is_available():
device='cuda';n=1000
x=torch.full((n,),8.,device=device,requires_grad=True)
xb=x.detach().clone();target=torch.full((n,),8.1,device=device)
torch.cuda.reset_peak_memory_stats();torch.cuda.synchronize();start=time.perf_counter()
state=x
for _ in range(40):
state=checkpoint(torch_rk4,state,.01,use_reentrant=False)
loss=.5*torch.mean((state-target)**2)+.5*torch.mean((x-xb)**2)
loss.backward();torch.cuda.synchronize()
print('GPU 1000 variables, 40 pasos, checkpoint por paso: pérdida, segundos, pico bytes:',
loss.item(),time.perf_counter()-start,torch.cuda.max_memory_allocated())
assert torch.isfinite(x.grad).all()
else:
print('GPU no disponible: la demostración GPU queda pendiente.')npm run lab and open the connection link.Exercises
Step 1 of 3. What equation does increment δ=x−xb satisfy?
Step 1 of 3. How does an initial perturbation affect the next step?
import numpy as np
def rhs(x):
return (np.roll(x,-1)-np.roll(x,2))*np.roll(x,1)-x+8
def tangent(x,v):
return ((np.roll(x,-1)-np.roll(x,2))*np.roll(v,1)
+np.roll(x,1)*(np.roll(v,-1)-np.roll(v,2))-v)
def adjoint(x,w):
a=np.roll(x,-1)-np.roll(x,2);b=np.roll(x,1)*w
return np.roll(a*w,-1)+np.roll(b,1)-np.roll(b,-2)-w
def stages(x,dt):
k1=rhs(x);s2=x+dt*k1/2;k2=rhs(s2)
s3=x+dt*k2/2;k3=rhs(s3);s4=x+dt*k3
return (x,s2,s3,s4)
def l96_tlm_adjoint(x_traj,dt):
# Devuelve dos funciones que propagan vectores por toda la ventana.
raise NotImplementedError()