Phase 02 · Week 8 · 90 minutes

Day 50: map→odom→base frames, occupancy grids, SLAM, and AMCL

Mandatory Nav2 and SLAM first flight · Operate the complete loop by contract now; preserve its evidence for estimator theory in Week 11.

Chapter 08

Map, localize, navigate, and recover with Nav2

Give the simulated mobile robot from Week 7 its first bounded navigation flight: launch one pinned SLAM Toolbox, AMCL, and Nav2 stack; inspect every input, output, frame owner, lifecycle state, action result, cancellation, and recovery; then preserve the run for Week 11. This chapter teaches the operating contract and observable failure signals. It deliberately postpones estimator mathematics and parameter tuning until the learner has built the probability, covariance, and Bayes foundations needed to reason about them.

Before you start

  • Run the Week 7 differential-drive robot in Gazebo with simulation time, wheel odometry, a correctly mounted lidar, and a connected map→odom→base_link→laser frame tree.
  • Use ROS 2 topics, actions, parameters, lifecycle states, rosbag2, RViz, and timestamps at a beginner level.
  • Read metres, seconds, radians, rates, percentages, and a simple x-y coordinate pair.
  • Keep all exercises in simulation; physical mobile-base testing requires a clear area, speed limits, independent stopping controls, and supervised commissioning.

By the end

  • Explain why map, odom, and base_link have different jobs and identify which component should publish each transform.
  • Build a 2D occupancy map with SLAM Toolbox, recognize scan-matching and loop-closure symptoms, save the result, and localize in it with AMCL.
  • Configure global and local layered costmaps using a measured footprint, live obstacle observations, inflation, unknown-space policy, and keepout zones.
  • Trace one NavigateToPose goal through localization, the global planner, optional smoother, local controller, progress and goal checks, and its action result.
  • Read a Nav2 behavior tree, distinguish a targeted recovery from blind retry, and verify lifecycle startup and shutdown before accepting goals.
  • Measure cancellation-to-stop latency, obstruction handling, collision-monitor behavior, replanning, retry budgets, and safe failure outcomes.
  • Evaluate navigation with frozen scenarios, denominators, path and timing metrics, localization evidence, recovery metrics, and an honest failure taxonomy.
  • Ship a repeatable Nav2 and SLAM phase demo that another engineer can launch, inspect, interrupt, and judge against declared acceptance criteria.

The field story

The Medicine-Cart Route Trial

A simulated medicine cart must travel from the pharmacy to a ward without entering a staff-only zone, colliding with a trolley, or continuing after an operator cancels. The Rainy-Day Simulator Lab provides its base, lidar, odometry, clock, and fault harness, but navigation adds a longer chain: map, global correction, local continuity, costmaps, path proposal, repeated control, lifecycle readiness, recovery, and terminal result. You will integrate that chain first and keep every authority and failure observable.

The Medicine-Cart Route Trial deliberately previews two deeper subjects without pretending to finish them. A small A* starter explains graph cost and heuristic choice before Nav2 plugins; a physical uncertainty preview distinguishes estimator confidence from measured error before Chapter 11 teaches probability, covariance, Bayes filtering, and EKF diagnostics. This spiral order lets a programmer ship a bounded navigation artifact now while knowing exactly which theory is deferred. The chapter ends with fixed scenarios, hard gates, cancellation-to-stop evidence, and an honest simulation-only verdict.

Why this chapter now

The simulator is ready for an integration-first autonomy artifact, and navigation provides a motivating target before estimator theory is studied deeply.

Ignore for now

Ignore derivations of covariance, Bayes filters, EKF Jacobians, and every Nav2 plugin option. Preview A* and uncertainty, then use one pinned stack with measured limits.

This unlocks

A portfolio-grade autonomy loop plus concrete failure evidence that Chapter 11 can later explain and improve.

Proof you will leave with

Save frame and transform ownership, map provenance, A* starter trace, costmap policy, planner/controller/action timelines, lifecycle and recovery paths, cancellation stopping evidence, metrics with denominators, fault artifacts, and gate verdict.

