Module contents
Lesson 22 of 27Advanced 115 min

Data assimilation II: ensemble Kalman filter and particle methods

Approximate Kalman filtering with ensembles, understand stochastic and square-root updates, localization and inflation, apply ensemble Kalman inversion, and examine particle-filter degeneracy in high dimension.

After this lesson you can

  • Implement perturbed-observation EnKF and ETKF and explain the perturbation's role.
  • Diagnose spurious correlations and apply covariance and domain localization.
  • Apply multiplicative and additive inflation to mitigate ensemble collapse.
  • Estimate simulator parameters without gradients using ensemble Kalman inversion.
  • Explain high-dimensional particle-filter degeneracy and compare methods on Lorenz-96.

Before you start

From covariance to ensemble

If a state has billions of components, storing a dense covariance is infeasible. The ensemble Kalman filter (EnKF) propagates NN states with the model and approximates their moments using the mean and anomalies. For members x(j)\vb x^{(j)},

xˉ=1N∑jx(j),A=[x(1)−xˉ,…,x(N)−xˉ],Pf=AA⊤N−1.\bar{\vb x}=\frac1N\sum_j\vb x^{(j)},\qquad \mat A=[\vb x^{(1)}-\bar{\vb x},\ldots,\vb x^{(N)}-\bar{\vb x}],\qquad \mat P_f=\frac{\mat A\mat A\T}{N-1}.

The matrix has rank at most N−1N-1: an ensemble of a few dozen simulations does not represent every direction of a huge state. Nevertheless, observation products can be computed from anomalies without constructing the dense matrix. Nonlinear dynamics are evaluated for each member; the Kalman-type update remains a moment-based approximation, not generally an exact posterior.

Perturbed observations and square roots

With linear operator H\mat H, noise covariance R\mat R and gain K=PfH⊤(HPfH⊤+R)−1\mat K=\mat P_f\mat H\T(\mat H\mat P_f\mat H\T+\mat R)^{-1}, stochastic EnKF updates each member with an independent observation y+ϵ(j)\vb y+\vb\epsilon^{(j)}, where ϵ(j)∼N(0,R)\vb\epsilon^{(j)}\sim\Normal(0,\mat R). Observation perturbation contributes, in expectation conditioned on the ensemble, the missing covariance term KRK⊤\mat K\mat R\mat K\T.

If all members use the same observation, their anomalies are multiplied by I−KH\mat I-\mat K\mat H and covariance becomes

(I−KH)Pf(I−KH)⊤,(\mat I-\mat K\mat H)\mat P_f(\mat I-\mat K\mat H)\T,

less than Kalman analysis covariance by KRK⊤\mat K\mat R\mat K\T. In a finite ensemble independent perturbations add sampling noise: a realization’s mean and covariance need not match Kalman exactly.

A square-root filter updates anomalies deterministically to obtain the desired covariance. In ETKF, with Z=A/N−1\mat Z=\mat A/\sqrt{N-1} and Y=HZ\mat Y=\mat H\mat Z,

S=I+Y⊤R−1Y,xˉa=xˉf+ZS−1Y⊤R−1(y−Hxˉf),Aa=N−1 ZS−1/2.\mat S=\mat I+\mat Y\T\mat R^{-1}\mat Y,\qquad \bar{\vb x}_a=\bar{\vb x}_f+\mat Z\mat S^{-1}\mat Y\T\mat R^{-1}(\vb y-\mat H\bar{\vb x}_f),\qquad \mat A_a=\sqrt{N-1}\,\mat Z\mat S^{-1/2}.

The symmetric root is computed in the space of NN members. For nonlinear observations, evaluate their values at each member and form anomalies in observation space; the update still approximates the posterior. Model, observation and NN-sized algebra costs still matter.

InteractiveUpdating the ensemble cloud
  • forecast
  • analysis
  • ensemble covariance
  • quadrature moments

60 members with seed 71: independent normals (x,y) are transformed to (x+0.35(y²−1), 0.8y). The first coordinate is observed with Gaussian noise. Quadrature on a finite [−5,5]² grid integrates the transformed density and likelihood; ellipses summarize moments and do not guarantee Gaussian coverage.

Update
1.0
0.7
Ensemble mean x0.650
Quadrature mean x0.693
Ensemble variance x0.309
Compare stochastic and ETKF updates with a quadrature reference.

