Filtering-based SLAM: EKF-SLAM, FastSLAM and data association
Estimate pose and map jointly using full and online SLAM, EKF-SLAM and Rao-Blackwellized FastSLAM. Study data association and why EKF-SLAM can become inconsistent.
After this lesson you can
- Formulate full and online SLAM as probabilistic inference and draw its graphical model.
- Implement EKF-SLAM with landmark initialization and explain its dense covariance.
- Implement nearest-neighbor association with chi-square validation and understand JCBB.
- Derive the FastSLAM factorization and implement it with resampling.
- Explain and detect EKF-SLAM overconfidence from linearization and observability.
Before you start
A map that is uncertain too
In an unfamiliar building, pose is used to place a landmark, but the landmark is needed to correct pose. The probabilistic formulation of SLAM retains both uncertainties and their correlations. Full SLAM estimates ; online SLAM marginalizes past poses and estimates . The former lets us revise a past trajectory when a place is recognized; the latter retains its effect summarized in the current distribution.
In the graphical model, each control links , each observation depends on the pose and observed landmark, and landmarks have independent priors. Conditioning on all poses and associations separates landmark branches. Without an external reference, jointly translating or rotating the entire trajectory and map preserves relative observations: the global frame has three gauge degrees of freedom in 2D. One can fix the initial pose or use an explicit prior. Comparing errors in global coordinates without handling that gauge mixes representation error with geometric error.
A fragment of the directed graph, with association of to and to fixed, is:
x₀ ──u₁──▶ x₁ ──u₂──▶ x₂
│ │
m₁ ───────▶ z₁ m₂ ─▶ z₂
Each parameterizes the transition factor. If association is unknown, it must be added as a variable or hypothesis; the conditional separation described below depends on fixing it.
An EKF for pose and map
In EKF-SLAM, and contains pose-pose, pose-map, and map-map blocks. Prediction changes only nominal pose, but its Jacobian also transforms correlations with the map. A landmark range-bearing observation directly touches only pose and that landmark; gain propagates correction to all correlated components. This explains why observing a known wall can adjust a distant one. It does not mean all ellipses must visibly shrink at each step.
A new landmark is initialized using inverse function : . Let and . Its covariance block is , and its cross-covariance with the existing state is . Copying only sensor noise as landmark covariance ignores pose uncertainty and creates false independence. Do not update again using the measurement used for initialization: that would count it twice.
To check dimensions, is , is and has one row per existing state component and three columns. The cross result has one row per old component and two columns. Its transpose is placed below to preserve symmetry. If initial orientation is uncertain, two landmarks initialized from that pose share an angular error component; adding the same number to their diagonal variances is insufficient. The code uses the full correlation map when adding each new observation.
The cost of storing a dense matrix grows quadratically with landmark count. Some formulations exploit the structure of for a quadratic update, while Joseph form written with generic dense products can be more expensive. In 2D, 2000 landmarks plus pose produce entries: 128 192 072 bytes in float64, about 122.25 MiB, for that matrix alone. Correlation is not a defect that can be set to zero without changing the distribution.
Association: a structural decision
Data association decides which observation corresponds to which landmark. Nearest-neighbor association computes innovation and distance , with , for each candidate. A chi-square gate rejects incompatible candidates: with two components and a correct Gaussian model, the 99% threshold is 9.210. Euclidean distance ignores the shape and scale of uncertainty. If no candidate passes, creating a landmark may duplicate an existing one; discarding or waiting for additional evidence are alternatives.
Independent selection can assign two observations to the same landmark or produce an incompatible combination. JCBB explores assignments using branch and bound, uses the joint innovation covariance, and seeks a compatible association under its criterion. Residuals share pose uncertainty and are not independent. The joint test has dimension equal to the sum of residual dimensions and its own chi-square threshold. JCBB does not guarantee truth: several assignments may be compatible, the model may be miscalibrated, or the correct hypothesis may be rejected by the gate.
For example, if pose error shifts two predictions right at once, two similar positive residuals may be compatible jointly even if each is relatively large. A pair with opposite-sign residuals may be less compatible with that same common error. The joint matrix has off-diagonal blocks and its inverse measures precisely that combination. Multiplying two individual tests or summing their distances under an independence assumption discards those blocks. The interactive example reduces each observation to one dimension so you can calculate joint distance by hand.
An incorrect association introduces a false constraint between pose and map. In a single EKF, the update mixes all variables and generally cannot be undone exactly without retaining the previous state and replaying observations. FastSLAM can retain different associations in different particles, provided their proposals and weights actually represent those hypotheses; if resampling eliminates the correct one, it cannot magically recover it either. Mutual exclusion, new-object detection, and perceptually ambiguous loop closures are modeling problems, not just threshold problems.
One trajectory and map per particle
With associations known or conditioned on, independent landmark priors, and measurements independent given trajectory and map, FastSLAM uses the factorization
Fixing the full trajectory makes observations of different landmarks depend on different parameters. Marginalizing the trajectory correlates them again; conditioning only on current pose is insufficient. Rao-Blackwellization means analytically integrating each conditional landmark and sampling the trajectory, rather than sampling every map point. Per-landmark EKFs remain local Gaussian approximations. With unknown association, each particle must maintain or choose its own associations, and the stated independence requires conditioning on them.
FastSLAM 1.0 proposes a pose from the motion model, weights by predictive observation probability, and updates landmark filters. Resampling concentrates resources where likelihood is high but duplicates histories; after a long loop only one old ancestor may remain even when current effective sample size is high. FastSLAM 2.0 also uses the measurement to propose pose and corrects weights for the proposal; it can reduce degeneracy with a precise sensor. The single-particle convergence result of Montemerlo and colleagues concerns a restricted linear Gaussian class, not arbitrary nonlinear SLAM with unknown association.
For a landmark already initialized in a particle, measurement prediction uses the sampled pose and the landmark’s local EKF. With innovation , covariance and dimension , its Gaussian factor is proportional to . Sum logarithms to combine factors without underflow and normalize after subtracting the maximum. Pose uncertainty does not appear inside that local : particle spread represents it. Also adding a global pose covariance to every without deriving the model would count uncertainty twice.
A high effective sample size only says current weights are similar. If all particles descend from one long-ago ancestor, they do not represent eliminated historical alternatives. Retaining each particle’s trajectory helps diagnose this depletion, but copying it in full at each step consumes memory. Large systems use shared structures or windows and separately monitor ancestor count, current spread, and error when ground truth is available.
With suitable persistent structures, work per observation can grow logarithmically with landmarks per particle; a naive implementation copying every map on resampling does not have that cost. The following figure retains trajectories and maps for 100 particles; six are shown. Associations are known to isolate the effect of resampling.
Inconsistency and observability
SLAM inconsistency occurs when actual error is too large for the declared uncertainty. EKF-SLAM repeatedly linearizes at changing estimates: linearizations can assign spurious information to directions unobserved by the relative problem, especially with accumulated angular uncertainty. An incorrectly associated loop closure worsens the problem, but even correct associations can show inconsistency. Bailey and colleagues analyze the effect; observability-preserving formulations and optimization with relinearization are alternatives, not automatic guarantees.
To quantify it, use with wrapped angular difference and . With 100 independent replicates and three-dimensional pose, the ideal NEES sum follows ; the central pointwise 95% band for the mean is [2.539, 3.499]. Instants from one trajectory are correlated: the fraction outside the band is descriptive, not a test with independent temporal samples. Frame, priors, and association must match when comparing error and covariance.
Lab: two filters, the same observations
The functions build the EKF with correlated initialization, a range-bearing model, Joseph form, and an individual gate. The sensor generates four landmarks without occlusion; unknown=True uses nearest neighbor and can duplicate landmarks, while the later comparison uses known identities. The first state is anchored near zero. represents distance and rotation noise transformed into the global frame by the control Jacobian.
import numpy as np
from scipy.stats import chi2
def wrap(a): return (a+np.pi)%(2*np.pi)-np.pi
def predict(mu,P,u,Q):
s,a=u; theta=mu[2]; n=len(mu); F=np.eye(n)
F[0,2]=-s*np.sin(theta);F[1,2]=s*np.cos(theta)
G=np.zeros((n,2));G[0,0]=np.cos(theta);G[1,0]=np.sin(theta);G[2,1]=1
mu=mu.copy();mu[:3]+=[s*np.cos(theta),s*np.sin(theta),a];mu[2]=wrap(mu[2])
P=F@[email protected]+G@[email protected]
return mu,(P+P.T)/2
def model(mu,index):
i=3+2*index; dx,dy=mu[i:i+2]-mu[:2];q=dx*dx+dy*dy; r=np.sqrt(q)
if r<1e-8: raise ValueError('landmark coincide con la pose')
z=np.array([r,wrap(np.arctan2(dy,dx)-mu[2])]);H=np.zeros((2,len(mu)))
H[:,:3]=[[-dx/r,-dy/r,0],[dy/q,-dx/q,-1]]
H[:,i:i+2]=[[dx/r,dy/r],[-dy/q,dx/q]]
return z,H
def initialize(mu,P,z,R):
r,b=z; a=mu[2]+b;c=np.cos(a);s=np.sin(a)
landmark=mu[:2]+r*np.array([c,s]);Jx=np.array([[1,0,-r*s],[0,1,r*c]])
Jz=np.array([[c,-r*s],[s,r*c]])
cross=P[:,:3]@Jx.T; sub=Jx@P[:3,:3]@Jx.T+Jz@[email protected]
return np.r_[mu,landmark],np.block([[P,cross],[cross.T,sub]])
def update(mu,P,z,index,R):
zh,H=model(mu,index);nu=z-zh;nu[1]=wrap(nu[1]);S=H@[email protected]+R
K=np.linalg.solve(S,H@P).T;mu=mu+K@nu;mu[2]=wrap(mu[2])
A=np.eye(len(mu))-K@H;P=A@[email protected]+K@[email protected]
return mu,(P+P.T)/2
def associate(mu,P,z,R,gate=5.991):
best=None
for i in range((len(mu)-3)//2):
zh,H=model(mu,i);nu=z-zh;nu[1]=wrap(nu[1]);S=H@[email protected]+R
[email protected](S,nu)
if d2<gate and (best is None or d2<best[0]):best=(d2,i)
return None if best is None else best[1]
def sense(pose,landmark):
d=landmark-pose[:2];return np.array([np.hypot(*d),wrap(np.arctan2(d[1],d[0])-pose[2])])
def experiment(seed=0,angular=.03,steps=70,unknown=False,save=False):
rng=np.random.default_rng(seed);true=np.zeros(3);mu=np.zeros(3);P=np.eye(3)*1e-9
landmarks=np.array([[1.5,1.8],[3.,1.2],[3.,3.8],[.5,3.4]])
Q=np.diag([.025**2,angular**2]);R=np.diag([.12**2,.06**2]);seen={}; history=[]
for t in range(steps):
u=np.array([.085,.055]);actual=u+rng.multivariate_normal(np.zeros(2),Q)
true[:2]+=actual[0]*np.array([np.cos(true[2]),np.sin(true[2])]);true[2]=wrap(true[2]+actual[1])
mu,P=predict(mu,P,u,Q)
for j,landmark in enumerate(landmarks):
z=sense(true,landmark)+rng.multivariate_normal(np.zeros(2),R);z[1]=wrap(z[1])
if unknown:
index=associate(mu,P,z,R)
if index is None:mu,P=initialize(mu,P,z,R)
else:mu,P=update(mu,P,z,index,R)
elif j not in seen:
seen[j]=(len(mu)-3)//2;mu,P=initialize(mu,P,z,R)
else:mu,P=update(mu,P,z,seen[j],R)
e=mu[:3]-true;e[2]=wrap(e[2]);[email protected](P[:3,:3],e)
history.append((true.copy(),mu.copy(),P.copy(),float(nees)))
return history
h=experiment(5,steps=50,unknown=True)
print('Landmarks creados con asociación desconocida:',(len(h[-1][1])-3)//2,'frente a 4 reales')In the following filter each particle retains a trajectory and an independent EKF per landmark. The first measurement initializes each landmark without a weight factor, equivalent to a common diffuse-prior convention for this example; it is not a probability comparison between creating and associating objects. Both filters use known identities, the same world and data, with 100 particles. Measured times depend on machine, particle count, and implementation and illustrate only these dense-array versions.
import numpy as np
import time
def wrap(a): return (a+np.pi)%(2*np.pi)-np.pi
def generate(seed=9,T=70,count=4):
rng=np.random.default_rng(seed); points=np.array([[1.5,1.8],[3.,1.2],[3.,3.8],[.5,3.4]])
if count>4:
angles=np.linspace(0,2*np.pi,count-4,endpoint=False)
points=np.vstack((points,np.column_stack((2.5+2*np.cos(angles),2.5+2*np.sin(angles)))))
Q=np.diag([.025**2,.05**2]);R=np.diag([.12**2,.06**2]);truth=np.zeros(3);out=[]
for _ in range(T):
u=np.array([.085,.055]);actual=u+rng.multivariate_normal(np.zeros(2),Q)
truth[:2]+=actual[0]*np.array([np.cos(truth[2]),np.sin(truth[2])]);truth[2]=wrap(truth[2]+actual[1])
d=points-truth[:2];z=np.column_stack((np.hypot(d[:,0],d[:,1]),wrap(np.arctan2(d[:,1],d[:,0])-truth[2])))
z+=rng.normal(0,[.12,.06],z.shape);z[:,1]=wrap(z[:,1]);out.append((truth.copy(),u,z))
return out,Q,R
def fastslam(data,Q,R,M=100,seed=123):
rng=np.random.default_rng(seed);count=len(data[0][2]);pose=np.zeros((M,3));land=np.zeros((M,count,2));cov=np.zeros((M,count,2,2))
weights=np.full(M,1/M);ancestors=np.arange(M);history=[];paths=np.zeros((M,len(data),3))
for t,(truth,u,zs) in enumerate(data):
noise=rng.multivariate_normal(np.zeros(2),Q,M);ds=u[0]+noise[:,0];da=u[1]+noise[:,1]
pose[:,0]+=ds*np.cos(pose[:,2]);pose[:,1]+=ds*np.sin(pose[:,2]);pose[:,2]=wrap(pose[:,2]+da)
paths[:,t]=pose
logw=np.log(weights+1e-300)
for j,z in enumerate(zs):
r,b=z;a=pose[:,2]+b;c=np.cos(a);s=np.sin(a)
if t==0:
land[:,j,0]=pose[:,0]+r*c;land[:,j,1]=pose[:,1]+r*s
J=np.zeros((M,2,2));J[:,0,0]=c;J[:,0,1]=-r*s;J[:,1,0]=s;J[:,1,1]=r*c
cov[:,j]=J@[email protected](0,2,1)
else:
dx=land[:,j,0]-pose[:,0];dy=land[:,j,1]-pose[:,1];q=dx*dx+dy*dy;d=np.sqrt(q)
h=np.column_stack((d,wrap(np.arctan2(dy,dx)-pose[:,2])));nu=z-h;nu[:,1]=wrap(nu[:,1])
H=np.empty((M,2,2));H[:,0,0]=dx/d;H[:,0,1]=dy/d;H[:,1,0]=-dy/q;H[:,1,1]=dx/q
S=H@cov[:,j]@H.transpose(0,2,1)+R
logw+=-.5*((nu[:,None,:]@np.linalg.solve(S,nu[:,:,None]))[:,0,0]+np.linalg.slogdet(S)[1]+2*np.log(2*np.pi))
K=np.linalg.solve(S,H@cov[:,j]).transpose(0,2,1);land[:,j]+=(K@nu[:,:,None])[:,:,0]
A=np.eye(2)-K@H;cov[:,j]=A@cov[:,j]@A.transpose(0,2,1)+K@[email protected](0,2,1)
weights=np.exp(logw-logw.max());weights/=weights.sum()
estimate=np.sum(weights[:,None]*pose[:,:2],axis=0);err=np.linalg.norm(estimate-truth[:2]);ess=1/np.sum(weights**2)
history.append((truth.copy(),pose.copy(),land.copy(),weights.copy(),float(err),float(ess),len(np.unique(ancestors)),paths[:,:t+1].copy()))
if ess<M/2:
cdf=np.cumsum(weights);cdf[-1]=1;u0=(rng.random()+np.arange(M))/M
index=np.searchsorted(cdf,u0,side='right');pose=pose[index].copy();land=land[index].copy();cov=cov[index].copy();ancestors=ancestors[index];paths=paths[index].copy();weights.fill(1/M)
return history
def ekf(data,Q,R):
# Import the EKF from the preceding lab cell when run in the lesson.
mu=np.zeros(3);P=np.eye(3)*1e-9;errs=[];ne=[]
for t,(truth,u,zs) in enumerate(data):
mu,P=predict(mu,P,u,Q)
for j,z in enumerate(zs):
if t==0:mu,P=initialize(mu,P,z,R)
else:mu,P=update(mu,P,z,j,R)
e=mu[:3]-truth;e[2]=wrap(e[2]);errs.append(np.linalg.norm(e[:2]));ne.append([email protected](P[:3,:3],e))
return np.array(errs),np.array(ne)
data,Q,R=generate(); e,nees=ekf(data,Q,R); h=fastslam(data,Q,R)
print('EKF RMS/final/NEES:',round(float(np.sqrt(np.mean(e**2))),3),round(e[-1],3),round(nees[-1],2))
print('FastSLAM RMS/final/antepasados:',round(float(np.sqrt(np.mean([a[4]**2 for a in h]))),3),round(h[-1][4],3),h[-1][6])
for count in (4,8,16):
data,Q,R=generate(T=30,count=count)
start=time.perf_counter();ekf(data,Q,R);a=time.perf_counter()-start
start=time.perf_counter();fastslam(data,Q,R);b=time.perf_counter()-start
print('landmarks',count,'tiempos:',round(a,4),round(b,4))In one native run with seed 9 and 70 steps, position RMS error was 0.205 m for EKF and 0.260 m for FastSLAM; final errors were 0.339 and 0.378 m. Final EKF NEES was 11.38, and one of 100 initial ancestors survived. In 30 steps, with 4, 8 and 16 landmarks, approximately 0.006, 0.012 and 0.043 s were measured for EKF and 0.073, 0.106 and 0.257 s for FastSLAM in this implementation and run; these are not a universal complexity comparison. Changing the seed or running in a browser changes times and results.
Lab: 100 independent worlds
To isolate linearization, correct identities are provided and 100 independent 70-step simulations are repeated with three angular-noise standard deviations. The vectorized run retains a state matrix per world and measures pose NEES in the fixed frame. The chi-square band is an ideal reference, not a promise for a nonlinear EKF initialized from a measurement. Do not generalize to every map and configuration.
import numpy as np
from scipy.stats import chi2
def wrap(a): return (a+np.pi)%(2*np.pi)-np.pi
def monte_carlo(angular,seed=21,M=100,T=70):
rng=np.random.default_rng(seed); landmarks=np.array([[1.5,1.8],[3.,1.2],[3.,3.8],[.5,3.4]])
D=11;truth=np.zeros((M,3));mean=np.zeros((M,D));P=np.zeros((M,D,D));P[:,:3,:3]=np.eye(3)*1e-9
Q=np.diag([.025**2,angular**2]);R=np.diag([.12**2,.06**2]); I=np.eye(D); stats=[]
for t in range(T):
s=.085+rng.normal(0,.025,M); da=.055+rng.normal(0,angular,M)
truth[:,0]+=s*np.cos(truth[:,2]);truth[:,1]+=s*np.sin(truth[:,2]);truth[:,2]=wrap(truth[:,2]+da)
theta=mean[:,2].copy();mean[:,0]+=.085*np.cos(theta);mean[:,1]+=.085*np.sin(theta);mean[:,2]=wrap(theta+.055)
F=np.broadcast_to(I,(M,D,D)).copy();F[:,0,2]=-.085*np.sin(theta);F[:,1,2]=.085*np.cos(theta)
G=np.zeros((M,D,2));G[:,0,0]=np.cos(theta);G[:,1,0]=np.sin(theta);G[:,2,1]=1
P=F@[email protected](0,2,1)+G@[email protected](0,2,1)
for j,point in enumerate(landmarks):
delta=point-truth[:,:2];z=np.column_stack((np.hypot(delta[:,0],delta[:,1]),wrap(np.arctan2(delta[:,1],delta[:,0])-truth[:,2])))
z+=rng.normal(0,[.12,.06],(M,2));z[:,1]=wrap(z[:,1]);ix=3+2*j
if t==0:
a=mean[:,2]+z[:,1];c=np.cos(a);s=np.sin(a);r=z[:,0]
mean[:,ix]=mean[:,0]+r*c;mean[:,ix+1]=mean[:,1]+r*s
J=np.zeros((M,2,3));J[:,0,0]=1;J[:,1,1]=1;J[:,0,2]=-r*s;J[:,1,2]=r*c
V=np.zeros((M,2,2));V[:,0,0]=c;V[:,0,1]=-r*s;V[:,1,0]=s;V[:,1,1]=r*c
cross=P[:,:,:3]@J.transpose(0,2,1);sub=J@P[:,:3,:3]@J.transpose(0,2,1)+V@[email protected](0,2,1)
P[:,:,ix:ix+2]=cross;P[:,ix:ix+2,:]=cross.transpose(0,2,1);P[:,ix:ix+2,ix:ix+2]=sub
else:
dx=mean[:,ix]-mean[:,0];dy=mean[:,ix+1]-mean[:,1];q=dx*dx+dy*dy;r=np.sqrt(q)
h=np.column_stack((r,wrap(np.arctan2(dy,dx)-mean[:,2])));nu=z-h;nu[:,1]=wrap(nu[:,1])
H=np.zeros((M,2,D));H[:,0,0]=-dx/r;H[:,0,1]=-dy/r;H[:,1,0]=dy/q;H[:,1,1]=-dx/q;H[:,1,2]=-1
H[:,0,ix]=dx/r;H[:,0,ix+1]=dy/r;H[:,1,ix]=-dy/q;H[:,1,ix+1]=dx/q
S=H@[email protected](0,2,1)+R;K=np.linalg.solve(S,H@P).transpose(0,2,1)
mean+=(K@nu[:,:,None])[:,:,0];mean[:,2]=wrap(mean[:,2]);A=I-K@H
P=A@[email protected](0,2,1)+K@[email protected](0,2,1)
e=mean[:,:3]-truth;e[:,2]=wrap(e[:,2]);nees=(e[:,None,:]@np.linalg.solve(P[:,:3,:3],e[:,:,None]))[:,0,0]
stats.append(float(nees.mean()))
return np.array(stats)a01=monte_carlo(.01);a=a01
band=chi2.ppf([.025,.975],300)/100
print('ruido .01, banda:',np.round(band,3),'NEES final:',round(a[-1],3),'máximo:',round(a.max(),3),'fracción sobre banda:',round(float(np.mean(a>band[1])),3))a05=monte_carlo(.05);a=a05
band=chi2.ppf([.025,.975],300)/100
print('ruido .05, banda:',np.round(band,3),'NEES final:',round(a[-1],3),'máximo:',round(a.max(),3),'fracción sobre banda:',round(float(np.mean(a>band[1])),3))a10=monte_carlo(.10);a=a10
band=chi2.ppf([.025,.975],300)/100
print('ruido .10, banda:',np.round(band,3),'NEES final:',round(a[-1],3),'máximo:',round(a.max(),3),'fracción sobre banda:',round(float(np.mean(a>band[1])),3))import matplotlib.pyplot as plt
fig,ax=plt.subplots(figsize=(7,3.5))
for values,label in [(a01,'0.01 rad'),(a05,'0.05 rad'),(a10,'0.10 rad')]:
ax.plot(np.arange(1,len(values)+1),values,label=label)
ax.axhspan(band[0],band[1],alpha=.2,color='gray',label='banda puntual 95 %')
ax.set(xlabel='Paso',ylabel='NEES medio',title='100 simulaciones por configuración')
ax.legend();fig.tight_layout();plt.show()With seed 21, the band is [2.539, 3.499]. Final mean NEES values for angular noise 0.01, 0.05 and 0.10 rad per step were 5.039, 3.380 and 5.557; fractions of instants above the band were 0.557, 0.200 and 0.686. They do not grow monotonically with noise in this sample. There is overconfidence at several instants, but the plot and final position are insufficient to infer a general failure rate.
Exercises
Step 1 of 3. Which variables remain shared between observations of different landmarks?
import numpy as np
def ekf_slam_update(mu, Sigma, z, landmark_id):
passSources: Montemerlo and colleagues, FastSLAM, FastSLAM 2.0, Neira and Tardós, joint compatibility, Bailey and colleagues, EKF-SLAM consistency and Durrant-Whyte and Bailey, Simultaneous Localization and Mapping: Part I.