Module contents
Lesson 14 of 27Advanced 100 min

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

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,

xt=f(xt−1,ut)+wt,yt=h(xt)+vt,\vb x_t=f(\vb x_{t-1},\vb u_t)+\vb w_t,\qquad \vb y_t=h(\vb x_t)+\vb v_t,

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 KL⁡(p∥q)\operatorname{KL}(p\|q) over Gaussians matches mean and covariance. EKF and UKF use different moment approximations; an approximation with negative weights can even produce an invalid covariance.

InteractiveThe polar banana
  • 500 samples
  • EKF 95 %
  • Gaussian UT 95 %
  • exact mean

Normal radius with mean 4 and standard deviation 0.25, normal bearing centered at zero; independent. Samples use seed 33. Ellipses summarize covariance, and do not necessarily contain 95 % of a transformed non-Gaussian distribution.

0.60
Exact mean x3.341
Linearized mean x4.000
Unscented mean x3.301
UKF covariance validyes
Transform a polar cloud and compare its moments with a linearization and the unscented transform.

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 4e−σθ2/24e^{-\sigma_\theta^2/2}, 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 ff and hh by first-order expansions. With Ft=∂f/∂x\mat F_t=\partial f/\partial\vb x evaluated at the previous mean and Ht=∂h/∂x\mat H_t=\partial h/\partial\vb x at the predictive mean,

mt−=f(mt−1,ut),Pt−=FtPt−1Ft⊤+Q,St=HtPt−Ht⊤+R.\vb m_t^-=f(\vb m_{t-1},\vb u_t),\quad \mat P_t^-=\mat F_t\mat P_{t-1}\mat F_t\T+\mat Q,\quad \mat S_t=\mat H_t\mat P_t^-\mat H_t\T+\mat R.

Gain, innovation and covariance update as in Kalman using predicted observation h(mt−)h(\vb m_t^-). Linearization can ignore curvature and underestimate uncertainty. If h(x)=x2h(x)=x^2 near a zero mean, its derivative there is zero although the measurement contains information about ∣x∣|x|; 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 N(m−,P−)\Normal(\vb m^-,\mat P^-) it seeks the minimum of

12∥x−m−∥(P−)−12+12∥y−h(x)∥R−12.\tfrac12\|\vb x-\vb m^-\|^2_{(\mat P^-)^{-1}} +\tfrac12\|\vb y-h(\vb x)\|^2_{\mat R^{-1}}.

Gauss-Newton uses the Jacobian at the current iteration; equivalently, with Kk\mat K_k calculated from P−\mat P^- and Hk\mat H_k,

xk+1=m−+Kk[y−h(xk)+Hk(xk−m−)].\vb x_{k+1}=\vb m^-+\mat K_k[ \vb y-h(\vb x_k)+\mat H_k(\vb x_k-\vb m^-)].

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 2n+12n+1 deterministic points that reproduce input mean and covariance. For λ=α2(n+κ)−n\lambda=\alpha^2(n+\kappa)-n and LL⊤=(n+λ)P\mat L\mat L\T=(n+\lambda)\mat P, use χ0=m\chi_0=\vb m and χi=m±L:i\chi_i=\vb m\pm\mat L_{:i}. The weights are

w0(m)=λn+λ,w0(c)=w0(m)+1−α2+β,wi(m)=wi(c)=12(n+λ).w_0^{(m)}=\frac{\lambda}{n+\lambda},\qquad w_0^{(c)}=w_0^{(m)}+1-\alpha^2+\beta,\qquad w_i^{(m)}=w_i^{(c)}=\frac{1}{2(n+\lambda)}.

We need n+λ>0n+\lambda>0 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. α\alpha controls scale, β\beta modifies the central covariance weight and κ\kappa enters the scale. Negative central weights are possible; with some parameters the approximate output covariance can cease to be positive semidefinite.

InteractiveSigma points
  • negative mean weight
  • positive mean weight
  • prior 95 %

Fixed correlation 0.4 and test function f(x,y)=(x²,y²). Negative weights can occur; after a nonlinear transformation they can yield invalid covariance. Input reconstruction preserves its first two moments in exact arithmetic.