The nonlinear transformation in this figure creates a curved cloud. An ellipse summarizes its first two moments and does not reproduce its full shape. Quadrature is a numerical reference on a finite grid; ETKF’s exact agreement with Kalman concerns sample covariance and the linear update problem, not the complete non-Gaussian posterior.

Localization, inflation and diversity

With small NN, spurious correlations appear between physically distant points. Covariance localization damps correlations by distance; Gaspari–Cohn is a compact function equal to one at zero and zero at twice its scale radius. Its elementwise product with a covariance preserves positive semidefiniteness when the localization matrix is positive semidefinite. An arbitrary distance or function does not guarantee that property.

InteractiveSpurious correlations and localization
Reference: 4000 states
Pool covariance
Localized covariance

Blue is positive and orange negative; intensity is proportional to absolute value up to 15. Lorenz-96 with 40 variables, F=8, step 0.05 and seed 120. A reference of 4000 states and subsequent pool of 500 are sampled every two steps: they are temporally correlated, not independent samples. The reference is a finite estimate, not an exact covariance. Gaspari–Cohn vanishes at two radii; localization does not guarantee lower error for every sample.

20
4
Sample covariance RMSE4.951
Localized covariance RMSE1.446
Compare covariances from a time pool with a finite climatological reference.

The radius should reflect physical scales: too short removes useful connections. LETKF localizes by domain: for each point it solves an ensemble-space analysis using nearby observations, weighted here with Gaspari–Cohn. This is not merely multiplying final covariance by a mask and, with a small ensemble, the result depends on radius and observations.

Multiplicative inflation scales anomalies by a factor greater than one before analysis. Additive inflation incorporates model perturbations; RTPS partially relaxes analysis spread toward forecast spread and can adapt using diagnostics. Inflation can mitigate collapse and model error, but an excessive factor degrades analysis. If the ensemble becomes too narrow, gain decreases and the filter may ignore observations: filter divergence.

InteractiveEnKF dashboard
  • Analysis RMSE
  • Ensemble spread

40-variable Lorenz-96, truth F=8, step 0.05, observation-noise deviation 1 and seed 19. Analysis is serial EnKF with perturbed observations and Gaspari–Cohn localization. Filter forcing is 8 plus bias. There are 30 four-step cycles; one experiment does not prove calibration.

20
4
1.04
4
0.0
Final RMSE1.392
Final spread1.072
Cycles computed30
Change ensemble, inflation, localization, sensors and model bias; compare RMSE and spread.

Compare RMSE with spread across several independent realizations. If spread is small and error grows, overconfidence is plausible; it does not alone identify the optimal inflation or radius. Ensemble smoothers reuse future observations to correct past states; hybrid methods combine static and flow-dependent covariances. None automatically eliminates model error.

Ensemble Kalman inversion

In ensemble Kalman inversion (EKI), each member is a parameter θ(j)\vb\theta^{(j)} and the simulator produces G(θ(j))\mathcal G(\vb\theta^{(j)}). Sample cross-covariance between parameters and outputs updates the ensemble without differentiating G\mathcal G. To control repeated use of the same data, the lab distributes observation precision over tempered steps. Iterations remain in the initial affine parameter subspace: if truth lies outside, the update cannot reach it without enriching the ensemble. Final iterative EKI spread is not automatically calibrated posterior uncertainty.

Why particles collapse

In a bootstrap filter each particle receives a weight proportional to likelihood. Weight degeneracy occurs when a few dominate. For independent observed components, log-likelihood sums contributions; its variability can grow with effective dimension and cause the number of particles needed to grow very quickly. The result depends on posterior geometry and does not define a universal critical dimension.

InteractiveWeight collapse

100 replicates, 1000 independent N(0,I) particles, observation fixed at zero and N(0,I) noise; seed 121. Weights are normalized in log space. Collapse depends on model and effective dimension: this simulation sets no universal threshold. After resampling ESS can rise even when few distinct particles remain.

20
Mean maximum weight0.068
Mean ESS before resampling65.6
Observe maximum weight and effective size as observed dimension varies.

Resampling restores equal weights but may leave many duplicates. High ESS after resampling therefore does not prove diversity or recovery. Particle localization, transport and guided proposals seek to mitigate the problem, with their own trade-offs and assumptions.

Lab: cycles and calibration

