The localizer hands the planner one pose. The planner needs a map, built at the right pose and the right time. Place each scan 30 ms late while the robot turns at 90° a second, and a wall 5 m away lands 24 cm off.
Pick how late the code places each scan and watch the robot turn in its room. Then we build, piece by piece, the grid, the cost, the surface, the boxes, the tracks and the handoff that a planner reads.
You need what a probability is and a little Python. We build the rest from zero.
Robotics Engineering, Lesson 9 of 26, the Robot Perception series. It follows Lesson 8, Drift and Loop Closure. Detection basics are taught in AA 274A Lesson 10; the full occupancy derivation is in AA 274A Lesson 12.
Illustrative toy: an 8 m by 5 m room with a 1.1 m door, on a 5 cm grid, 180 beams, 10 scans a second for 4 s. The robot turns at 90°/s left, then right. A cell is a wall after 2 hits. The halo is a 0.25 m robot radius.
Chapter 0
Sweep a robot down an aisle and watch a fan of ranges become a map
A warehouse robot knows where it is to two centimetres. Lessons 1 to 8 earned that. Now it must drive to the loading dock, and thirty seconds ago a forklift parked in the only aisle.
The localizer gives three numbers: x, y and the heading θ. The planner asks a different question: which floor around me is free? A pose cannot answer it. The answer is a map: a store, built from the sensor stream, that says for each place whether the robot may go there.
Left is all the sensor gives: one distance per beam. Right is the map the beams have built so far. Drag the robot down the aisle.
Illustrative toy: a 32 by 18 cell aisle, 90 beams over 270°, no noise.
The beams inferred every cell on the right. The sensor never said "wall". It said "3.2 m at this angle", from a pose that changes between scans. Downstream perception is the code that turns those numbers into a map a planner can query in one lookup.
The symptom is a robot that drives into a forklift that arrived after the last map update. To measure it, log the age of the map cells the planner reads. The fix is a map that every scan updates, which the next chapter builds.
Chapter 1
Feed one cell forty noisy scans and see why the update is a sum
Chop the floor into square cells, 5 cm on a side. Each cell holds one number about whether something solid fills it. That array is an occupancy grid.
One beam says two things. Every cell it flew through is probably free. The cell where it stopped is probably occupied. We need a rule that adds this evidence to each cell, scan after scan, without storing old scans.
Store the belief as log-odds: the log of p over one minus p, where p is the chance the cell is occupied. A cell nobody has seen has p = 0.5 and log-odds 0. In log-odds, Bayes' rule for one more reading becomes one addition. AA 274A Lesson 12 derives it step by step.
Call the cell's log-odds after scan t ℓt. Call what one reading adds ℓz: one fixed amount for a hit and another for a pass.
Ell-t equals ell-t-minus-one plus ell-z.
Ask whether the beam stopped in the cell or passed through it. Add the matching ell-z to the cell's log-odds. To read it back, p = 1 − 1 / (1 + eℓ).
OctoMap's default sensor model uses hit 0.7 and pass 0.4. Three hits take ell from 0 to 0.847, 1.695, 2.542, so p goes 0.70, 0.85, 0.93. After five hits (4.236), two stray passes leave 3.426, p = 0.97.
The cell is truly a wall. Each scan is a hit, or a false pass at the noise rate. Purple is the log-odds. Raise the noise, then lower the clamp.
Illustrative: +0.847 per hit, −0.405 per pass, a fixed random seed per noise rate. The cell reads occupied above p = 0.7.
A clamp keeps the log-odds between two limits, so a cell can change its mind. OctoMap clamps at p = 0.12 and 0.97, which is −2.0 to +3.5. We read a cell as occupied above p = 0.7, free below 0.3, and unknown between.
| A wall that stood for 500 hits, then moved | Log-odds at the start | Passes until it stops reading occupied |
|---|---|---|
| No clamp | 423.6 | 1,043 |
| Clamp at 8 | 8.0 | 18 |
| Clamp at 3.5 | 3.5 | 7 |
The symptom is a streak of phantom wall across open floor, where a person walked through the beams. To measure it, log the cells cleared and the cells marked per scan. A 10 m beam at 5 cm clears about 200 cells and marks 1, so a ratio near 1 means clearing is off. The fix is a free pass on every beam, plus the clamp.
Chapter 2
Grow a cost halo around two walls and find out if a robot still fits the gap
A planner treats the robot as a point. The robot is not a point. Route a 0.5 m wide robot through a 0.45 m gap and the grid says free while the body scrapes both sides.
The fix writes the robot's width into the map. Every occupied cell spreads a cost to the cells around it. That map of costs is a costmap, and the spreading step is inflation.
nav2 stores one byte per cell. 254 is lethal: an obstacle. 253 is inscribed: the robot's centre here puts its body on the obstacle. 0 is free.
Call the distance from a cell to the nearest obstacle d. Call the robot's inscribed radius, the largest circle inside its footprint, ri. A decay rate k, which nav2 calls cost_scaling_factor, sets how fast the cost falls.
Cost of d equals 252 times e to the minus k times d minus r-i, for d larger than r-i.
Find how far past r-i the cell is. Multiply by k, flip the sign and take e to that power. Multiply by 252. nav2 keeps the whole number.
With made-up k = 3.0 per m and r-i = 0.20 m: at d = 0.30 m, 252 × e−0.3 = 186.7, stored as 186. At 0.40 m, 138. At 0.60 m, 75. The cost drops under 50 past 0.74 m.
Purple cells are two walls. Warm is the cost halo; the solid warm band is where the robot's centre may not go. The curve is the cost across the gap. Change the three knobs.
The cost formula and the values 254, 253 and 252 are nav2's inflation layer. The walls, the gap and the knob ranges are illustrative.
The robot fits if the gap's centre is more than r-i from each side. Above that, k only sets how much the planner dislikes the squeeze. A planner adds cell costs to path length, so a small k makes the robot take long detours around clutter.
The symptom is a robot that refuses a gap a person can see it fits. To measure it, read the cost at the gap's centre. At 253 the footprint is too large; just under it, k is too small. Fix the footprint to the real robot, then raise k.
Chapter 3
Fuse two wrong depth readings and watch the surface land where neither put it
A drone needs free air in 3D; a robot arm needs the exact surface of a part. A 3D grid of cubes, a voxel grid, takes the Chapter 1 update unchanged. But a slanted wall fills every voxel it crosses, and halving the voxel costs eight times the memory.
A TSDF (truncated signed distance function) stores a signed distance in each voxel: how far the surface is along the camera ray, and on which side. The surface is where that number crosses zero, found between voxels.
One depth pixel measures the depth z along its ray. A voxel on that ray sits at range r from the camera. A truncation distance μ limits how far from the surface we care.
D equals z minus r over mu, clamped between minus one and plus one.
Subtract the voxel's range r from the measured depth z. Divide by mu. Cut the result to between minus one and plus one.
With made-up numbers: z = 1.98 m, mu = 0.08 m, a voxel at r = 2.00 m. D = (1.98 − 2.00) / 0.08 = −0.25: a quarter of mu behind the surface.
Each voxel keeps a running weighted average over frames (Curless and Levoy, 1996). Call the stored value D with weight W, and the new frame's value Dz with weight w.
The new D is W times D plus w times D-z, over W plus w. The new W is W plus w.
Multiply the stored D by its weight W. Add the new D-z times its weight w. Divide by the total weight, then add w to W.
With made-up numbers: the true surface is at 2.00 m. Camera A says 1.98, camera B says 2.02. At the voxel r = 2.00, A gives −0.25 and B gives +0.25. Equal weights: (−0.25 + 0.25) / 2 = 0. The fused zero is on the truth.
Pink is the true surface, blue lines the two cameras, purple the fused field. Move camera A's error and weight.
Illustrative: one ray, surface at 2.00 m, mu = 0.08 m, 2 cm voxels. B's error mirrors A's.
The fused surface sits at the weighted mean of the depths: weights 3 and 1 give 1.99 m. Marching Cubes (Lorensen and Cline, 1987) turns the field into a mesh where cube corners change sign.
The symptom is a flat wall that comes out doubled or fuzzy. Two frames wrote it at different places because a pose was wrong. To measure it, look along a ray for two zero crossings. The fix is better poses (Lesson 8) and a mu larger than the pose jitter.
Chapter 4
Score two boxes by their overlap, then prune four boxes down to one per object
The grid says a cell is occupied. It cannot say if that is a wall to avoid forever or a forklift that will leave in ten seconds. That takes object detection: for each camera frame, a list of boxes, each with a class and a confidence score. AA 274A Lesson 10 builds a detector from zero; here we need the two tools that sit after it.
Both rest on one question: how much do two boxes overlap? Call the area both boxes cover the intersection, and the area either one covers the union.
IoU of A and B equals the area of A intersect B, over area of A plus area of B minus that overlap.
The overlap runs from the larger left edge to the smaller right edge, and the same for top and bottom. If a width comes out negative, use zero. Add both areas, subtract the overlap once, and divide.
With made-up boxes A from (10, 10) to (60, 60) and B from (30, 30) to (80, 80): the overlap is 30 × 30 = 900. The union is 2,500 + 2,500 − 900 = 4,100. IoU = 900 / 4,100 = 0.22.
A detector fires several boxes on one object. Non-maximum suppression (NMS) keeps one:
A and B sit on a forklift; C and D on a person. Solid boxes survive; NMS fades the ones it suppresses. Drag the threshold.
Illustrative boxes, each 100 by 100 pixels. Pair IoUs: A–B 0.67, A–C 0.25, A–D 0.11, C–D 0.67.
At 0.5, A deletes B (0.67) but not C (0.25). Then C deletes D. Two boxes stay, one per object. A could never delete D, because they barely overlap. Each object's best box prunes its own cluster.
The symptom is two people side by side detected as one. To measure it, count merged objects in crowded test frames. The fix is a higher threshold, or Soft-NMS, which lowers scores instead of deleting. A second classic bug is a missing max(0, ·): two boxes that do not touch then report an overlap.
Chapter 5
Change how hollow a pallet is and count the free cells a box marks as blocked
A box is always a rectangle. Real objects are not. Put an L-shaped pallet on a 4 by 4 patch of floor cells: the bottom row and the left column, 7 cells. The tightest box around it covers all 16 cells. It marks 9 free cells, 56% of the box, as blocked.
Semantic segmentation labels every pixel with a class. Instance segmentation also tells objects apart. Either way the output for an object is a mask: the set of its pixels. In an aisle one pallet wide, those 9 cells decide if the robot can squeeze past the open side of the L.
Purple cells are the mask. The dashed blue rectangle is the box. Red-hatched cells are free floor the box blocks. Drag the notch.
Illustrative grid. At notch 0 the pallet is a full rectangle and the box is exact.
Score a mask with the same IoU, counted over pixels: matching pixels over pixels in either mask. Averaged over classes it is the mIoU that segmentation papers report. Two different masks can share one box, so box IoU cannot see a wrong outline. Mask IoU can.
| Output | Stable from frame to frame? | Truthful about free floor? |
|---|---|---|
| Box | yes | no: 9 of 16 cells wrong for the L |
| Mask | the inside is; the edge flickers | yes, cell by cell |
The symptom is a mask whose edge flickers, so the costmap halo grows and shrinks each frame and the path twitches. Edge pixels sit near the 0.5 threshold, and noise flips them. To measure it, track boundary IoU (IoU in a thin band at the outline) apart from full IoU. The fix is two thresholds, a high one to turn a pixel on and a lower one to keep it on, or smoothing over time.
Chapter 6
Stretch a prediction's uncertainty and see which detections can belong to the track
A detector forgets everything between frames. To predict where the forklift goes, the robot needs its identity over time: multi-object tracking. Each track runs a constant-velocity Kalman filter (Lesson 3 covers the covariance) and predicts where its object appears next.
Which new box belongs to which track? That is data association. A box is a candidate only inside the track's gate, a test on the Mahalanobis distance: distance measured in units of the prediction's own uncertainty.
Call the gap between the detected position and the predicted position the residual y. Call the prediction's covariance P, and the gate threshold γ.
D-M squared equals y transpose times P inverse times y, and it must be less than gamma.
Take the residual y. Square its part along each axis of P and divide by the variance on that axis. Add. If the sum is below gamma, the box may be this track.
With made-up numbers: prediction (5, 5), P = diag(1, 1). A box at (5.5, 5.2): y = (0.5, 0.2), d-M squared = 0.25 + 0.04 = 0.29, inside 9.21. A box at (9, 9): y = (4, 4), 32, rejected; it starts a new track.
The purple cross is the track's prediction; the ellipse is its gate. Blue dots are detections; a red ring marks a rejected one. Stretch and turn the uncertainty.
Illustrative detections. The 9.21 threshold is the 99% point of the chi-squared distribution with 2 degrees of freedom.
Take sigmas of 4 m and 1 m. A detection 3.5 m along the long axis scores 3.5² / 4² = 0.77 and passes. The same 3.5 m across the short axis scores 12.25 and fails. Among the boxes inside the gates, the Hungarian algorithm picks the pairing with the least total cost. SORT (Bewley et al., 2016) is this recipe with IoU as the cost. DeepSORT (Wojke et al., 2017) adds what the object looks like.
The symptom is one walking person who gets ID 4, then 9, then 12, so the velocity estimate restarts each time. An occlusion hides the person longer than the track lives, and the tracker deletes it. To measure it, count ID switches (IDS) in MOTA = 1 − (FN + FP + IDS) / GT. Rising IDS with steady misses and false alarms points at association. The fix is a longer coast time and an appearance feature.
Chapter 7
Carry a wall from the robot's body up to the planner's map, and see why poses do not add
The planner reads a costmap; the controller drives the wheels. Each needs the obstacles and the robot in its own frame, a coordinate system with an origin and axes. ROS fixes three frames in its convention REP 105:
Why two global frames? A controller cannot chase a pose that jumps 20 cm in one tick. A planner cannot trust a pose that drifts. A pose of frame B inside frame A is a heading θ and a position t. A point pB, given in B, lands in A at pA:
P-A equals R of theta times p-B, plus t.
Turn the point by B's heading theta, then add B's position t. To go up two frames, do it twice: base_link to odom, then odom to map.
With made-up poses: the robot is at (3, 0), heading 30°, in odom; odom is at (2, 1), turned 10°, in map. A wall 4 m ahead: R(30°)(4, 0) + (3, 0) = (6.46, 2.00) in odom. Then R(10°)(6.46, 2.00) + (2, 1) = (8.02, 4.09) in map.
The grey axes are map, purple is odom, teal is the robot. The pink dot is the wall, placed correctly. Drag the correction angle and switch on the shortcut.
Illustrative poses: the robot at (3, 0, 30°) in odom, odom at (2, 1) in map, the wall 4 m ahead.
The shortcut adds the positions and the angles: the robot at (5, 1), heading 40°. It forgets that the correction also turns the odometry offset. The wall lands at (8.06, 3.57), 0.52 m from the truth. The planner's goal goes the other way, down to the body: pB = R(θ)T(pA − t). The goal (8.0, 4.0) in map is (3.93, −0.06) for the robot: almost straight ahead.
The symptom is obstacles placed up to 0.75 m off while driving at 1.5 m/s with a 2 Hz localizer. The code read the global pose directly, and it was half a second old. To measure it, log the age of every transform used. The fix is to go through odom. Odometry covers the half second, so the error is only the drift in it: about 1.5 cm at an illustrative 2%.
Chapter 8
Turn the robot faster and delay the pose, and measure how far a wall moves
This is the hero's bug. The lidar stamps a scan at time t. The code places it with the pose at now, which is t plus a delay. If the robot turned during that delay, every beam lands at the wrong bearing. The walls in the costmap smear into arcs, and the local planner boxes itself in.
Call the robot's turn rate, the yaw rate, ω. Call the delay between the scan's stamp and the pose used L, the latency. A beam's range is r, and the sideways error of its end point is s.
S equals r times tan of omega times L.
Multiply the yaw rate omega by the latency L: that is the wrong angle. Take its tangent and multiply by the range r.
With made-up numbers: 90°/s and 30 ms give a wrong angle of 2.7°. At 5 m: 5 × tan 2.7° = 0.236 m, about 24 cm. At 1 m it is only 4.7 cm.
The pink arc is the true wall at 5 m. Purple is where the scan puts it. Warm is a 0.10 m inflation margin. Turn faster or wait longer.
Illustrative wall and margin. The offset is s = r tan(ωL) at r = 5 m.
| Yaw rate | Latency | Wrong angle | Offset at 5 m |
|---|---|---|---|
| 45°/s, gentle arc | 10 ms | 0.45° | 3.9 cm |
| 90°/s, brisk turn | 30 ms | 2.7° | 23.6 cm |
| 90°/s, brisk turn | 50 ms | 4.5° | 39.4 cm |
| 180°/s, spin in place | 30 ms | 5.4° | 47.3 cm |
Driving forward adds less. At 0.4 m/s over 30 ms the scan slides 1.2 cm, at every range. Past 0.25 m of range, the turn error is the larger one. The fix is to look up the pose at the scan's stamp. The transform buffer holds poses at ticks, so the lookup blends the two ticks around the stamp. Blend the heading along the short arc: midway between 359° and 1° is 0°, not 180°.
pythonimport numpy as np def interp_se2(A, tA, B, tB, t): # A, B: (x, y, heading in rad) a = (t - tA) / (tB - tA) # how far along: 0 at A, 1 at B x = A[0] + a * (B[0] - A[0]) y = A[1] + a * (B[1] - A[1]) d = (B[2] - A[2] + np.pi) % (2 * np.pi) - np.pi # the short arc return x, y, A[2] + a * d # poses at 1.00 s and 1.10 s, scan stamped 1.06 s -> (4.996, 1.572, 41.6 deg) interp_se2((4.90, 1.50, np.radians(38)), 1.00, (5.06, 1.62, np.radians(44)), 1.10, 1.06)
The symptom is a crisp costmap while driving straight that smears into arcs when the robot turns. To measure it, log now minus the scan stamp for every scan, and plot the smear against yaw rate times that age. The fix is a transform lookup at the scan's stamp, never at now. Unit tests rarely turn fast, so this bug ships.
Chapter 9
Drive a robot down an aisle, add sensor noise and turn the clamp
This bench puts Chapter 1 to work on a whole aisle. Every beam does four things, in order:
Left is the true aisle and the beams. Right is the map. Press Drive, then raise the noise and watch settled walls; then lower the clamp.
Illustrative toy: a 32 by 18 cell aisle, 90 beams over 270°, range 14 cells. Noise is the chance a beam that hit a wall reports nothing, so it clears through the wall.
Trace one Bresenham line by hand, from cell (2, 2) to (7, 5). It steps (3, 3), (4, 3), (5, 4), (6, 4) and ends at (7, 5). It touches each cell once, with no gaps and no floats. The first five cells get a clear; (7, 5) gets the mark.
Cells seen once, from far, at a slant, stay unsure. Cells seen from many poses harden. That difference is what an exploration policy uses to choose where to look next (frontiers).
The symptom is a settled wall that wears away under a burst of bad readings, or a wall that stays after its pallet moved. To measure it, count the passes a wall cell needs to stop reading occupied: 7 from a clamp at 3.5, 18 from 8. The fix is a clamp chosen from how fast the world changes.
Chapter 10
Keep the numbers, the checklist and the core code in one place
A pose is a point; a decision needs a neighbourhood. Downstream perception turns noisy, stamped measurements into a map of free space, surfaces and moving things that a planner reads in one lookup. Store the belief as a sum and fuse by weighted averages. Give moving things an identity. Place every measurement with the pose from its own moment.
| Term | What it is | Number to carry |
|---|---|---|
| Log-odds update | ℓt = ℓt−1 + ℓz | +0.847 per hit, −0.405 per pass; 3 hits: p = 0.93 |
| Clamp | limits on ℓ | OctoMap −2.0 to +3.5; 7 passes to forget from 3.5 |
| Inflation | 252 e−k(d − ri) | 254 lethal, 253 inscribed; k = 3, d = 0.30: 186 |
| TSDF | clamp((z − r) / μ, −1, 1) | 1.98 and 2.02 fuse to 2.00 |
| IoU | overlap / union | 900 / 4,100 = 0.22 |
| Gate | yTP−1y < γ | γ = 9.21; 0.29 passes, 32 fails |
| Frames | pA = R(θ)pB + t | wall (4, 0) in base_link: (8.02, 4.09) in map |
| Clock error | s = r tan(ωL) | 90°/s, 30 ms, 5 m: 24 cm |
pythonimport numpy as np L_OCC, L_FREE, L_MAX = np.log(0.7/0.3), np.log(0.4/0.6), 3.5 def integrate_scan(L, robot_cell, beams): # beams: [(end_cell, hit)] for end, hit in beams: ray = bresenham(robot_cell, end) for cx, cy in ray[:-1]: L[cy, cx] += L_FREE # passed through ex, ey = ray[-1] L[ey, ex] += L_OCC if hit else L_FREE # max range marks nothing np.clip(L, -L_MAX, L_MAX, out=L) def inflate_cost(d, r_i, k): # nav2's inflation formula if d == 0: return 254 if d <= r_i: return 253 return int(252 * np.exp(-k * (d - r_i))) def to_map(p_base, T_map_odom, T_odom_base): # 3x3 homogeneous transforms at the SCAN stamp return (T_map_odom @ T_odom_base @ np.append(p_base, 1.0))[:2]
| Topic | Lesson | How it connects |
|---|---|---|
| Frames | Lesson 1 | the rigid-body math behind Chapter 7 |
| Clocks | Lesson 2 | stamps and sync, the root of Chapter 8 |
| Covariance | Lesson 3 | the P in the gate |
| Detection | AA 274A Lesson 10 | how a detector makes the boxes and masks |
| Occupancy and frontiers | AA 274A Lesson 12 | the full log-odds derivation and exploration |
| 3D geometry | 3D Vision | depth, point clouds, camera models |
Robotics Engineering, Lesson 9 of 26, in the Robot Perception series. The ideas are re-taught here in our own words, devices and toy numbers.
Now press Present or Teach. Explain from memory the log-odds sum, inflation, the TSDF zero, IoU and NMS, the gate and the frame tree. Then go back to the turning robot, pick 100 ms late, and say why the door closes.