Chapter 08 · Map, localize, navigate, and recover with Nav2
Today in the field story
One problem, then the next
Release the Medicine-Cart Route Trial as two explicit modes—mapping and saved-map navigation—with one transform authority each. Run the frozen suite, preserve nominal and failure bags, enforce zero keepout and post-cancel command violations, and let hard gates override a flattering average. The verdict must state that Jazzy/Harmonic simulation validates only the modeled stack and tested fault conditions.
- Why now
The chapter’s integration work becomes credible only when a clean reviewer can reproduce the full verdict.
- Ignore today
Ignore real-floor stopping, wheel slip, safety PLC, and site acceptance claims.
- Unlocks next
A concrete autonomy artifact and failure corpus for perception and estimator improvements.
Understand
Build the physical picture first
The phase demo is a release candidate, not a magic show: another engineer should be able to start it, interrupt it, inspect the evidence, and reach the same verdict.
The completed workflow has two deliberate operating modes. Mapping mode runs the simulator, odometry, lidar, and SLAM Toolbox to create and inspect a map. Navigation mode loads an approved map, starts one localization authority such as AMCL, brings the Nav2 lifecycle stack active, verifies current costmaps and transforms, then accepts goals. Keep these launch paths and configuration versions explicit so a reviewer never accidentally runs two map→odom publishers or navigates with an unsaved draft map.
A resilient demonstration covers the whole goal loop: valid initial pose, active lifecycle state, current localization, global plan, local commands, progress, goal verification, terminal result, and correlated operator status. It must also exercise cancellation, a temporary obstruction that can recover, a permanent obstruction that must reroute or fail, stale or lost localization, and one lifecycle or server failure. The required response may be success or safe failure; resilience does not mean every impossible mission finishes.
Acceptance criteria must be written before the final runs. Examples include a minimum autonomous success rate for fixed scenarios, no collision events, final-pose tolerance, maximum cancellation-to-stop time, bounded recovery attempts, transform freshness, and zero command output after terminal state. Some conditions are hard gates: one command-chain bypass or collision may reject the release even when average task success is high. Keep safety-critical gates separate from performance averages.
The evidence package should include a short architecture and frame diagram, map provenance, versioned parameters, launch commands, scenario manifest, raw result table, bags or decisive traces, uncut nominal and failure videos, issue links, and an honest limitations section. A README should explain the one-command happy path and the one-command regression suite. Avoid screenshots without timestamps or logs without the goal and scenario identity that produced them.
This project is strong job evidence because it joins software and physical reasoning. In an interview, explain the map and frame contract, planner/controller boundary, costmap layers, lifecycle and behavior-tree policy, one failure's causal trace, the metric that prevented a false claim, and the next test needed on real hardware. Do not claim production safety or hardware validation from Gazebo. Claim exactly what the simulation, injected faults, and reproducible artifacts prove.
Words you need
Name each idea precisely
- Operating mode
A declared set of active components and authorities for a specific purpose such as mapping or saved-map navigation.
Physical example:Mapping uses SLAM Toolbox as
map→odomauthority; saved-map navigation stops it and activates AMCL instead.- Acceptance criterion
A measurable rule written before the trial that decides pass, safe failure, or rejection.
Physical example:After cancel, observed speed must fall below 0.02 m/s within 0.5 s in the fixed simulation.
- Hard gate
A condition whose violation rejects the build regardless of average performance.
Physical example:Any uncommanded motion after terminal cancellation blocks release even if 19 other trials pass.
- Traceability
The ability to connect a requirement and scenario to exact configuration, execution evidence, result, and issue.
Physical example:NAV-CANCEL-02 links its criterion to row 17, an MCAP bag, the cancel timeline, and a fixed defect.
- Safe failure
A task does not complete, but the system reaches a bounded non-moving or otherwise declared safe state and reports why.
Physical example:Both aisles remain blocked, so the goal aborts, commands stop, and the fleet receives a structured obstruction result.
Math, one line at a time
Work through today’s relationship
Prerequisite rescue · optionalOccupancy probability and path cost
Navigation converts uncertain map cells into a collision-aware route.
- p(occupied)
- belief that a map cell contains an obstacleUnit: probability from 0 to 1
- g(n)
- cost already travelled to cell nUnit: cost or metres
- h(n)
- estimated remaining costUnit: same as g
For an A* node, suppose g = 4 m and admissible h = 3 m.
Total priority f = g + h = 7 m.
The planner compares f values, but the final path must also clear the inflated robot footprint.
It resembles shortest-path routing in a network, but each node represents physical space and the robot has width.
What is f when g = 2.5 m and h = 1.5 m?
f = 4.0 m.
One explicit acceptance gate is
Apply hard gates before accepting a high average
A 12-trial candidate completes 11 goals autonomously, so task success is 91.7%. The declared target is at least 90%, but one cancellation trial emits a nonzero velocity command after the action reaches Canceled, violating a zero-post-terminal-command hard gate.
Calculate task success: 11 / 12 = 0.9167, or 91.7%, which meets the numeric success-rate target.
Inspect hard gates separately: the post-terminal command violates an explicit command-integrity rule.
Reject the candidate even though its average success rate passes; averages cannot waive a hard gate.
Trace the late command to its publisher, goal identity, timestamp, and velocity chain rather than labeling the whole trial simply failed.
Repair the publisher ownership or shutdown sequence and rerun the affected case for diagnosis.
Rerun the full frozen 12-trial suite before release because the command-chain change could affect nominal and obstruction behavior.
The first candidate is rejected on command integrity despite 91.7% task success; acceptance requires the repaired build to pass both the full suite and every hard gate.
Release judgment is a set of explicit constraints, not one score that allows a dangerous result to hide inside an average.
Physical examples
Where this appears in real life
Fire drill instead of a building tour
A building is not judged only by a pleasant guided tour; a drill checks alarms, exits, roles, timing, and what happens when one route is blocked.
The failure path is planned, observed, and timed rather than hidden from the demonstration.
Recipe with weighed ingredients
Another cook follows the same recipe, ingredient weights, oven setting, and timing, then compares the result with a declared standard.
Reproducibility requires versions and conditions, not only a photo of the first successful result.
Hands-on exercise
Make the idea observable
Create a clean release-candidate tag or recorded commit for the simulated Nav2 project and a frozen scenario manifest. Do not connect powered hardware.
Run the mapping launch once, inspect coverage and loop closure, save map and pose-graph artifacts, and record the exact simulation, sensor, and SLAM configuration.
Run the saved-map navigation launch and add automated preflight checks for lifecycle active state, single transform authority, current localization, current costmaps, and command-publisher ownership.
Execute the frozen suite with nominal, cancel, temporary block, permanent block, bad initial pose or localization loss, and one managed-server failure; retain every result row.
Verify hard gates for collision, post-terminal commands, cancellation-to-stop time, retry budget, stale-data behavior, and correct structured terminal result.
Freeze a hashable Week 11 handoff: source commit or container identity; Gazebo world and random seed; MCAP bag; map image/YAML and serialized pose graph; launch, parameter, and behavior-tree files; a timestamped TF snapshot; scenario manifest; raw result rows; architecture diagram; uncut demos; failure taxonomy; and known limitations.
Ask another engineer or a clean environment to follow the README, reproduce one nominal and one failure case, and record any undocumented assumption as a defect.
The final state shown by the action, behavior tree, lifecycle nodes, command stream, odometry, localization, costmaps, and report should agree for every trial.
A clean reviewer can verify every handoff hash, build or launch the project, reproduce the declared suite, recalculate metrics from raw rows, inspect at least one failure trace, and reach the same release verdict.
Build today
Launch one pinned Gazebo, SLAM Toolbox, AMCL, and Nav2 stack; survive cancellation, obstruction, stale localization, and bounded recovery; then freeze the world, seed, bag, map, graph, configuration, transform snapshot, scenarios, and raw results.
Evidence to save
DONE when the weekly ship note explains how “Mandatory resilient Nav2/SLAM phase demo” changed the build, what still fails, and the first task for next week.
Project gate
Gate 2 · Ship a ROS 2 simulated task with bags, logs, metrics, and recovery—not only a success video.
Common mistakes
Catch the wrong mental model
Showing mapping and navigation together without naming which node owns map→odom.
Define separate operating modes and assert exactly one transform authority before accepting work.
Calling every recovered trial a clean success.
Keep recovery type, attempt count, delay, and original failure visible even when the final task succeeds.
Letting a high average success score override a collision or post-cancel command.
Evaluate safety and command-integrity hard gates separately from aggregate performance.
Claiming a simulation demo proves production hardware safety.
State the exact simulation and fault-injection evidence, then list hardware commissioning, stopping, sensor, load, and safety validation still required.
Job connection
How this becomes employable evidence
Own an AMR navigation release gate across on-robot software, operator UI, and fleet result reporting, with replayable cancellation, obstruction, localization, lifecycle, and command-chain evidence.
Relevant target roles
- Robotics Deployment, Integration & Validation Engineer
- Robotics Application / ROS 2 Integration Engineer
- Robotics Software Engineer — ROS 2 / AMR
- Robot HMI / Control & Monitoring Engineer
- Robot Fleet Backend / Platform Engineer
Chapter 08 interview drill
Interview questions: Mandatory resilient Nav2/SLAM phase demo
Practise a 60–90 second answer: define the idea, connect it to a physical robot, state assumptions, frames, and units when relevant, then finish with the failure signal or evidence you would inspect.
Primary interview scenario
Walk through your Nav2 phase demo as a release review: architecture, frame ownership, map provenance, costmap policy, planner/controller flow, lifecycle, failure injection, hard gates, metrics, and what remains unproven without hardware.
Answer shape: clarify the situation → trace the physical and software path → test the most likely boundaries → name the evidence that would confirm the result.
Technical follow-up questions
Q1Why should mapping and saved-map navigation be separate launch modes?
They use different global-pose authorities and artifacts; separation prevents conflicting map→odom publishers and makes the approved map version explicit.
Q2Can a 95% task-success rate pass a release with one hard-gate violation?
No. A hard gate is evaluated independently and rejects the build regardless of the average.
Q3What should you claim after a Gazebo-only Nav2 project?
Claim the reproducible simulated behavior, timing, failure handling, and evidence actually tested, while clearly stating that hardware and production safety remain unverified.
Chapter starter artifact
Preview A* on a frozen medicine-cart grid
A Jazzy/Harmonic Nav2 and SLAM package maps or loads one world, localizes with single transform ownership, enforces footprint and keepout policy, navigates fixed goals, handles obstruction and cancellation, and passes a reproducible scenario matrix with no command-integrity hard-gate violation.
const mission = "medicine-cart";
const start = [0, 0];
const goal = [4, 4];
const blocked = new Set(["1,1", "1,2", "2,2", "3,2"]);
const key = ([x, y]) => x + "," + y;
const heuristic = ([x, y]) => Math.abs(goal[0] - x) + Math.abs(goal[1] - y);
if (blocked.has(key(start)) || blocked.has(key(goal)) || heuristic(start) !== 8) throw new Error("invalid search contract");
const open = [{ point: start, cost: 0, path: [key(start)] }];
const best = new Map([[key(start), 0]]);
const moves = [[1, 0], [0, 1], [-1, 0], [0, -1]];
let solved; const expanded = [];
while (open.length > 0) {
open.sort((a, b) =>
(a.cost + heuristic(a.point)) - (b.cost + heuristic(b.point))
|| a.path.join(">").localeCompare(b.path.join(">")));
const current = open.shift();
expanded.push(key(current.point));
if (key(current.point) === key(goal)) { solved = current; break; }
for (const [dx, dy] of moves) {
const next = [current.point[0] + dx, current.point[1] + dy];
const name = key(next);
const inside = next.every((value) => value >= 0 && value <= 4);
const nextCost = current.cost + 1;
if (!inside || blocked.has(name) || nextCost >= (best.get(name) ?? Infinity)) continue;
best.set(name, nextCost);
open.push({ point: next, cost: nextCost, path: current.path.concat(name) });
}
}
if (!solved) throw new Error("no route");
console.log("mission=" + mission);
console.log("cost=" + solved.cost);
console.log("expanded=" + expanded.join(">"));
console.log("route=" + solved.path.join(">"));
console.log("uncertainty=PREVIEW_ONLY");
console.log("status=PASS");Download the file into your terminal's current folder, then run the command below. The expected output is exact.
- Run
node week-08-medicine-cart-astar.mjs
- Expected output
mission=medicine-cart cost=8 expanded=0,0>0,1>0,2>0,3>0,4>1,4>2,4>3,4>4,4 route=0,0>0,1>0,2>0,3>0,4>1,4>2,4>3,4>4,4 uncertainty=PREVIEW_ONLY status=PASS
- Planted failure to diagnose
Multiply the Manhattan heuristic by three. It then overestimates remaining cost and loses the admissibility guarantee used by this shortest-path teaching case, even if this small grid still returns a route.