We reuse exactly the previous lesson’s synthetic truth and observations: 40-variable Lorenz-96, eight windows and sensors every four positions. Stochastic EnKF, ETKF and LETKF use observation-noise variance 1. The particle filter uses 1000 members and systematic resampling after every observation. 3D-Var and 4D-Var retain the previous lab’s climatological covariance; ensemble methods start with perturbations of deviation 1. This is not a controlled contest over all possible backgrounds or proof of general superiority.

[ ]Previous lesson's variational modelBrowser
"""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
[ ]EnKF, ETKF, LETKF and particlesBrowser
"""EnKF, ETKF, LETKF y partículas para observaciones lineales."""
import numpy as np
from scipy.linalg import cho_factor,cho_solve
from scipy.special import logsumexp


def gaspari_cohn(distance,radius):
    """radio de escala: el soporte termina en distancia 2*radius."""
    q=np.abs(np.asarray(distance,float))/radius
    out=np.zeros_like(q);a=q<=1;b=(q>1)&(q<2)
    z=q[a];out[a]=1-5*z*z/3+5*z**3/8+z**4/2-z**5/4
    z=q[b];out[b]=4-5*z+5*z*z/3+5*z**3/8-z**4/2+z**5/12-2/(3*z)
    return np.clip(out,0,1)


def symmetric_inverse_sqrt(S):
    values,vectors=np.linalg.eigh((S+S.T)/2)
    if values.min()<=0:raise ValueError('La matriz debe ser definida positiva')
    return (vectors/np.sqrt(values))@vectors.T


def etkf_analysis(E,y,H,R,inflation=1.):
    """E tiene forma (estado, miembros); inflación multiplica anomalías."""
    n,N=E.shape;mean=E.mean(axis=1);A=(E-mean[:,None])*inflation
    Z=A/np.sqrt(N-1);Y=H@Z;cf=cho_factor(R,lower=True)
    RY=cho_solve(cf,Y);S=np.eye(N)+Y.T@RY
    w=np.linalg.solve(S,Y.T@cho_solve(cf,y-H@mean))
    return (mean+Z@w)[:,None]+np.sqrt(N-1)*Z@symmetric_inverse_sqrt(S)


def enkf_analysis(E,y,H,R,rng,inflation=1.):
    n,N=E.shape;mean=E.mean(axis=1);A=(E-mean[:,None])*inflation
    E=mean[:,None]+A;Y=H@A
    [email protected]/(N-1);[email protected]/(N-1)+R
    K=cho_solve(cho_factor(Cyy,lower=True),Cxy.T).T
    noise=rng.multivariate_normal(np.zeros(len(y)),R,size=N).T
    return E+K@(y[:,None]+noise-H@E)


def letkf_analysis(E,y,ids,variance,radius,inflation=1.):
    """LETKF local por nodo: observaciones independientes y distancia periódica."""
    n,N=E.shape;mean=E.mean(axis=1);A=(E-mean[:,None])*inflation
    Z=A/np.sqrt(N-1);Y=Z[ids,:];innovation=y-mean[ids]
    result=np.empty_like(E)
    for i in range(n):
        d=np.abs(ids-i);d=np.minimum(d,n-d)
        precision=gaspari_cohn(d,radius)/variance
        S=np.eye(N)+(Y.T*precision)@Y
        w=np.linalg.solve(S,Y.T@(precision*innovation))
        result[i,:]=mean[i]+Z[i]@w+np.sqrt(N-1)*Z[i]@symmetric_inverse_sqrt(S)
    return result


def l96(x,forcing=8.):
    return (np.roll(x,-1,axis=0)-np.roll(x,2,axis=0))*np.roll(x,1,axis=0)-x+forcing


def rk4(x,dt=.05,forcing=8.):
    a=l96(x,forcing);b=l96(x+dt*a/2,forcing)
    c=l96(x+dt*b/2,forcing);d=l96(x+dt*c,forcing)
    return x+dt*(a+2*b+2*c+d)/6


def particle_update(particles,y,ids,variance,rng):
    """Pesos normalizados estables y remuestreo sistemático."""
    logw=-.5*np.sum((particles[ids]-y[:,None])**2,axis=0)/variance
    w=np.exp(logw-logsumexp(logw));N=len(w)
    ess=1/np.sum(w*w);u=(rng.random()+np.arange(N))/N
    indices=np.searchsorted(np.cumsum(w),u,side='right')
    indices=np.minimum(indices,N-1)
    return particles[:,indices],ess,float(w.max())


def l96_observations(seed=22,cycles=8,dt=.05):
    """Exactamente la verdad y secuencia de medidas del laboratorio l21."""
    rng=np.random.default_rng(seed);truth=8+.1*rng.normal(size=40)
    for _ in range(500):truth=rk4(truth,dt)
    xb=truth+rng.normal(0,1,40);ids=np.arange(0,40,4);windows=[]
    for _ in range(cycles):
        states=[];ys=[]
        for _ in range(4):
            truth=rk4(truth,dt);states.append(truth.copy())
            ys.append(truth[ids]+rng.normal(size=len(ids)))
        windows.append((np.array(states),np.array(ys)))
    return xb,ids,windows


class EnsembleExperiment:
    def __init__(self,N=20,radius=4.,inflation=1.04,seed=101,particles=1000):
        self.N=N;self.radius=radius;self.inflation=inflation
        self.rng=np.random.default_rng(seed);self.rng_pf=np.random.default_rng(seed+1)
        self.xb,self.ids,self.windows=l96_observations()
        self.ensemble=self.xb[:,None]+self.rng.normal(0,1,(40,N))
        self.particles=self.xb[:,None]+self.rng_pf.normal(0,1,(40,particles))
        self.rows=[];self.index=0

    def advance(self,method='letkf'):
        states,ys=self.windows[self.index];ids=self.ids;H=np.eye(40)[ids];R=np.eye(len(ids))
        ess=[]
        for k in range(4):
            self.ensemble=rk4(self.ensemble);self.particles=rk4(self.particles)
            if method=='letkf':
                self.ensemble=letkf_analysis(self.ensemble,ys[k],ids,1.,self.radius,self.inflation)
            elif method=='etkf':
                self.ensemble=etkf_analysis(self.ensemble,ys[k],H,R,self.inflation)
            elif method=='enkf':
                self.ensemble=enkf_analysis(self.ensemble,ys[k],H,R,self.rng,self.inflation)
            else:raise ValueError('método desconocido')
            self.particles,e,_=particle_update(self.particles,ys[k],ids,1.,self.rng_pf);ess.append(e)
        truth=states[-1];mean=self.ensemble.mean(axis=1)
        rmse=np.sqrt(np.mean((mean-truth)**2))
        spread=np.sqrt(np.var(self.ensemble,axis=1,ddof=1).mean())
        pf_rmse=np.sqrt(np.mean((self.particles.mean(axis=1)-truth)**2))
        unique=len(np.unique(self.particles.T,axis=0))
        self.index+=1;self.rows.append((rmse,spread,pf_rmse,np.mean(ess),unique))
        return self.rows[-1]
[ ]Check ETKF and localizationBrowser
rng=np.random.default_rng(7);E=rng.normal(size=(6,30));H=rng.normal(size=(3,6))
R=np.diag([.7,1.,1.3]);y=rng.normal(size=3);inflation=1.1
m=E.mean(axis=1);P=np.cov(E)*inflation**2
K=np.linalg.solve(H@[email protected]+R,H@P).T
expected=m+K@(y-H@m);expectedP=P-K@H@P
analysed=etkf_analysis(E,y,H,R,inflation)
print('Errores ETKF media y covarianza:',np.max(abs(analysed.mean(axis=1)-expected)),
      np.max(abs(np.cov(analysed)-expectedP)))
print('Gaspari-Cohn a 0, 1 y 2 radios:',gaspari_cohn(np.array([0.,1.,2.]),1.))
assert np.allclose(analysed.mean(axis=1),expected,atol=1e-10)
assert np.allclose(np.cov(analysed),expectedP,atol=1e-10)

The test compares with Kalman using inflated sample covariance, not an unknown population covariance. LETKF weights each local observation’s precision and applies a different transformation per node; stochastic EnKF uses independent perturbations.

[ ]Prepare the previous lesson's experimentBrowser
B=climatological_covariance()
baseline=TwinExperiment(B)
[ ]3D/4D reference, window 1Browser
print(baseline.advance())
[ ]3D/4D reference, window 2Browser
print(baseline.advance())
[ ]3D/4D reference, window 3Browser
print(baseline.advance())
[ ]3D/4D reference, window 4Browser
print(baseline.advance())
[ ]3D/4D reference, window 5Browser
print(baseline.advance())
[ ]3D/4D reference, window 6Browser
print(baseline.advance())
[ ]3D/4D reference, window 7Browser
print(baseline.advance())
[ ]3D/4D reference, window 8Browser
print(baseline.advance())
[ ]Reference summaryBrowser
base=np.array([r[:4] for r in baseline.rows])
print('RMSE medio análisis y pronóstico 3D/4D:',base.mean(axis=0))

Each run below computes eight windows on the same data with a separate particle-filter seed. Output records ensemble RMSE and spread, particle RMSE, mean ESS before resampling and final number of distinct particle states. ESS can be high when all surviving particles are already identical.

[ ]Stochastic EnKFBrowser
run=EnsembleExperiment(N=20,radius=4,inflation=1.04)
for _ in range(8): run.advance('enkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))
[ ]ETKFBrowser
run=EnsembleExperiment(N=20,radius=4,inflation=1.04)
for _ in range(8): run.advance('etkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))
[ ]Reference LETKFBrowser
run=EnsembleExperiment(N=20,radius=4,inflation=1.04)
for _ in range(8): run.advance('letkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))
[ ]LETKF with ten membersBrowser
run=EnsembleExperiment(N=10,radius=4,inflation=1.04)
for _ in range(8): run.advance('letkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))
[ ]LETKF with short radiusBrowser
run=EnsembleExperiment(N=20,radius=1,inflation=1.04)
for _ in range(8): run.advance('letkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))
[ ]LETKF without inflationBrowser
run=EnsembleExperiment(N=20,radius=4,inflation=1)
for _ in range(8): run.advance('letkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))
[ ]LETKF with forty membersBrowser
run=EnsembleExperiment(N=40,radius=4,inflation=1.04)
for _ in range(8): run.advance('letkf')
result=np.array(run.rows)
print('medias RMSE, spread, RMSE partículas, ESS:',result[:,:4].mean(axis=0))
print('partículas distintas al final:',int(result[-1,4]))

These results are one realization with a perfect model. Effective size before resampling can approach 1000 after the filter has already collapsed to one trajectory; hence the number of distinct states is shown. Size, radius and inflation are varied one at a time against reference LETKF; changing multiple factors or the seed can change the comparison.

Lab: calibration without gradients

Now calibrate scalar forcing FF of 20-variable Lorenz-96 with known initial condition and ten synthetic observations after 25 steps. Truth is F=8.5F=8.5 and the ensemble prior is normal with mean 7 and deviation 1. Generator and inverse share the same model: this is a perfect-model example, not validation against a different simulator. EKI distributes observation precision over twenty updates, while the adjoint optimizer minimizes MAP cost with the same prior. EKI mean and MAP are not generally the same estimator.

[ ]EKI and forcing adjoint gradientBrowser
"""Calibración escalar por EKI y adjunto discreto de Lorenz-96."""
import time
import numpy as np
from scipy.optimize import minimize


def f96(x,F):
    return (np.roll(x,-1,axis=0)-np.roll(x,2,axis=0))*np.roll(x,1,axis=0)-x+F


def f96_transpose(x,w):
    b=np.roll(x,1)*w
    return np.roll((np.roll(x,-1)-np.roll(x,2))*w,-1)+np.roll(b,1)-np.roll(b,-2)-w


def step_force(x,F,dt):
    a=f96(x,F);s2=x+dt*a/2;b=f96(s2,F)
    s3=x+dt*b/2;c=f96(s3,F);s4=x+dt*c;d=f96(s4,F)
    return x+dt*(a+2*b+2*c+d)/6,(x,s2,s3,s4)


def adjoint_force(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
    gf=np.sum(b4);v=f96_transpose(s4,b4);bx+=v;b3+=dt*v
    gf+=np.sum(b3);v=f96_transpose(s3,b3);bx+=v;b2+=dt*v/2
    gf+=np.sum(b2);v=f96_transpose(s2,b2);bx+=v;b1+=dt*v/2
    gf+=np.sum(b1);bx+=f96_transpose(x,b1)
    return bx,gf


def forward_force(x0,F,steps=25,dt=.03):
    x=np.array(x0,float);caches=[]
    for _ in range(steps):
        x,c=step_force(x,F,dt);caches.append(c)
    return x,caches


def calibration_data(seed=88):
    rng=np.random.default_rng(seed);x0=8+rng.normal(0,1,20)
    ids=np.arange(0,20,2);true_F=8.5;noise=.15
    state,_=forward_force(x0,true_F)
    y=state[ids]+rng.normal(0,noise,len(ids))
    return x0,ids,y,noise,true_F


def force_cost(F,x0,ids,y,noise,prior_mean=7.,prior_sd=1.):
    state,caches=forward_force(x0,float(F));res=(state[ids]-y)/noise
    value=.5*res@res+.5*((F-prior_mean)/prior_sd)**2
    adj=np.zeros(len(x0));adj[ids]=res/noise;grad=(F-prior_mean)/prior_sd**2
    for cache in reversed(caches):
        adj,g=adjoint_force(cache,adj,.03);grad+=g
    return float(value),float(grad)


def calibrate_eki(seed=94,N=30,iterations=20):
    x0,ids,y,noise,true_F=calibration_data();rng=np.random.default_rng(seed)
    E=rng.normal(7,1,N);trajectory=[E.copy()];evaluations=0
    start=time.perf_counter()
    for _ in range(iterations):
        states=np.repeat(x0[:,None],N,axis=1)
        for _ in range(25):states,_=step_force(states,E,.03)
        G=states[ids];e=E-E.mean();A=G-G.mean(axis=1,keepdims=True)
        [email protected]/(N-1);[email protected]/(N-1)+iterations*noise**2*np.eye(len(ids))
        gain=np.linalg.solve(cov,cross)
        pert=rng.normal(0,noise*np.sqrt(iterations),(len(ids),N))
        E=E+gain@(y[:,None]+pert-G);trajectory.append(E.copy());evaluations+=N
    elapsed_eki=time.perf_counter()-start
    calls=[0]
    def objective(z):
        calls[0]+=1;v,g=force_cost(z[0],x0,ids,y,noise);return v,np.array([g])
    start=time.perf_counter()
    result=minimize(objective,np.array([7.]),jac=True,method='L-BFGS-B')
    elapsed_adj=time.perf_counter()-start
    return {'truth':true_F,'eki_mean':E.mean(),'eki_sd':E.std(ddof=1),
            'adjoint_map':result.x[0],'adjoint_success':result.success,
            'eki_forwards':evaluations,'adjoint_forwards':calls[0],
            'eki_seconds':elapsed_eki,'adjoint_seconds':elapsed_adj,
            'trajectory':np.array(trajectory)}
[ ]Verify gradient and calibrateBrowser
x0,ids,y,noise,true_F=calibration_data()
value,grad=force_cost(7.4,x0,ids,y,noise)
h=1e-5
fd=(force_cost(7.4+h,x0,ids,y,noise)[0]-force_cost(7.4-h,x0,ids,y,noise)[0])/(2*h)
print('Gradiente adjunto y diferencia central:',grad,fd)
assert np.isclose(grad,fd,rtol=1e-7)
result=calibrate_eki()
for key in ['truth','eki_mean','eki_sd','adjoint_map','adjoint_success',
            'eki_forwards','adjoint_forwards','eki_seconds','adjoint_seconds']:
    print(key,result[key])

The EKI count expresses equivalent member evaluations, though grouped into vectorized batches. Times belong to this run and should not be treated as a general benchmark: implementations and hardware matter. EKI avoids differentiating the simulator; the adjoint requires implementing its derivative, but one gradient evaluation can inform many parameters. Final EKI spread is descriptive, not a coverage guarantee.

Exercises

ProofCovariance without perturbations
Prove: Prove what happens if all members use the same observation.
0
H and K are linear and P is the sample forecast covariance.

Step 1 of 3. How do anomalies transform?

ProofEKI affine subspace
Prove: Explain why EKI remains in the affine space generated by its initial members.
0
No perturbations are added directly to parameters.

Step 1 of 3. Which columns combine to form each parameter increment?

Numeric
For 20 independent Gaussian pairs with zero true correlation, what is the exact standard deviation of sample correlation?
Quiz
A filter shows small spread and growing RMSE. What initial diagnosis is most reasonable?
CodeETKF analysis
Implement etkf_analysis(E,y,H,R,inflation): E has shape state × members; inflation multiplies anomalies. Return the analysis ensemble using a symmetric root in ensemble space. R is positive definite.
import numpy as np
def etkf_analysis(E,y,H,R,inflation=1.):
  # Devuelve un conjunto (estado, miembros).
  return E
Shift+Enter to run
Key idea
Ensembles approximate covariances tractably, but need rank, localization, spread and diversity diagnostics for interpretable results.

References