Localization and occupancy grid mapping
Study localization with a known map and mapping with known poses. Implement EKF and Monte Carlo localization, kidnapped-robot recovery, occupancy grids with log-odds updates, and a LiDAR likelihood field.
After this lesson you can
- Implement EKF localization with known landmarks and Mahalanobis-distance association.
- Implement Monte Carlo localization with a likelihood field and low-variance resampling.
- Address the kidnapped-robot problem by injecting random particles according to mean likelihood.
- Build an occupancy grid using log-odds updates and an inverse sensor model.
- Choose between Gaussian and particle localization based on environmental ambiguity.
Before you start
Two problems, two assumptions
A warehouse vehicle has a map and wants to know its pose. An explorer knows its trajectory, for example from an external system, and wants to map its surroundings. The first problem estimates ; the second estimates the map given poses and observations. If pose and map are both uncertain and correlated, the problem becomes SLAM: treating estimated pose as truth can draw double walls and make the filter overconfident.
Localization with landmarks
EKF localization represents pose by a mean and covariance. Prediction applies the motion model and propagates . For a known landmark and range and bearing measurement, with and . Its Jacobian, for and , is
If identity is unknown, for each candidate form , wrap the angle and compute and . Choose the smallest that passes a gate, for example the quantile under Gaussian assumptions. If none pass, reject or start a new hypothesis. The gate reduces unlikely associations but does not guarantee identity: several landmarks can be compatible and a wrong covariance can reject the correct association. For the selected one, , , and Joseph form updates ; wrap the angle after correction.
Mahalanobis distance measures the residual on the scale and along the directions of its uncertainty, not a physical distance in meters. A one-meter difference may be surprising with a precise prediction and acceptable with a broad covariance. For a two-component measurement under the correct model, the 95% gate rejects approximately 5% of correct associations: it is a tradeoff, not proof of identity. With simultaneous observations, choosing nearest neighbors separately can assign the same landmark twice; joint association imposes compatibility among assignments and their correlations.
Prediction depends on the control and its covariance. For displacement and rotation , the approximation , , has and . Angular uncertainty thus becomes lateral error. For a large turn, integrate the arc rather than assuming constant heading. Wrapping angular differences is also essential: and are two degrees apart, not 358. Local linearization loses accuracy when orientation uncertainty or ambiguity is large.
import numpy as np
def wrap(a): return (a+np.pi)%(2*np.pi)-np.pi
def predict(mean,P,distance,turn,Q):
theta=mean[2]; out=mean.copy()
out+=np.array([distance*np.cos(theta),distance*np.sin(theta),turn])
out[2]=wrap(out[2])
F=np.eye(3); F[0,2]=-distance*np.sin(theta);F[1,2]=distance*np.cos(theta)
return out,F@[email protected]+Q
def associate_update(mean,P,z,landmarks,R,gate=5.991):
choices=[]
for landmark in landmarks:
dx,dy=landmark-mean[:2]; r=np.hypot(dx,dy)
if r<1e-8: continue
h=np.array([r,wrap(np.arctan2(dy,dx)-mean[2])])
H=np.array([[-dx/r,-dy/r,0],[dy/r**2,-dx/r**2,-1]])
innovation=z-h; innovation[1]=wrap(innovation[1])
S=H@[email protected]+R; [email protected](S,innovation)
choices.append((d2,H,innovation,S))
if not choices: return mean,P,None
d2,H,innovation,S=min(choices,key=lambda item:item[0])
if d2>gate: return mean,P,None
K=np.linalg.solve(S,H@P).T; new=mean+K@innovation; new[2]=wrap(new[2])
A=np.eye(3)-K@H; cov=A@[email protected]+K@[email protected]
return new,cov,float(d2)
pred,P=predict(np.array([-.1,0.,0.]),np.eye(3)*.1,.1,0.,np.eye(3)*.001)
mean,P,d2=associate_update(pred,P,
np.array([2.1,.05]),np.array([[2.,0.],[0.,3.]]),np.diag([.1,.05])**2)
print('pose:',np.round(mean,3),'Mahalanobis²:',round(d2,3))A single Gaussian does not describe two distant, equally probable locations. A premature association can move the EKF to the wrong branch and reduce its covariance; the gate may then prevent acceptance of the correct observation. Maintaining multiple hypotheses is a representation choice, not a guarantee that a particle filter always succeeds.
Particles and likelihood field
Monte Carlo localization approximates the belief with poses and weights. It propagates each pose with noisy odometry, computes the product of beam likelihoods, normalizes, and resamples when effective sample size falls below a threshold. Low-variance systematic selection uses one random position in and then equally spaced positions. Its copies are not independent; particle order can affect its variance. Frequent resampling can unnecessarily remove diversity; with exactly uniform weights, systematic resampling retains one copy of each particle.
A beam model predicts the ray’s exact first intersection and compares its distance with the reading. The intercepted object can change abruptly as pose varies, especially near corners and occlusions. The likelihood field precomputes the distance to the nearest obstacle for each map point and scores the observed endpoint using . It is fast and locally smooth, but loses information about what was traversed and may score an endpoint behind a wall highly. Beams are not usually independent in reality; multiplying many as if they were can overconcentrate weights. A grid distance transform computes the field once per map.
In the bootstrap filter, after propagation from the motion model. If a different proposal uses the measurement to decide where to generate particles, it generally must include the ratio between target and proposal distributions. The lab omits that correction in its injections and is therefore a recovery heuristic, not an exact implementation of the original posterior. To prevent a product of many probabilities rounding to zero, sum logarithms, subtract their maximum, and exponentiate before normalizing.
Effective sample size summarizes weight inequality; it does not measure how many distinct locations remain represented. After resampling, every copy can have equal weight and even if almost all descend from one ancestor. Reasonable motion noise and informative measurements preserve exploration; excessive artificial noise instead disperses the filter and degrades accuracy. Weights also depend on sensor failures: missing rays, specular reflection, moving objects, and maximum-range readings require explicit models or filtering.
With global initialization, particles must cover free space and orientation. For the kidnapped robot, augmented MCL compares slow and fast likelihood averages and proposes a fraction of new poses when likelihood falls. The rule depends on scale, averages, and sensors: it does not guarantee recovery. Fox’s KLD-sampling adapts sample count to occupied distribution bins and a chosen error/tolerance; it requires minimum and maximum limits and suitable discretization. Too few samples may miss the true hypothesis even if their apparent spread is small.
The KLD approximation for occupied bins requires approximately
where is divergence tolerance, confidence and the normal quantile. Lower tolerance requires more samples. The count changes as samples are generated, so the limit is updated during resampling; a minimum is set when . The formula describes discretized approximation error under its assumptions, not position error against truth or the probability of discovering a region that never received samples.
Mapping beam by beam
An occupancy map approximates each cell with a binary variable. Given known poses and an inverse model, cells before a hit receive free-space evidence; the hit cell receives occupied evidence. A ray with no hit up to its maximum range does not turn its endpoint into an obstacle. This representation usually updates cells separately, although a first-hit observation correlates them. The inverse model and beam angles must respect sensor resolution, width, and limits.
With , the log-odds update is
It follows by multiplying prior odds by the likelihood ratio; the inverse model already incorporates the prior, so its log-odds are subtracted. Recover probability using . Clipping to a finite interval lets new evidence reverse an old belief and avoids overflow, although it also loses information. Ray tracing must update each traversed cell once per beam, not once per distance sample.
For example, with prior 0.5, inverse model 0.3 for free and 0.7 for occupied, a beam adds approximately to each free cell and to the hit cell. Three independent hits in a cell produce odds and probability 0.927. But three identical, highly correlated measurements are not three independent pieces of information; adding them without correction can make the map overconfident. A fine grid represents details better but increases cost and causes pose noise to spread a wall across cells.
An unobserved cell retains the prior and must not be confused with free space. A static map can also become outdated: log-odds clipping makes evidence easier to reverse, but does not explicitly model object motion. For planning, choose a conservative treatment of unknown cells and inflate obstacles according to the robot footprint and pose uncertainty. If mapping poses contain drift, every beam is displaced or rotated, and the resulting grid inherits that uncertainty even when the per-cell formulas are correct.
Lab: MCL from scratch
The map and sensor below are synthetic. Two generators separate world and filter noise. The field comes from the distance transform; a geometric mean of 16 beams raised to the fourth power gives a tempered likelihood that reduces concentration relative to the full product. For recovery, uniform candidates are generated and selected using the measurement: this informed proposal has no importance correction and is not an exact posterior. The best particle is used as the estimate because the mean can fall between modes. Try seeds, particle counts, and thresholds; compare errors before and after the jump without mistaking one successful run for a guarantee.
import numpy as np
from scipy.ndimage import distance_transform_edt
RES=0.2; H,W=20,25
grid=np.zeros((H,W),bool)
grid[[0,-1],:]=True;grid[:,[0,-1]]=True
grid[3:16,12]=True;grid[8:11,12]=False
grid[3:6,18:21]=True;grid[14:17,4:7]=True
distance=distance_transform_edt(~grid)*RES
beams=np.linspace(-np.pi,np.pi,16,endpoint=False)
def wrap(a): return (a+np.pi)%(2*np.pi)-np.pi
def isfree(p):
x=np.floor(p[:,0]/RES).astype(int);y=np.floor(p[:,1]/RES).astype(int)
ok=(x>=0)&(x<W)&(y>=0)&(y<H)
out=np.zeros(len(p),bool);out[ok]=~grid[y[ok],x[ok]]
return out
def random_poses(rng,n):
free=np.argwhere(~grid);ix=rng.integers(0,len(free),n);cells=free[ix]
return np.column_stack(((cells[:,1]+rng.random(n))*RES,(cells[:,0]+rng.random(n))*RES,rng.uniform(-np.pi,np.pi,n)))
def scan(pose):
ds=np.arange(0.05,5.01,0.05);out=[]
for a in beams+pose[2]:
points=pose[:2]+ds[:,None]*np.array([np.cos(a),np.sin(a)])
blocked=np.flatnonzero(~isfree(points))
out.append(ds[blocked[0]] if len(blocked) else 5.)
return np.array(out)
def likelihood(particles,z):
angles=particles[:,2,None]+beams
xx=particles[:,0,None]+z[None,:]*np.cos(angles)
yy=particles[:,1,None]+z[None,:]*np.sin(angles)
ix=np.clip(np.floor(xx/RES).astype(int),0,W-1);iy=np.clip(np.floor(yy/RES).astype(int),0,H-1)
d=distance[iy,ix]
# Geometric mean keeps the likelihood scale stable as beam count changes.
return np.exp(np.mean(np.log(0.99*np.exp(-0.5*(d/0.15)**2)+0.01),axis=1))
def systematic(particles,weights,rng):
n=len(particles); w=np.asarray(weights,float);w=w/w.sum()
edges=np.cumsum(w);edges[-1]=1
positions=(rng.random()+np.arange(n))/n
return particles[np.searchsorted(edges,positions,side='right')].copy()
def move(poses,dist,turn):
out=poses.copy(); out[:,0]+=dist*np.cos(poses[:,2]);out[:,1]+=dist*np.sin(poses[:,2]);out[:,2]=wrap(poses[:,2]+turn)
return out
def simulate(seed=4,inject=True,n=600,steps=100,initial='global'):
rng=np.random.default_rng(seed); world_rng=np.random.default_rng(seed+1000)
pose=np.array([1.0,1.0,0.])
particles=random_poses(rng,n) if initial=='global' else pose+rng.normal(0,[0.12,0.12,0.08],(n,3))
weights=np.full(n,1/n); slow=fast=None; trace=[]; snapshots=[]
for k in range(steps):
if k==45: pose=np.array([3.6,2.8,-np.pi/2])
turn=0.045 if k%35>24 else 0.; u=0.045
proposal=move(pose[None,:],u,turn)[0]
if isfree(proposal[None,:])[0]:pose=proposal; actual_dist,actual_turn=u,turn
else: pose[2]=wrap(pose[2]+0.12);actual_dist,actual_turn=0.,0.12
# Odometría: se entrega movimiento en el marco local con ruido independiente.
uobs=actual_dist+world_rng.normal(0,0.008); turnobs=actual_turn+world_rng.normal(0,0.006)
particles=move(particles,uobs+rng.normal(0,0.025,n),turnobs+rng.normal(0,0.025,n))
z=np.clip(scan(pose)+world_rng.normal(0,0.025,len(beams)),0,5)
likelihoods=likelihood(particles,z);likelihoods[~isfree(particles)]=1e-10
avg=float(likelihoods.mean())
if slow is None:slow=fast=avg
slow+=0.0001*(avg-slow);fast+=0.4*(avg-fast)
lw=np.log(np.maximum(weights,1e-300))+4*np.log(np.maximum(likelihoods,1e-300))
weights=np.exp(lw-lw.max());weights/=weights.sum()
ess=1/np.sum(weights**2)
# La media no es una estimación fiable si la posterior es multimodal.
best=particles[np.argmax(weights)]
error=float(np.linalg.norm(best[:2]-pose[:2]))
trace.append((k,error,ess,max(0.,1-fast/slow) if inject else 0.))
snapshots.append((pose.copy(),particles.copy(),weights.copy()))
if ess<n/2 or (inject and 1-fast/slow>0.02):
particles=systematic(particles,weights,rng);weights.fill(1/n)
amount=rng.binomial(n,max(0.,1-fast/slow)) if inject else 0
if amount:
candidates=random_poses(rng,amount*25)
scores=likelihood(candidates,z)**8
scores/=scores.sum()
particles[:amount]=candidates[rng.choice(len(candidates),amount,p=scores)]
return np.array(trace),snapshots
trace,_=simulate(0,True,n=300,steps=80)
print('error antes y final (m):',np.round(trace[[44,-1],1],3),'inyección máxima:',round(trace[:,3].max(),3))With 600 particles and local initialization, final errors after 200 steps were 0.02, 3.26, 0.02 and 3.66 m for seeds 0 through 3 with guided recovery; for the same seeds without injection they were 4.39, 3.51, 4.01 and 4.42 m. The heuristic still fails in two cases. The result depends on this map, trajectory, and parameters and does not establish general rates.
The following ray tracer samples positions along the ray, forms a list of cells, and avoids updating them repeatedly. The hit is handled separately; if the beam reaches maximum range, no occupied evidence is added. Its endpoint must lie inside the grid. Sampling can miss a cell traversed only near a corner; for exact geometric coverage use a grid traversal algorithm. Here the sensor is ideal and pose is known.
import numpy as np
def ray_cells(origin, angle, distance, resolution, shape):
# Muestrea por debajo del tamaño de celda y conserva el orden de paso.
end=np.floor((np.asarray(origin)+distance*np.array([np.cos(angle),np.sin(angle)]))/resolution).astype(int)
if not (0<=end[0]<shape[1] and 0<=end[1]<shape[0]): raise ValueError('extremo fuera de la rejilla')
d=np.r_[np.arange(0,distance,resolution/3),distance]
xy=np.asarray(origin)+d[:,None]*[np.cos(angle),np.sin(angle)]
ij=np.floor(xy/resolution).astype(int)
return list(dict.fromkeys((int(y),int(x)) for x,y in ij
if 0<=y<shape[0] and 0<=x<shape[1]))
def update_ray(logodds, cells, hit, p_free=.3, p_occ=.7, cap=3.):
cells=list(dict.fromkeys(tuple(c) for c in cells))
free=cells[:-1] if hit else cells
for y,x in free: logodds[y,x]+=np.log(p_free/(1-p_free))
if hit and cells:
y,x=cells[-1];logodds[y,x]+=np.log(p_occ/(1-p_occ))
np.clip(logodds,-cap,cap,out=logodds)
return logodds
grid=np.zeros((4,12))
cells=ray_cells((.25,.25),0.,1.25,.25,grid.shape)
for _ in range(3): update_ray(grid,cells,True)
print('celdas atravesadas:',cells)
print('libre e impacto:',np.round(1/(1+np.exp(-grid[1,[2,6]])),3))Local lab: MuJoCo rays
A static box scene is built, the robot body is moved kinematically to known poses to build a map, and rays are emitted using mj_ray. Then, on a different trajectory, MCL receives only odometry and noisy rays; true pose generates measurements and evaluates error. Mapping poses were chosen outside obstacles with knowledge of the scene, and the robot moves through imposed coordinates, not wheel dynamics. Localization initializes near the correct pose, not globally. In this run with seed 7: 1699 free cells, 239 occupied, RMSE 0.0235 m, and final error 0.0039 m. These are not physical robot results or a statistical trial.
import numpy as np
import mujoco
from scipy.ndimage import distance_transform_edt
xml='''<mujoco><worldbody>
<geom name="floor" type="plane" size="5 5 .1" group="1"/>
<geom type="box" pos="2.5 0 .5" size="2.5 .05 .5"/>
<geom type="box" pos="2.5 4 .5" size="2.5 .05 .5"/>
<geom type="box" pos="0 2 .5" size=".05 2 .5"/>
<geom type="box" pos="5 2 .5" size=".05 2 .5"/>
<geom type="box" pos="2.5 2 .5" size=".15 .6 .5"/>
<geom type="box" pos=".9 2.7 .5" size=".3 .3 .5"/>
<geom type="box" pos="4 .9 .5" size=".3 .3 .5"/>
<body name="robot" pos="0 0 .2"><joint name="x" type="slide" axis="1 0 0"/>
<joint name="y" type="slide" axis="0 1 0"/><joint name="yaw" type="hinge" axis="0 0 1"/>
<geom type="sphere" size=".1" mass="1" group="2"/></body>
</worldbody></mujoco>'''
m=mujoco.MjModel.from_xml_string(xml); d=mujoco.MjData(m)
robot=mujoco.mj_name2id(m,mujoco.mjtObj.mjOBJ_BODY,'robot')
group=np.array([1,0,0,0,0,0],np.uint8); gid=np.zeros(1,np.int32)
angles=np.linspace(-np.pi,np.pi,32,endpoint=False); resolution=.1; h,w=40,50
def scan(pose):
d.qpos[:3]=pose; mujoco.mj_forward(m,d); result=[]
origin=np.array([pose[0],pose[1],.2])
for a in angles+pose[2]:
v=np.array([np.cos(a),np.sin(a),0.]); dist=mujoco.mj_ray(m,d,origin,v,group,1,robot,gid)
result.append(min(dist,5.) if dist>=0 else 5.)
return np.array(result)
def trace(grid,pose,z):
for a,r in zip(angles+pose[2],z):
# Sample each traversed cell once; an endpoint at max range is not a hit.
ds=np.arange(0,r,resolution/3); xy=pose[:2]+ds[:,None]*[np.cos(a),np.sin(a)]
ij=np.floor(xy/resolution).astype(int); ij=np.unique(ij,axis=0)
ij=ij[(ij[:,0]>=0)&(ij[:,0]<w)&(ij[:,1]>=0)&(ij[:,1]<h)]
end=np.floor((pose[:2]+r*np.array([np.cos(a),np.sin(a)]))/resolution).astype(int)
# Ignore the endpoint while applying free evidence.
ij=ij[np.any(ij!=end,axis=1)]; grid[ij[:,1],ij[:,0]]-=.4
if r<5 and 0<=end[0]<w and 0<=end[1]<h: grid[end[1],end[0]]+=.85
np.clip(grid,-3,3,out=grid)
grid=np.zeros((h,w))
# Mapping poses are known in this first phase, and lie outside the boxes.
for y in np.arange(.3,3.9,.4):
for x in np.arange(.3,4.9,.4):
if (abs(x-2.5)<.25 and abs(y-2)<.7) or (abs(x-.9)<.4 and abs(y-2.7)<.4) or (abs(x-4)<.4 and abs(y-.9)<.4): continue
p=np.array([x,y,0.]);trace(grid,p,scan(p))
distance=distance_transform_edt(grid<.5)*resolution
rng=np.random.default_rng(7); n=700; pose=np.array([.5,.6,0.])
particles=pose+rng.normal(0,[.12,.12,.08],(n,3)); weights=np.full(n,1/n); errors=[]
for k in range(40):
turn=.02; move=.04
pose+=np.array([move*np.cos(pose[2]),move*np.sin(pose[2]),turn])
# Independent noisy odometry and lidar; truth is used only to simulate/evaluate.
u=move+rng.normal(0,.005); omega=turn+rng.normal(0,.004)
particles[:,0]+=(u+rng.normal(0,.012,n))*np.cos(particles[:,2])
particles[:,1]+=(u+rng.normal(0,.012,n))*np.sin(particles[:,2])
particles[:,2]+=omega+rng.normal(0,.01,n)
z=np.clip(scan(pose)+rng.normal(0,.02,len(angles)),0,5)
a=particles[:,2,None]+angles; xx=particles[:,0,None]+z*np.cos(a); yy=particles[:,1,None]+z*np.sin(a)
ix=np.clip((xx/resolution).astype(int),0,w-1); iy=np.clip((yy/resolution).astype(int),0,h-1)
likelihood=.99*np.exp(-.5*(distance[iy,ix]/.15)**2)+.01
logw=np.log(weights+1e-300)+np.mean(np.log(likelihood),axis=1)*4
weights=np.exp(logw-logw.max());weights/=weights.sum()
estimate=np.sum(particles[:,:2]*weights[:,None],axis=0)
errors.append(np.linalg.norm(estimate-pose[:2]))
if 1/np.sum(weights**2)<n/2:
c=np.cumsum(weights);c[-1]=1; positions=(rng.random()+np.arange(n))/n
particles=particles[np.searchsorted(c,positions,side='right')].copy();weights.fill(1/n)
print('celdas libres/ocupadas:',np.sum(grid<-.5),np.sum(grid>.5))
print('RMSE y error final de posicion (m):',round(float(np.sqrt(np.mean(np.array(errors)**2))),4),round(float(errors[-1]),4))npm run lab and open the connection link.Exercises
Step 1 of 3. How are prior odds updated?
import numpy as np
def resample(particles, weights, rng):
passSources: Dellaert and colleagues, MCL, Elfes, occupancy grids, Fox, KLD-sampling and MuJoCo ray API. See also Thrun, Burgard and Fox, Probabilistic Robotics, chapters 6, 7 and 9.