Environment contractUbuntu 24.04 with ROS 2 Jazzy, Gazebo Harmonic, a Jazzy-qualified Nav2 stack, and SLAM Toolbox is the golden integration path. The dependency-free starter runs with repository-supported Node.js 22.13.0 or newer.
Compatibility boundary

Unversioned Nav2 pages and later distributions are reference material, not runtime authority. Migrate only in an isolated matrix that repeats mapping, localization, planning, control, cancellation, lifecycle, recovery, and metric gates.

Smoke check

Source Jazzy, confirm the Harmonic simulation baseline, and verify nav2_bringup, slam_toolbox, and the selected localization package resolve before launching the frozen world.

Contract reviewed

2026-07-25

Runtime evidence

The dependency-free starter is executed by repository tests on the supported Node.js baseline. Chapter-specific ROS 2, Gazebo, model, dataset, checkpoint, and hardware environments are learner-created unless the repository supplies an explicit asset; run the smoke check and preserve its versions and output before claiming runtime compatibility.

Drift risk

high

Today in the field story

One problem, then the next

The Medicine-Cart Route Trial begins with two location stories: smooth local odometry and globally corrected map pose. Assign odom→base_link and map→odom to single authorities, build or load the occupancy map in separate modes, and initialize AMCL with scan evidence. Treat particles and covariance as an integration preview; Chapter 11 will derive probability, covariance, Bayes updates, and consistency checks.

Why now

Navigation needs a current global pose without corrupting the smooth local frame used by control.

Ignore today

Ignore covariance derivation and particle-filter mathematics until Chapter 11.

Unlocks next

A time-valid pose and map on which costmaps and goal execution can operate.

Understand

Build the physical picture first

Navigation needs two kinds of location at once: odom is a smooth pencil line that drifts, while map is the corrected floor plan that may move that whole pencil line when better evidence arrives.

A robot cannot plan to “the far shelf” until it can answer two questions: what does the floor look like, and where am I on that floor? A two-dimensional occupancy map divides the floor into small square cells. Each cell records free space, occupied space, or unknown space. The map has a resolution such as 0.05 m per cell and an origin that connects cell indexes to coordinates in the map frame. A map is a measurement product, not permanent truth: glass, shiny surfaces, narrow chair legs, moved pallets, and missing lidar coverage can make cells wrong or unknown.

The frame chain map→odom→base_link separates global correction from smooth local motion. Wheel odometry or a local state estimator normally publishes odom→base_link. It changes smoothly enough for control, but wheel slip and small calibration errors make it drift. SLAM or a localization system normally publishes map→odom. That transform corrects accumulated drift and can jump when a loop closure or new localization evidence changes the global estimate. Nav2 combines both transforms to learn the robot pose in map without forcing the controller to follow a jumping local signal.

SLAM means simultaneous localization and mapping: while the robot moves through an unknown space, it estimates both its path and the map. In this first flight, treat scan matching, pose graphs, and loop closure as named internal stages whose inputs, outputs, timestamps, and visible corrections you can observe. Do not tune their mathematics yet. A loop closure can straighten a corridor that slowly bent in the draft map, and it can change map→odom; Week 11 will reopen the saved run to explain why that correction was justified.

After a map is approved and saved, AMCL can estimate the robot pose inside that static map. Its particle cloud is a visible collection of pose hypotheses, but this week the cloud is a health signal rather than a tuning target. Confirm the required map, scan, initial pose, frames, timestamps, and single map→odom owner; then record convergence, loss, and recovery from the outside. Week 11 will teach weighting, resampling, covariance, motion and measurement models before asking you to alter estimator parameters.

Use one authoritative component for map→odom. For this chapter, use SLAM Toolbox while building the map, then stop that mapping instance and use AMCL with the saved map for normal navigation. SLAM Toolbox also has its own pose-graph localization mode, and Cartographer is another SLAM system with a similar frame contract, but mixing several active global-pose publishers creates conflicting transforms. Depth comes from making one stack observable and reliable before comparing alternatives.

