Module contents
Lesson 21 of 27Advanced 110 min

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

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 x\vb x can contain variables over an entire grid. The observation operator HH maps that state to instrument space: it may interpolate to a sensor, integrate a column or convert variables. If the instrument measures y=H(x)+ϵ\vb y=H(\vb x)+\vb\epsilon, 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 x∼N(xb,B)\vb x\sim\Normal(\vb x_b,\mat B) and ϵ∼N(0,R)\vb\epsilon\sim\Normal(0,\mat R), with positive definite matrices. MAP analysis minimizes

J(x)=12(x−xb)⊤B−1(x−xb)+12(y−Hx)⊤R−1(y−Hx).J(\vb x)=\tfrac12(\vb x-\vb x_b)\T\mat B^{-1}(\vb x-\vb x_b) +\tfrac12(\vb y-\mat H\vb x)\T\mat R^{-1}(\vb y-\mat H\vb x).

For linear H\mat H, the normal equations give

xa=xb+K(y−Hxb),K=BH⊤(HBH⊤+R)−1.\vb x_a=\vb x_b+\mat K(\vb y-\mat H\vb x_b),\qquad \mat K=\mat B\mat H\T(\mat H\mat B\mat H\T+\mat R)^{-1}.

This is optimal interpolation and Kalman analysis if B\mat B is predictive covariance. With fixed B\mat B, 3D-Var does not automatically propagate the full covariance as a complete Kalman filter does. Linear posterior covariance is B−KHB\mat B-\mat K\mat H\mat B; implementations solve systems without forming explicit inverses.

InteractiveBackground, observation and analysis
  • background
  • analysis
  • observation

One point observation and Gaussian covariance B(x,z)=σ² exp(−(x−z)²/(2ℓ²)). Dragging changes position and value; the analysis is the exact linear solution for this case.

1.0
0.5
1.0
Local observation weight0.667
Local analysis variance0.333
Drag the observation and change variances and correlation length.

Background error covariance describes how much one point can be corrected by observing another. A diagonal B\mat B 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 x=xb+Lz\vb x=\vb x_b+\mat L\vb z, where B=LL⊤\mat B=\mat L\mat L\T. The background term becomes ∥z∥2/2\|\vb z\|^2/2; preconditioning can improve optimization without changing the minimum.

4D-Var: a time window

The strong constraint assumes the discrete model xk+1=Mk(xk)\vb x_{k+1}=M_k(\vb x_k) is exact within the window. The initial state is fitted using observations at several times:

J(x0)=12∥x0−xb∥B−12+12∑k=0T∥yk−Hk(xk)∥Rk−12.J(\vb x_0)=\tfrac12\|\vb x_0-\vb x_b\|_{\mat B^{-1}}^2+ \tfrac12\sum_{k=0}^{T}\|\vb y_k-H_k(\vb x_k)\|_{\mat R_k^{-1}}^2.

Let Mk=∂Mk/∂xk\mat M_k=\partial M_k/\partial\vb x_k, Hk=∂Hk/∂xk\mat H_k=\partial H_k/\partial\vb x_k and gk=Hk⊤Rk−1(Hk(xk)−yk)\vb g_k=\mat H_k\T\mat R_k^{-1}(H_k(\vb x_k)-\vb y_k), taking gk=0\vb g_k=0 where there is no measurement. The adjoint is computed backward:

λT=gT,λk=gk+Mk⊤λk+1,∇J(x0)=B−1(x0−xb)+λ0.\vb\lambda_T=\vb g_T,\qquad \vb\lambda_k=\vb g_k+\mat M_k\T\vb\lambda_{k+1},\qquad \nabla J(\vb x_0)=\mat B^{-1}(\vb x_0-\vb x_b)+\vb\lambda_0.

Here Mk\mat M_k 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.

InteractiveFitting a 4D-Var window
  • truth
  • fitted trajectory
  • exact observations

Lorenz-63, RK4 with step 0.01, exact synthetic observations of x at five times. Descent uses central differences and line search with a background penalty; the counter shows real iterations. A long window may yield a nonconvex objective and the result depends on initialization.

80
0
Cost164.612
Initial state x-1.000
Step through real fitting iterations on Lorenz-63 and change the window.

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 ηk=xk+1−Mk(xk)\vb\eta_k=\vb x_{k+1}-M_k(\vb x_k), with penalty 12∑k∥ηk∥Qk−12\tfrac12\sum_k\|\vb\eta_k\|_{\mat Q_k^{-1}}^2. The state of the entire window, or the errors, becomes part of the control. This allows an imperfect model, but choosing Qk\mat Q_k, 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.

InteractiveAssimilation cycles in Lorenz-96
  • truth
  • 3D-Var
  • 4D-Var
  • final observations

Synthetic 20-variable Lorenz-96 experiment, RK4 with step 0.05 and seed 47. Methods see the same data, with background B=4I and R=σ²I. 3D-Var updates at each observation; 4D-Var fits the start of each four-step window with its discrete adjoint and up to 35 descent steps. Error also includes unobserved positions and depends on this realization.

4
2
1.0
8
RMSE 3D-Var3.744
RMSE 4D-Var2.562
4D cost initial → final70.09 → 8.08
4D iterations35
Change sensor spacing, frequency and noise, and follow error evolution.

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 F=8F=8:

x˙i=(xi+1−xi−2)xi−1−xi+F.\dot x_i=(x_{i+1}-x_{i-2})x_{i-1}-x_i+F.

We construct B\mat B 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 B\mat B 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.

[ ]Lorenz-96, discrete tangent and adjointBrowser
"""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})
    [email protected]
    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
[ ]Adjoint and gradient testsBrowser
rng=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-12

Reducing hh 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.

[ ]Prepare covariance and experimentBrowser
B=climatological_covariance();experiment=TwinExperiment(B)
print('Autovalores extremos de B:',np.linalg.eigvalsh(B)[[0,-1]])
[ ]Window 1Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 2Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 3Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 4Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 5Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 6Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 7Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Window 8Browser
print('RMSE análisis 3D/4D, pronóstico 3D/4D, convergencia e iteraciones:',experiment.advance())
[ ]Summary of eight windowsBrowser
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)==8

Run 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 B\mat B 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.

[ ]Spread of an illustrative ensembleBrowser
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.

[ ]Autograd and checkpointingLocal GPU
"""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})
    [email protected]
    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.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof3D-Var and Kalman analysis
Prove: Prove equivalence between the linear 3D-Var minimizer and the Kalman analysis formula.
0
B and R are positive definite and H is linear.

Step 1 of 3. What equation does increment δ=x−xb satisfy?

ProofWindow adjoint
Prove: Derive the gradient with respect to the initial condition of strong-constraint 4D-Var.
0
Each M_k is the discrete numerical map and g_k is the observation-term gradient at x_k.

Step 1 of 3. How does an initial perturbation affect the next step?

Numeric
With background variance 4, observation variance 1 and H=1, what is the observation weight in the analysis?
Numeric
With the same data, what is the analysis variance?
Quiz
Why can a very long 4D-Var window be difficult?
CodeRK4 tangent and adjoint
Complete l96_tlm_adjoint(x_traj,dt). x_traj contains the initial and subsequent states of an RK4 trajectory. Return two functions: the first propagates a tangent vector through the window and the second applies the adjoint of that propagation. ODE derivatives are provided.
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()
Shift+Enter to run
Key idea
3D-Var combines background and observations at one instant; 4D-Var uses observations across a window and requires a gradient consistent with the discrete model.

References