0.0
0.0
1.0
0.7
0.7
2.0
0.0
Central mean weight-1.041
Central covariance weight1.469
Input covariance error5.55e-17
Minimum eigenvalue after squaring0.23835
Output covariancepositive
Change mean, covariance and parameters, and also examine a quadratic transform.

The reconstructed input covariance is the original in exact arithmetic. The figure also transforms points with (x,y)↦(x2,y2)(x,y)\mapsto(x^2,y^2) and calculates the smallest eigenvalue of the resulting covariance. A negative eigenvalue indicates an invalid approximation, not a negative physical variance. Extremely small α\alpha 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.

InteractivePendulum: EKF and UKF
  • True angle
  • EKF
  • UKF

Synthetic damped pendulum, Euler discretization and sin(θ) measurement with standard deviation 0.2; fixed state noise and seed 55. Sine is ambiguous and angles wrap; lines can jump across ±π. Time-averaged NEES of one trajectory is not an independent χ² test.

0.20
0.5
EKF time-averaged NEES3.39
UKF time-averaged NEES3.51
Change initial uncertainty and time step of a simulation with sine measurements.

The figure discretizes a damped pendulum with Euler and uses a noisy measurement of sin⁡θ\sin\theta. 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 −π-\pi and a prediction near π\pi differ little, not almost 2π2\pi. Calculate angular residual with consistent wrapping and also use angular differences when forming covariances. The lab uses [−π,π)[-\pi,\pi) 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 dd is ε⊤P−1ε\varepsilon\T\mat P^{-1}\varepsilon, with wrapped angular error. In NN independent simulations, under ideal Gaussian consistency assumptions, the sum of final NEES follows χNd2\chi^2_{Nd} and the mean is compared with its quantiles divided by NN. 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 (x,y,θ)(x,y,\theta) 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 α=0.4,β=2,κ=0\alpha=0.4,\beta=2,\kappa=0 with wrapped angular residuals.

[ ]Nonlinear filters from scratchBrowser
"""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@P@H.T+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@P@F.T+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@Pp@J.T+K@R@K.T
    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@S@K.T
    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]=error@np.linalg.solve(covs[k],error)
    return sq/T,nees
[ ]Check Jacobians and momentsBrowser
m=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.

[ ]Prepare simulationsBrowser
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))
[ ]Simulations 1 to 10Browser
block(0)
[ ]Simulations 11 to 20Browser
block(10)
[ ]Simulations 21 to 30Browser
block(20)
[ ]Simulations 31 to 40Browser
block(30)
[ ]Simulations 41 to 50Browser
block(40)
[ ]Simulations 51 to 60Browser
block(50)
[ ]Simulations 61 to 70Browser
block(60)
[ ]Simulations 71 to 80Browser
block(70)
[ ]Simulations 81 to 90Browser
block(80)
[ ]Simulations 91 to 100Browser
block(90)
[ ]Compare RMSE and NEESBrowser
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.

[ ]Automatic Jacobians and FilterPyLocal GPU
"""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@P@H.T+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@P@F.T+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@Pp@J.T+K@R@K.T
    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@S@K.T
    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]=error@np.linalg.solve(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@Px@F.T+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)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofQuadratic mean with sigma points
Prove: Prove that the unscented mean is exact for f(x)=a+bx+cx² if x is a one-dimensional Gaussian.
0
Mean weights sum to one and points reproduce mean m and variance P.

Step 1 of 3. What is the weighted sum of points?

Numeric
In 1D, m=0, P=4, α=1, β=2 and κ=2. What is the positive sigma point?
Numeric
With the same parameters, what is the central mean weight?
Numeric
For 50 independent simulations and a state of dimension 3, what is the lower bound of the central 95 % interval of mean NEES?
Numeric
For those same 50 simulations, what is the upper bound of the central 95 % interval of mean NEES?
Quiz
When does EKF linearization require particular caution?
CodeUnscented transform
Implement unscented_transform(f,m,P,alpha,beta,kappa): f takes a vector and returns a vector. Use 2n+1 points with Cholesky columns and return (mean,covariance). Tests use n+λ>0 and positive-definite P.
import numpy as np
def unscented_transform(f,m,P,alpha,beta,kappa):
  return None,None
Shift+Enter to run
Key idea
EKF linearizes; UKF approximates moments using sigma points. Neither alone eliminates problems of angles, multimodality and consistency.

References