Words you need

Name each idea precisely

Occupancy grid

A floor map split into equal cells that represent free, occupied, or unknown space.

Physical example:

At 0.05 m resolution, a 1 m-wide corridor spans about 20 grid cells.

map frame

A globally useful frame tied to the saved environment, where localization corrections are allowed.

Physical example:

A loading bay remains near the same map coordinate even after wheel odometry drifts.

odom frame

A locally smooth frame produced by odometry; it is useful for short-term control but may drift away from the map.

Physical example:

The wheels report a smooth 10 m trip even though slip makes the estimate end 0.4 m from the true mark.

SLAM

The task of estimating a robot path and building or refining a map at the same time.

Physical example:

A rover uses wheel motion and lidar scans to draw an unfamiliar office while estimating its own route.

AMCL

A particle-filter localizer that estimates a robot pose in an existing static map.

Physical example:

Hundreds of pose guesses compete until their predicted wall distances match the lidar scan.

Loop closure

Recognition that the robot has returned to a previously mapped place, adding a constraint that can correct accumulated drift.

Physical example:

The two ends of a mapped corridor loop finally meet, causing the draft walls to align.

Visual model

See the relationship

Swipe the technical canvas horizontally on a small screen.map→odom→base frames, occupancy grids, SLAM, and AMCL — concept diagramAn autonomous mobile robot replans around a trolley in a warehouse aisle. This visual applies that grammar to “map→odom→base frames, occupancy grids, SLAM, and AMCL”. Clear route: Localization is stable and the path preserves clearance. The displayed measure is 0.6 m clearance.robotgoaloccupiedClear route
Day 50 · ConceptLocalization is stable and the path preserves clearance. Measured anchor: 0.6 m clearance.

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
  1. For an A* node, suppose g = 4 m and admissible h = 3 m.

  2. Total priority f = g + h = 7 m.

  3. The planner compares f values, but the final path must also clear the inflated robot footprint.

Programmer analogy

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.

For this aligned one-dimensional example, transform composition reduces to addition:

xmapbase=xmapodom+xodombase=0.30+2.20=2.50 m.x_{\text{map}\to\text{base}}=x_{\text{map}\to\text{odom}}+x_{\text{odom}\to\text{base}}=0.30+2.20=2.50\ \mathrm{m}.

Combine a smooth odometry pose with a map correction

In an aligned, no-rotation teaching case, odometry says base_link is at (4.20, 1.00) m in odom. A localization update places the odom origin at (-0.70, 0.30) m in map.

  1. Name the relationships before touching the numbers: localization owns map→odom, while wheel odometry owns odom→base_link.

  2. Because this simplified case has aligned axes, add the x translations: x in map = -0.70 + 4.20 = 3.50 m.

  3. Add the y translations: y in map = 0.30 + 1.00 = 1.30 m.

  4. Report the answer as base_link at (3.50, 1.30) m in map; do not drop the frame or metre unit.

  5. Now suppose a loop closure changes only map→odom x from -0.70 to -0.85 m. The smooth odometry pose remains 4.20 m, but the corrected map x becomes 3.35 m.

  6. State the limitation: real transforms include rotation and timestamp, so tf2 must compose them; component-wise addition works only for this deliberately aligned example.

Result

The controller can keep using the smooth odometry history while global planning sees a corrected map pose.

What this proves

The apparent global pose can change without corrupting the locally smooth motion estimate because the correction lives on a different transform edge.

Physical examples

Where this appears in real life

Chalk line and printed floor plan

A wheeled suitcase traces a smooth chalk line around a room, but the line gradually misses the printed floor-plan doorway because each wheel turn was estimated slightly wrong.

Look for:

The continuous chalk line acts like odom. Moving the entire line until the doorway agrees acts like the map→odom correction; the suitcase does not physically teleport.

