Nonlinear Gaussian filtering: EKF and UKF
When dynamics or observations are nonlinear, an approximate Gaussian is maintained. We derive the extended Kalman filter (linearization), its iterated version (Gauss-Newton), the unscented transform and UKF, and present them as cases of moment-matching assumed-density filtering, which returns in expectation propagation.
After this lesson you can
- Derive the EKF by linearizing dynamics and observation and explain its bias.
- Interpret the iterated EKF as Gauss-Newton on the one-step posterior.
- Construct sigma points and weights of the unscented transform and prove which moments they reproduce.
- Implement EKF and UKF for range-and-bearing localization with beacons and assess consistency with NEES.
- Frame EKF, UKF and cubature filters as quadrature choices in Gaussian filtering.
Before you start
- 14Kalman filterKalman gainInnovations and prediction error decompositionNumerical stability of the Kalman filterLinear Gaussian state-space modelMoment-matching (M-) projection
- 03Jacobian matrixLinearization and tangent plane
- 09Gauss-Hermite quadrature for Gaussian expectationsGaussian quadratureForward-mode automatic differentiationReverse-mode automatic differentiation
- 06Gauss-Newton method
Keeping a Gaussian when the model is nonlinear
A radar measures range and bearing, but Cartesian position is not a linear function of those measurements. In a nonlinear state-space model,
a Gaussian input need not produce a Gaussian output. Assumed-density filtering replaces the distribution with a manageable family, here a Gaussian, approximating its moments at each step. If exact moments exist, the Gaussian minimizing over Gaussians matches mean and covariance. EKF and UKF use different moment approximations; an approximation with negative weights can even produce an invalid covariance.
The example’s radius and bearing are independent normals, with radial mean 4 and standard deviation 0.25. The exact Cartesian mean on the horizontal axis is , while transforming at the mean gives 4. Uncertain bearing yields a curved cloud that a single ellipse cannot represent. Ellipses show covariances of Gaussian approximations; they are not necessarily 95% coverage regions for the non-Gaussian cloud.
EKF and its iterated version
The extended Kalman filter (EKF) approximates and by first-order expansions. With evaluated at the previous mean and at the predictive mean,
Gain, innovation and covariance update as in Kalman using predicted observation . Linearization can ignore curvature and underestimate uncertainty. If near a zero mean, its derivative there is zero although the measurement contains information about ; the posterior can be bimodal and a single Gaussian cannot represent it.
The iterated EKF relinearizes the observation within the update. For a one-step prior it seeks the minimum of
Gauss-Newton uses the Jacobian at the current iteration; equivalently, with calculated from and ,
The prior stays the same during iterations: the same observation is not counted again as if it were independent measurements. Iteration can require damping or line search and may converge to a local minimum. With angles, state and observation differences must respect their geometry.
The unscented transform
The unscented transform propagates deterministic points that reproduce input mean and covariance. For and , use and . The weights are
We need and a covariance suitable for Cholesky. The mean of a quadratic function is exact under these input moments, but this neither makes the transformed distribution Gaussian nor guarantees exact covariance for every nonlinear function. controls scale, modifies the central covariance weight and enters the scale. Negative central weights are possible; with some parameters the approximate output covariance can cease to be positive semidefinite.
The reconstructed input covariance is the original in exact arithmetic. The figure also transforms points with and calculates the smallest eigenvalue of the resulting covariance. A negative eigenvalue indicates an invalid approximation, not a negative physical variance. Extremely small can cause cancellation between large weights even when the formula is algebraically valid.
The UKF applies the transform to dynamics and observation to approximate their means, covariances and cross-covariance. It then performs a Gaussian update. Cubature filters use another point rule to approximate Gaussian integrals. Both avoid deriving Jacobians, but require several function evaluations per step and do not on their own solve multimodality or all numerical difficulties.
The figure discretizes a damped pendulum with Euler and uses a noisy measurement of . That observation is ambiguous and the posterior may be non-Gaussian. Errors and NEES for one trajectory are shown, with angular states wrapped; a time average is not a consistency test with independent samples. Comparison depends on parameters: there is no guarantee that UKF is always consistent or superior.
Angles and consistency
In beacon localization, a bearing measurement near and a prediction near differ little, not almost . Calculate angular residual with consistent wrapping and also use angular differences when forming covariances. The lab uses and an angular mean anchored to the prediction when sigma points stay nearby; distributions covering the whole circle require more care.
The NEES of a state of dimension is , with wrapped angular error. In independent simulations, under ideal Gaussian consistency assumptions, the sum of final NEES follows and the mean is compared with its quantiles divided by . That reference does not guarantee an approximate EKF or UKF posterior is Gaussian. Covariance inflation can mitigate overconfidence, but does not automatically fix bias, multimodality or a wrong model.
Lab: robot and beacons
The robot has state and speed and turning controls; a known beacon provides range and relative bearing. Jacobians are checked by central differences. Iterated EKF uses up to six iterations per observation and UKF uses with wrapped angular residuals.
"""EKF, EKF iterado y UKF para un robot con distancia y rumbo."""
import numpy as np
from scipy.linalg import cho_factor,cho_solve
def wrap(a):
return (a+np.pi)%(2*np.pi)-np.pi
def sigma_points(m,P,alpha=.4,beta=2.,kappa=0.):
m=np.asarray(m,float);P=np.asarray(P,float);n=len(m)
lam=alpha**2*(n+kappa)-n;c=n+lam
if c<=0:raise ValueError('n+lambda debe ser positivo')
L=np.linalg.cholesky(c*P)
points=np.vstack([m,m+L.T,m-L.T])
wm=np.full(2*n+1,1/(2*c));wc=wm.copy();wm[0]=lam/c
wc[0]=wm[0]+1-alpha**2+beta
return points,wm,wc
def unscented_transform(f,m,P,alpha=.4,beta=2.,kappa=0.):
points,wm,wc=sigma_points(m,P,alpha,beta,kappa)
values=np.array([np.atleast_1d(f(x)) for x in points])
mean=wm@values;centered=values-mean
cov=np.einsum('i,ij,ik->jk',wc,centered,centered)
return mean,(cov+cov.T)/2
def motion(x,u,dt=1.):
px,py,theta=x;v,omega=u
return np.array([px+v*dt*np.cos(theta),py+v*dt*np.sin(theta),wrap(theta+omega*dt)])
def motion_jac(x,u,dt=1.):
theta=x[2];v=u[0]
return np.array([[1.,0.,-v*dt*np.sin(theta)],[0.,1.,v*dt*np.cos(theta)],[0.,0.,1.]])
def observe(x,landmark):
d=np.asarray(landmark)-x[:2];r=np.hypot(*d)
if r<1e-8:raise ValueError('Rumbo indefinido en la baliza')
return np.array([r,wrap(np.arctan2(d[1],d[0])-x[2])])
def observe_jac(x,landmark):
dx,dy=np.asarray(landmark)-x[:2];r=np.hypot(dx,dy)
if r<1e-8:raise ValueError('Rumbo indefinido en la baliza')
return np.array([[-dx/r,-dy/r,0.],[dy/r**2,-dx/r**2,-1.]])
def delta_state(x,y):
d=np.asarray(x)-np.asarray(y);d=d.copy();d[-1]=wrap(d[-1]);return d
def delta_obs(x,y):
d=np.asarray(x)-np.asarray(y);d=d.copy();d[-1]=wrap(d[-1]);return d
def gain(P,H,R):
S=H@[email protected]+R
return cho_solve(cho_factor(S,lower=True),H@P).T
def ekf_step(m,P,u,y,landmark,Q,R,iterations=1):
F=motion_jac(m,u);mp=motion(m,u);Pp=F@[email protected]+Q;Pp=(Pp+Pp.T)/2
x=mp.copy()
for _ in range(iterations):
H=observe_jac(x,landmark);K=gain(Pp,H,R)
residual=delta_obs(y,observe(x,landmark))+H@delta_state(x,mp)
nxt=mp+K@residual;nxt[-1]=wrap(nxt[-1])
change=np.linalg.norm(delta_state(nxt,x));x=nxt
if change<1e-9:break
H=observe_jac(x if iterations>1 else mp,landmark);K=gain(Pp,H,R)
J=np.eye(len(m))-K@H;Pnew=J@[email protected]+K@[email protected]
return x,(Pnew+Pnew.T)/2
def anchored_mean(points,weights,angle_idx,anchor):
out=weights@points
out[angle_idx]=wrap(anchor+weights@wrap(points[:,angle_idx]-anchor))
return out
def ukf_step(m,P,u,y,landmark,Q,R,alpha=.4,beta=2.,kappa=0.):
pts,wm,wc=sigma_points(m,P,alpha,beta,kappa)
prop=np.array([motion(s,u) for s in pts]);mp=anchored_mean(prop,wm,2,motion(m,u)[2])
dp=np.array([delta_state(s,mp) for s in prop])
Pp=np.einsum('i,ij,ik->jk',wc,dp,dp)+Q;Pp=(Pp+Pp.T)/2
pts,wm,wc=sigma_points(mp,Pp,alpha,beta,kappa)
obs=np.array([observe(s,landmark) for s in pts])
ym=anchored_mean(obs,wm,1,observe(mp,landmark)[1])
dx=np.array([delta_state(s,mp) for s in pts]);dy=np.array([delta_obs(s,ym) for s in obs])
S=np.einsum('i,ij,ik->jk',wc,dy,dy)+R
C=np.einsum('i,ij,ik->jk',wc,dx,dy)
K=cho_solve(cho_factor(S,lower=True),C.T).T
mnew=mp+K@delta_obs(y,ym);mnew[-1]=wrap(mnew[-1])
Pnew=Pp-K@[email protected]
return mnew,(Pnew+Pnew.T)/2
def robot_trial(seed,T=30):
rng=np.random.default_rng(seed)
P0=np.diag([.25**2,.25**2,.2**2]);Q=np.diag([.02**2,.02**2,.01**2])
R=np.diag([.15**2,.05**2]);u=np.array([.25,.08])
landmarks=np.array([[-2.,-2.],[8.,-1.],[2.,8.]])
truth=rng.multivariate_normal(np.zeros(3),P0);truth[-1]=wrap(truth[-1])
means=[np.zeros(3) for _ in range(3)];covs=[P0.copy() for _ in range(3)]
sq=np.zeros(3);nees=np.zeros(3)
for t in range(T):
truth=motion(truth,u)+rng.multivariate_normal(np.zeros(3),Q);truth[-1]=wrap(truth[-1])
beacon=landmarks[t%len(landmarks)]
y=observe(truth,beacon)+rng.multivariate_normal(np.zeros(2),R);y[-1]=wrap(y[-1])
means[0],covs[0]=ekf_step(means[0],covs[0],u,y,beacon,Q,R)
means[1],covs[1]=ekf_step(means[1],covs[1],u,y,beacon,Q,R,iterations=6)
means[2],covs[2]=ukf_step(means[2],covs[2],u,y,beacon,Q,R)
for k in range(3):
error=delta_state(means[k],truth);sq[k]+=error[0]**2+error[1]**2
nees[k][email protected](covs[k],error)
return sq/T,neesm=np.array([1.,2.,.3]);P=np.diag([.3,.2,.1])
u=np.array([.25,.08]);beacon=np.array([2.,8.]);eye=np.eye(3);eps=1e-6
numF=np.column_stack([(motion(m+eps*v,u)-motion(m-eps*v,u))/(2*eps) for v in eye])
numH=np.column_stack([delta_obs(observe(m+eps*v,beacon),observe(m-eps*v,beacon))/(2*eps) for v in eye])
pts,wm,wc=sigma_points(m,P);centered=pts-wm@pts
print('errores jacobianos:',np.max(abs(numF-motion_jac(m,u))),np.max(abs(numH-observe_jac(m,beacon))))
print('errores media y covarianza sigma:',np.max(abs(wm@pts-m)),
np.max(abs(np.einsum('i,ij,ik->jk',wc,centered,centered)-P)))
assert np.allclose(numF,motion_jac(m,u),atol=1e-8)
assert np.allclose(numH,observe_jac(m,beacon),atol=1e-8)
Run one hundred independent simulations in blocks of ten, in order. To repeat the experiment, first rerun the preparation cell, which empties accumulators. Each simulation has 30 steps, three alternating beacons, the same controls and noise specified in code. RMSE is Euclidean position error averaged over steps and simulations; NEES is evaluated only at the final state of each simulation.
sq=[];nees=[]
def block(start):
for i in range(start,start+10):
a,b=robot_trial(1000+i);sq.append(a);nees.append(b)
print('simulaciones acumuladas:',len(sq))
block(0)block(10)block(20)block(30)block(40)block(50)block(60)block(70)block(80)block(90)from scipy.stats import chi2
print('Orden: EKF, EKF iterado, UKF')
print('RMSE posición:',np.sqrt(np.mean(sq,axis=0)))
print('NEES final media:',np.mean(nees,axis=0))
print('intervalo 95 % de referencia, 100 estados 3D:',chi2.ppf([.025,.975],300)/100)
assert len(sq)==100 and len(nees)==100
In this run RMSE values are 0.11026, 0.11004 and 0.11010, and mean final NEES values 2.616, 2.614 and 2.615. The reference interval is approximately [2.539, 3.499]. Differences are small for this configuration; being inside the interval does not demonstrate general consistency.
The next local cell recalculates Jacobians with torch.func.jacrev and compares twenty EKF steps with the FilterPy update. It requires PyTorch and FilterPy locally. The comparison uses the same prior, noise, measurements and angular residual.
"""EKF, EKF iterado y UKF para un robot con distancia y rumbo."""
import numpy as np
from scipy.linalg import cho_factor,cho_solve
def wrap(a):
return (a+np.pi)%(2*np.pi)-np.pi
def sigma_points(m,P,alpha=.4,beta=2.,kappa=0.):
m=np.asarray(m,float);P=np.asarray(P,float);n=len(m)
lam=alpha**2*(n+kappa)-n;c=n+lam
if c<=0:raise ValueError('n+lambda debe ser positivo')
L=np.linalg.cholesky(c*P)
points=np.vstack([m,m+L.T,m-L.T])
wm=np.full(2*n+1,1/(2*c));wc=wm.copy();wm[0]=lam/c
wc[0]=wm[0]+1-alpha**2+beta
return points,wm,wc
def unscented_transform(f,m,P,alpha=.4,beta=2.,kappa=0.):
points,wm,wc=sigma_points(m,P,alpha,beta,kappa)
values=np.array([np.atleast_1d(f(x)) for x in points])
mean=wm@values;centered=values-mean
cov=np.einsum('i,ij,ik->jk',wc,centered,centered)
return mean,(cov+cov.T)/2
def motion(x,u,dt=1.):
px,py,theta=x;v,omega=u
return np.array([px+v*dt*np.cos(theta),py+v*dt*np.sin(theta),wrap(theta+omega*dt)])
def motion_jac(x,u,dt=1.):
theta=x[2];v=u[0]
return np.array([[1.,0.,-v*dt*np.sin(theta)],[0.,1.,v*dt*np.cos(theta)],[0.,0.,1.]])
def observe(x,landmark):
d=np.asarray(landmark)-x[:2];r=np.hypot(*d)
if r<1e-8:raise ValueError('Rumbo indefinido en la baliza')
return np.array([r,wrap(np.arctan2(d[1],d[0])-x[2])])
def observe_jac(x,landmark):
dx,dy=np.asarray(landmark)-x[:2];r=np.hypot(dx,dy)
if r<1e-8:raise ValueError('Rumbo indefinido en la baliza')
return np.array([[-dx/r,-dy/r,0.],[dy/r**2,-dx/r**2,-1.]])
def delta_state(x,y):
d=np.asarray(x)-np.asarray(y);d=d.copy();d[-1]=wrap(d[-1]);return d
def delta_obs(x,y):
d=np.asarray(x)-np.asarray(y);d=d.copy();d[-1]=wrap(d[-1]);return d
def gain(P,H,R):
S=H@[email protected]+R
return cho_solve(cho_factor(S,lower=True),H@P).T
def ekf_step(m,P,u,y,landmark,Q,R,iterations=1):
F=motion_jac(m,u);mp=motion(m,u);Pp=F@[email protected]+Q;Pp=(Pp+Pp.T)/2
x=mp.copy()
for _ in range(iterations):
H=observe_jac(x,landmark);K=gain(Pp,H,R)
residual=delta_obs(y,observe(x,landmark))+H@delta_state(x,mp)
nxt=mp+K@residual;nxt[-1]=wrap(nxt[-1])
change=np.linalg.norm(delta_state(nxt,x));x=nxt
if change<1e-9:break
H=observe_jac(x if iterations>1 else mp,landmark);K=gain(Pp,H,R)
J=np.eye(len(m))-K@H;Pnew=J@[email protected]+K@[email protected]
return x,(Pnew+Pnew.T)/2
def anchored_mean(points,weights,angle_idx,anchor):
out=weights@points
out[angle_idx]=wrap(anchor+weights@wrap(points[:,angle_idx]-anchor))
return out
def ukf_step(m,P,u,y,landmark,Q,R,alpha=.4,beta=2.,kappa=0.):
pts,wm,wc=sigma_points(m,P,alpha,beta,kappa)
prop=np.array([motion(s,u) for s in pts]);mp=anchored_mean(prop,wm,2,motion(m,u)[2])
dp=np.array([delta_state(s,mp) for s in prop])
Pp=np.einsum('i,ij,ik->jk',wc,dp,dp)+Q;Pp=(Pp+Pp.T)/2
pts,wm,wc=sigma_points(mp,Pp,alpha,beta,kappa)
obs=np.array([observe(s,landmark) for s in pts])
ym=anchored_mean(obs,wm,1,observe(mp,landmark)[1])
dx=np.array([delta_state(s,mp) for s in pts]);dy=np.array([delta_obs(s,ym) for s in obs])
S=np.einsum('i,ij,ik->jk',wc,dy,dy)+R
C=np.einsum('i,ij,ik->jk',wc,dx,dy)
K=cho_solve(cho_factor(S,lower=True),C.T).T
mnew=mp+K@delta_obs(y,ym);mnew[-1]=wrap(mnew[-1])
Pnew=Pp-K@[email protected]
return mnew,(Pnew+Pnew.T)/2
def robot_trial(seed,T=30):
rng=np.random.default_rng(seed)
P0=np.diag([.25**2,.25**2,.2**2]);Q=np.diag([.02**2,.02**2,.01**2])
R=np.diag([.15**2,.05**2]);u=np.array([.25,.08])
landmarks=np.array([[-2.,-2.],[8.,-1.],[2.,8.]])
truth=rng.multivariate_normal(np.zeros(3),P0);truth[-1]=wrap(truth[-1])
means=[np.zeros(3) for _ in range(3)];covs=[P0.copy() for _ in range(3)]
sq=np.zeros(3);nees=np.zeros(3)
for t in range(T):
truth=motion(truth,u)+rng.multivariate_normal(np.zeros(3),Q);truth[-1]=wrap(truth[-1])
beacon=landmarks[t%len(landmarks)]
y=observe(truth,beacon)+rng.multivariate_normal(np.zeros(2),R);y[-1]=wrap(y[-1])
means[0],covs[0]=ekf_step(means[0],covs[0],u,y,beacon,Q,R)
means[1],covs[1]=ekf_step(means[1],covs[1],u,y,beacon,Q,R,iterations=6)
means[2],covs[2]=ukf_step(means[2],covs[2],u,y,beacon,Q,R)
for k in range(3):
error=delta_state(means[k],truth);sq[k]+=error[0]**2+error[1]**2
nees[k][email protected](covs[k],error)
return sq/T,nees
"""Autodiferenciación PyTorch y actualización EKF de FilterPy."""
import torch
from torch.func import jacrev
from filterpy.kalman import ExtendedKalmanFilter
torch.set_default_dtype(torch.float64)
u=np.array([.25,.08]);beacon=np.array([2.,8.])
def torch_motion(x):
return torch.stack((x[0]+u[0]*torch.cos(x[2]),
x[1]+u[0]*torch.sin(x[2]),
torch.atan2(torch.sin(x[2]+u[1]),torch.cos(x[2]+u[1]))))
def torch_observe(x):
dx=beacon[0]-x[0];dy=beacon[1]-x[1]
angle=torch.atan2(dy,dx)-x[2]
return torch.stack((torch.sqrt(dx*dx+dy*dy),torch.atan2(torch.sin(angle),torch.cos(angle))))
def jmotion(x):return jacrev(torch_motion)(torch.tensor(x)).detach().numpy()
def jobserve(x):return jacrev(torch_observe)(torch.tensor(x)).detach().numpy()
def htorch(x):return torch_observe(torch.tensor(x)).detach().numpy()
sample=np.array([1.,2.,.3])
print('errores jacrev F/H:',np.max(abs(jmotion(sample)-motion_jac(sample,u))),
np.max(abs(jobserve(sample)-observe_jac(sample,beacon))))
rng=np.random.default_rng(6);Q=np.diag([.02**2,.02**2,.01**2]);R=np.diag([.15**2,.05**2])
m=np.zeros(3);P=np.diag([.25**2,.25**2,.2**2]);truth=np.array([.1,-.1,.12])
mx=m.copy();Px=P.copy();lib=ExtendedKalmanFilter(dim_x=3,dim_z=2);lib.R=R
for _ in range(20):
truth=motion(truth,u)+rng.multivariate_normal(np.zeros(3),Q);truth[2]=wrap(truth[2])
y=observe(truth,beacon)+rng.multivariate_normal(np.zeros(2),R);y[1]=wrap(y[1])
m,P=ekf_step(m,P,u,y,beacon,Q,R)
F=jmotion(mx);mx=torch_motion(torch.tensor(mx)).detach().numpy()
Px=F@[email protected]+Q
lib.x=mx.copy();lib.P=Px.copy()
lib.update(y,HJacobian=jobserve,Hx=htorch,residual=delta_obs)
mx=lib.x.copy();mx[2]=wrap(mx[2]);Px=lib.P.copy()
print('error máximo FilterPy/autodiff estado y covarianza:',
np.max(abs(delta_state(mx,m))),np.max(abs(Px-P)))
assert np.allclose(mx,m,atol=1e-8) and np.allclose(Px,P,atol=1e-8)npm run lab and open the connection link.Exercises
Step 1 of 3. What is the weighted sum of points?
import numpy as np
def unscented_transform(f,m,P,alpha,beta,kappa):
return None,None