Many guesses in a school corridor

Several transparent cut-outs of a toy robot are placed at different points on a corridor plan, each with rays drawn toward nearby walls.

Look for:

The cut-outs whose predicted wall distances disagree with the measured distances lose weight; repeated motion and scans concentrate the likely pose.

Hands-on exercise

Make the idea observable

Use the working Week 7 Gazebo world, differential-drive robot, lidar, RViz, SLAM Toolbox, and rosbag2. Keep the real robot disconnected.

  1. Before mapping, inspect the frame tree and confirm one publisher owns odom→base_link, the laser has a time-valid path to base_link, and no node is already publishing map→odom.

  2. Launch SLAM Toolbox against the actual LaserScan topic, then drive the simulated robot slowly through the world while watching map cells, scan alignment, pose-graph growth, and transform age.

  3. Revisit one recognizable corridor or room to invite a loop closure; record a screenshot and the map→odom values before and after the correction.

  4. Save both the occupancy map metadata/image and the serialized pose graph, then record map resolution, origin, frame names, configuration version, and the bag used to create it.

  5. Stop the mapping instance, launch the saved map with AMCL, provide a deliberately approximate initial pose, and record the particle cloud, transform age, scan agreement, and recovery without tuning estimator internals.

  6. Plant one fault at a time—wrong scan topic, stale transform, or a second map→odom publisher—and capture the observable symptom before repairing it.

Observe

A useful map has aligned repeated structures, explored free space, sensible unknown boundaries, and reproducible provenance; localization has a time-valid transform and scan agreement, not merely a moving icon.

Done when

Another engineer can launch the bag or simulation, load the saved map, identify the publishers for both transform edges, initialize AMCL, and reproduce one documented mapping or localization fault.

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 learning log explains “map→odom→base frames, occupancy grids, SLAM, and AMCL” in five precise points and a checked example produces the predicted output.

Common mistakes

Catch the wrong mental model

Wrong

Calling the occupancy image the real environment.

Better

Treat it as a sampled, resolution-limited measurement with unknown regions, sensor blind spots, timestamped provenance, and a review process.

Wrong

Publishing map→base_link directly and skipping odom because the final pose appears correct.

Better

Preserve map→odom→base_link: global localization corrects the first edge and locally smooth odometry owns the second.

Wrong

Running AMCL, SLAM Toolbox mapping, and another localizer as simultaneous map→odom authorities.

Better

Select one global-pose authority for each operating mode and assert that the transform edge has only the intended publisher.

Wrong

Trusting a small AMCL particle cloud without checking scan alignment or external reference points.

Better

Compare predicted and observed scans, transform freshness, known landmarks, and repeatable pose error; confidence can be wrong.

Job connection

How this becomes employable evidence

Bring up an AMR localization stack at a customer site, determine whether a pose jump came from wheel odometry, scan timing, map quality, or the map→odom publisher, and leave a reproducible map provenance record.

Relevant target roles

  • Robotics Application / ROS 2 Integration Engineer
  • Robotics Software Engineer — ROS 2 / AMR
  • Robotics Deployment, Integration & Validation Engineer

Chapter 08 interview drill

Interview questions: map→odom→base frames, occupancy grids, SLAM, and AMCL

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

Explain why Nav2 needs both map and odom, who should publish each edge in map→odom→base_link, what changes during loop closure, and how you would diagnose a robot icon that jumps while wheel odometry stays smooth.

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 is `odom` allowed to drift but not jump?
Model interview answer

It supports smooth short-term motion and control. Global drift is corrected through map→odom so the odometry history does not suddenly jump.

Q2What is SLAM estimating that AMCL normally does not?
Model interview answer

SLAM estimates the map as well as the robot path, while AMCL estimates pose inside an already supplied static map.

Q3What should publish `map→odom` during AMCL navigation?
Model interview answer

The selected localization system, such as AMCL, should be the one authority; wheel odometry continues to publish odom→base_link.

Chapter references