Tutorials

Browser demo of nav2-coverage-planner-compare, showing a Nav2-style costmap, a planned path, and planner metrics. Simulation only.
Tutorial

How I built a Nav2-style planner comparison: A*, Dijkstra, Lazy Theta*, RRT*, and boustrophedon coverage

A portfolio, simulation-only walkthrough of nav2-coverage-planner-compare: how A*, Dijkstra, Lazy Theta*, RRT*, and boustrophedon coverage work on a Nav2-style costmap, how to build the C++17 core, Python bindings, browser demo, and ROS 2 Humble wrapper, and what the golden fixtures actually report.

Arpan Bom15 min read
ShareXLinkedIn

This is a simulation only

Before anything else: this is a portfolio demo, not a production Nav2 plugin. Everything here runs against static occupancy grids with a single differential-drive robot. There is no Gazebo, no SLAM, no AMCL, and nothing has touched real hardware. I built it to show how a handful of classic planners behave on the same costmap, with deterministic fixtures backing every number I quote below. Treat every result as "this is what the golden fixture says," not as a performance claim about a real robot.

Try the live demo

The fastest way to see this working is the browser demo: https://applycoding.github.io/nav2-coverage-planner-compare/

It runs the TypeScript port of the planners in a Web Worker, against the same maps and fixtures as the C++ core.

Browser demo of nav2-coverage-planner-compare, showing a Nav2-style costmap, a planned path, and planner metrics. Simulation only.

Image: the GitHub Pages demo, simulation only. applycoding.com.

What the project is

nav2-coverage-planner-compare (repo: applycoding/nav2-coverage-planner-compare, commit f9bde19) is a small comparison bench for five planning strategies you'd find discussed around Nav2: A*, Dijkstra, Lazy Theta*, RRT*, and boustrophedon (lawn-mower) coverage. The stack is:

  • A C++17 core with the costmap, collision checking, and the planners themselves.
  • pybind11 bindings (ncp_core) with a Python test suite that checks parity against golden fixtures.
  • A TypeScript port for the browser, checked against the same fixtures so the demo and the core agree.
  • An optional ROS 2 Humble wrapper exposing the planners as services.
  • GitHub Actions CI running the core tests, the Python parity tests, and (on PRs labeled ci-ros) a ROS smoke test.

The architecture, straight from the README:

GridMap (PGM/YAML) -> Costmap -> Collision -> GlobalPlanner / CoveragePlanner -> Metrics
                                      -> pybind11 (ncp_core) | ROS 2 srv | TypeScript worker

The planners all read from that same costmap, so a comparison means holding the map and the costmap parameters fixed and swapping only the planner.

How the costmap works

The costmap loads a PGM image plus a YAML sidecar, applies an unknown-cell policy (Lethal or Free), and then inflates obstacles. Occupancy itself is stored as free, occupied, or unknown. The costmap then assigns cost values, with hard lethal at 254, inscribed at 253, and unknown at 255. This is a simplified teaching model of a Nav2-style costmap, not a drop-in map_server loader: the PGM path in cpp/src/grid_map.cpp reads pixel probabilities directly and does not reverse image rows the way some ROS map loaders do.

There's a detail worth being precise about, because the code and the planning docs disagree slightly. PLAN.md defines inflation_radius_m as robot_radius_m + extra_margin_m. In the actual code, Costmap::build_inflation_and_costs uses params_.inflation_radius_m directly, and extra_margin_m exists on CostmapParams but is never read inside costmap.cpp. In practice the v1 fixtures just set inflation_radius_m explicitly, usually equal to robot_radius_m, so this doesn't bite you day to day, but if you're reading the source expecting the margin to be added automatically, it isn't.

Soft costs only show up when cost_decay > 0. Most of the golden fixtures set cost_decay to 0, which means those maps are effectively hard lethal versus free, no gradient.

Collision checking (point_center_free / segment_center_free) tests the path against hard-blocked cells using the robot's center point along the segment. There's no separate footprint sweep, so collision is checked once per segment, not double-counted against both endpoints and the body.

What each planner does, and when to pick it

A* and Dijkstra

Both share one implementation, plan_graph_search in cpp/src/planners/graph_search.cpp. A* adds an octile heuristic; Dijkstra doesn't, it's controlled by a single use_astar flag. The search is 8-connected, but diagonal corner-cutting is explicitly forbidden (diagonal_legal checks both orthogonal neighbors before allowing a diagonal step). Step cost is:

length * (1 + w_cost * cmax / 252)

with diagonal length res * sqrt(2). Failure reasons you'll see in results include out_of_bounds, start_in_obstacle, goal_in_obstacle, and unreachable.

Pick A* when you want a cost-aware shortest path on the grid and you want it fast and deterministic, which is the common case for these maps. Pick Dijkstra as a baseline, or when you specifically want uniform exploration without a heuristic biasing the search. On the open map golden, Dijkstra matches A* exactly: same length and the same 11-point path.

Lazy Theta*

cpp/src/planners/lazy_theta_star.cpp is labeled in the source as "Lazy Theta*: deferred line-of-sight (Nash, Koenig, Likhachev, AAAI 2010)." The original paper is the idea reference. In this implementation, line-of-sight is used to repair a node's parent when that node is expanded, and line_of_sight is also called when a neighbor is updated, so any-angle shortcuts can still replace a grid zigzag when the way is clear.

Pick Lazy Theta* when you want fewer waypoints and a shorter, more natural path whenever line-of-sight is actually clear. The open map golden shows this well: Lazy Theta* returns just two points, start and goal, the straight line, because there's nothing blocking it.

RRT*

cpp/src/planners/rrt_star.cpp uses a shared xorshift32 RNG, the same generator the TypeScript port uses, so seeded runs are reproducible across both implementations. Constants baked into the source: step_size 0.15, rewire_radius 0.4, goal_bias 0.1. It supports two termination modes: IterationOnly (used by the fixtures and goldens for determinism) and Deadline (rrt_max_time_ms, wall-clock budget).

Pick RRT* when you want a planner that can work under a time or iteration budget, or when you need a seeded, reproducible tree for testing. One thing I want to be explicit about: the rrt_iter golden plans to a different goal than the A*/Dijkstra/Lazy Theta* goldens on the open map, (1.8, 1.8) instead of (1.5, 1.0). Don't compare RRT*'s path length against the others as if they solved the same problem, because they didn't.

Boustrophedon coverage with stripe linking

cpp/src/coverage/coverage_planner.cpp generates axis-aligned lawn-mower stripes across the region's bounding box. Stripe spacing is:

stripe_spacing = 2 * robot_r - overlap_m

The request is invalid (invalid_request) if robot_r <= 0, overlap_m < 0, or overlap_m >= 2 * robot_r. Stripes get connected by whichever global planner you choose as the linker (A* in the hole golden). Partial plans don't teleport: if a link between stripes fails, the path simply stops there, and the reason is set to partial_coverage. Success is then decided by whether coverage_ratio_reachable still meets coverage_success_threshold. That means a partial plan can return success true with reason partial_coverage if the reachable coverage it did produce is already high enough.

Pick coverage when the job is to sweep reachable free space rather than reach a single goal, lawn mowing, inspection sweeps, that kind of task. This is not a production agricultural or indoor coverage stack, it's a demo of the stripe-and-link idea.

Build the C++ core and run the tests

From the repo root, the README's build sequence:

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=g++
cmake --build build -j
ctest --test-dir build --output-on-failure

CI builds this with python3.12 and g++-13. The repo's requires-python is >= 3.12.

Golden expected.json files are produced by ncp_dump_fixture. That tool overwrites expected.json and map.json for the fixture you pass it, so use it to regenerate goldens, not as a casual inspector. To read a committed result, open the file directly, for example fixtures/maps/open/expected.json. To regenerate the open map goldens after a planner change:

build/ncp_dump_fixture fixtures/maps/open

Plan a path from Python

Once the core is built, the pybind11 module ncp_core lands in build/python. Run the parity and bench tests with:

PYTHONPATH=build/python python3 -m pytest -q python/tests

(Optionally pip install -r python/requirements-dev.txt first, which pins pytest 9.2.0.)

Here's a short script in the spirit of python/tests/test_golden_fixtures.py, using the open map fixture:

import ncp_core

grid = ncp_core.load_grid(
    "fixtures/maps/open/map.pgm",
    "fixtures/maps/open/map.yaml",
)

params = ncp_core.CostmapParams()
params.robot_radius_m = 0.15
params.inflation_radius_m = 0.15
params.cost_decay = 0
params.unknown_policy = ncp_core.UnknownPolicy.Lethal

cmap = ncp_core.make_costmap(grid, params)

req = ncp_core.PlanRequest()
req.planner = ncp_core.PlannerId.AStar
req.start = ncp_core.WorldPoint()
req.start.x, req.start.y = 0.5, 0.5
req.goal = ncp_core.WorldPoint()
req.goal.x, req.goal.y = 1.5, 1.0

res = ncp_core.plan_global(cmap, req)
print(res.success, res.reason)
print(res.metrics.length_m)
print(res.metrics.objective_cost)

The golden fixture expects res.metrics.length_m to come out to 1.2071067811865475 on this map, start, and goal.

Coverage works the same way with CoverageRequest. For the hole fixture:

grid = ncp_core.load_grid(
    "fixtures/maps/hole/map.pgm",
    "fixtures/maps/hole/map.yaml",
)

params = ncp_core.CostmapParams()
params.robot_radius_m = 0.12
params.inflation_radius_m = 0.12
params.cost_decay = 0
cmap = ncp_core.make_costmap(grid, params)

cov = ncp_core.CoverageRequest()
cov.start = ncp_core.WorldPoint()
cov.start.x, cov.start.y = 0.5, 0.5
cov.linker = ncp_core.PlannerId.AStar
cov.overlap_m = 0.02
cov.coverage_success_threshold = 0.95

res = ncp_core.plan_coverage(cmap, cov)
print(res.success, res.metrics.coverage_ratio_reachable)

On this fixture the golden expects success, coverage_ratio_reachable of 1.0, and a path length of 27.033802338473798 m.

Run the browser demo locally

The web port lives in web/:

cd web && npm ci && npm test && npm run build && npm run preview

CI and web/package.json's preview script run on Node 26.13.0, with vite preview --port 4173 --host 127.0.0.1. Once it's running, open /nav2-coverage-planner-compare/ on port 4173.

The UI (web/src/app.ts) gives you a map selector (office, open, hole, narrow_pass, unreachable, unknown_row, tiny), a planner selector (astar, dijkstra, lazy_theta, rrt_star), a Plan button, a Coverage button, and a "Compare all planners" checkbox. Compare mode is for the global planners, it isn't wired to coverage. Coverage in the UI uses a fixed coverageOverlap of 0.02. Planning itself runs off the main thread in a Web Worker, so the UI stays responsive even on the busier maps. Metrics shown include length, objective cost, compute_ms, clearance, and a coverage percentage when applicable.

One important difference from the goldens: on the open map, the browser always plans from (0.5, 0.5) to (1.5, 1.0), including for RRT*. The rrt_iter golden uses a different goal, (1.8, 1.8), with seed 42 and 3000 iterations. If you click Plan with RRT* selected on the open map in the demo, you are not reproducing that golden.

Optional: the ROS 2 Humble wrapper

The ncp_planner ROS package is optional and targets ROS 2 Humble specifically; upstream support for Humble continues through May 2027, a Jazzy port is future work and isn't built in v1. The ROS workflow runs on pushes to main and on pull requests labeled ci-ros, against ros:humble-ros-base@sha256:a3f4de78e42cca693a543ece5798aedcf1cae0171fe71c334a047332cc72ef93.

From the repository root (not inside web/), you can build it against a local install prefix (adapting the CI steps):

cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DNCP_BUILD_PYTHON=OFF \
  -DNCP_BUILD_TESTS=OFF -DNCP_BUILD_ROS=OFF -DCMAKE_INSTALL_PREFIX="$PWD/install/ncp"
cmake --build build -j
cmake --install build --prefix "$PWD/install/ncp"

source /opt/ros/humble/setup.bash
export CMAKE_PREFIX_PATH="$PWD/install/ncp:$CMAKE_PREFIX_PATH"
colcon build --paths ros2/ncp_planner --cmake-args -DCMAKE_PREFIX_PATH="$PWD/install/ncp"
source install/setup.bash

Then either:

ros2 launch ncp_planner planner.launch.py

which starts ncp_planner_node with params robot_radius_m 0.15 and inflation_radius_m 0.15, or run the node directly, which is what the CI smoke test does:

ros2 run ncp_planner ncp_planner_node

The node (ros2/ncp_planner/src/planner_node.cpp) subscribes to /map (nav_msgs/OccupancyGrid, transient local, reliable), reading occupancy as 0 free, greater than 50 occupied, and anything else unknown. It exposes two services, plan_global and plan_coverage, and publishes successful plans on /plan (nav_msgs/Path). It also advertises /markers (visualization_msgs/MarkerArray), but the v1 node never publishes markers on that topic. If no map has arrived yet, both services return reason no_map.

PlanGlobal.srv takes start/goal as geometry_msgs/PoseStamped, a planner_id string, plus rrt_seed and rrt_max_iterations for RRT* requests, and returns path, success, reason, length_m, objective_cost. The valid planner_id strings, from cpp/src/types.cpp, are "dijkstra", "rrt_star", "lazy_theta", anything else (including "astar") falls through to A*.

PlanCoverage.srv takes start, linker_id, overlap_m, coverage_success_threshold, and returns path, success, reason, coverage_ratio_reachable, length_m.

CI's smoke test starts the node, then runs:

python3 ros2/ncp_planner/scripts/smoke_plan_global.py

which publishes a 20x20 open OccupancyGrid at 0.1 m resolution on /map, calls plan_global with start (0.5, 0.5), goal (1.5, 1.0), planner_id "astar", rrt_seed 1, rrt_max_iterations 1000, and asserts success with a non-empty path.

Results from the golden fixtures

These numbers come from the committed expected.json files under fixtures/maps/*, at commit f9bde19, not from a fresh timed run on any particular machine.

Open map (20x20, 0.1 m resolution, robot_radius_m 0.15, inflation_radius_m 0.15, cost_decay 0, w_cost 1), start (0.5, 0.5), goal (1.5, 1.0) unless noted:

Case Planner Success Length (m) Points
astar_to_goal A* true 1.2071 11
dijkstra_to_goal Dijkstra true 1.2071 11
lazy_theta Lazy Theta* true 1.1180 2
rrt_iter RRT* (goal 1.8, 1.8) true 1.8386 11

Straight-line distance from (0.5, 0.5) to (1.5, 1.0) is 1.1180 m, which is exactly what Lazy Theta* returns as a direct two-point path. A* and Dijkstra pay a small zigzag penalty on the 8-connected grid to get 1.2071 m. The RRT* row plans to a different goal, (1.8, 1.8), whose straight-line distance is about 1.8385 m, so its 1.8386 m result is close to optimal for its own goal, not a worse result relative to A*'s goal. clearance_m is null (NaN in code) for all four of these open-map goldens.

Corridor maps: office, narrow_pass, narrow_block, and office_large_inflation all share the exact same 30x20, 0.1 m occupancy grid. The only thing that changes between them is robot radius and inflation, not the floor plan.

  • office and narrow_pass (robot_radius_m 0.15, inflation_radius_m 0.15), A* from (0.5, 1.05) to (2.5, 1.05): success, length 2.7548 m, objective cost 2.7456, clearance 0.4243 m, 21 path points.
  • office_large_inflation and narrow_block (robot_radius_m 0.22, inflation_radius_m 0.22), same start/goal: success false, reason unreachable, empty path.

That's the teaching point of this pair: the floor plan never changed, only the robot's inflated footprint did, and that alone was enough to close a corridor that a smaller robot could pass through cleanly.

Hole / coverage (25x25, 0.1 m, robot_radius_m 0.12, inflation_radius_m 0.12): coverage_hole, start (0.5, 0.5), linker A*, overlap_m 0.02, coverage_success_threshold 0.95: success, length 27.0338 m, coverage_ratio_reachable 1.0, coverage_ratio_total 1.0, clearance 0.0100 m, 162 path points.

Unknown row (20x3, robot_radius_m 0.08, same start/goal (0.5, 0.05) to (1.5, 0.05)): lethal_unknown fails with start_in_obstacle; free_unknown succeeds with length 1.0 m. Same geometry, different unknown-cell policy, different outcome.

Unreachable map (20x20, robot_radius_m 0.1): astar_unreachable (goal (1.5, 1.0)) fails with unreachable; goal_in_obstacle (goal (1.05, 1.0)) fails with goal_in_obstacle; rrt_timeout (same start/goal as astar_unreachable, rrt_seed 7, rrt_max_iterations 500) fails with timeout after exploring 228 vertices.

Tiny map: start equals goal at (0.05, 0.05), succeeds trivially with length 0 and a single path point.

Timing from the recorded bench

The README includes one recorded bench run, not a claim about this tutorial's machine:

Platform Load map (ms) A* search (ms)
Linux/x86_64, py3.12, g++ 13 0.015 0.108

Those labels are from the README. In python/tests/test_bench.py, load_ms actually times make_costmap (the PGM is loaded before the timer starts), and search_ms times plan_global. You can rerun the test with:

PYTHONPATH=build/python pytest python/tests/test_bench.py -s

The test prints a small table, then calls capsys.readouterr(), which consumes that output. If you want to see the numbers on your machine, temporarily print the rows again after that call, or comment the capsys.readouterr() line out.

compute_ms is filled in on ordinary plan results and shown in the browser demo, but it is never stored in the golden expected.json files. Those files only capture deterministic path and metric values.

License and references

The project is Apache-2.0, see LICENSE and NOTICE in the repo. All planner code here was written for this demo; none of it is a vendored fork of anything.

A few projects I looked to for ideas, not code, credited in NOTICE / REFERENCES.md:

I also looked briefly at ethz-asl/polygon_coverage_planning (GPL-3.0) and nav2_amcl (LGPL-2.1-or-later) for ideas only, no code was derived from either, which matters given the license difference from this repo's Apache-2.0 terms.

How this was verified

I ran the standard portfolio-tutorial checks against commit f9bde19 on main.

  • The GitHub repo is not a fork. gh api repos/applycoding/nav2-coverage-planner-compare reports "fork": false.
  • All 12 commits have author and committer Arpan Bom (applycoding@gmail.com).
  • A search of the tree found no third_party, vendor, or external directories, and no "ported from", "adapted from", or "copied from" markers in the source. NOTICE states that no third-party planner source is vendored in this repository.
  • This is an original implementation of well-known methods (A*, Dijkstra, Lazy Theta*, RRT*, and boustrophedon coverage), inspired by the projects credited below. I did not invent these algorithms.
  • Idea references, with licenses, credited in NOTICE (conceptual only, no source copied): AtsushiSakai/PythonRobotics (MIT), ros-navigation/navigation2 including NavFn, Smac 2D, Theta*, and costmap_2d (Apache-2.0 / BSD-3-Clause), Fields2Cover/Fields2Cover (BSD-3-Clause), open-navigation/opennav_coverage (Apache-2.0), nobleo/full_coverage_path_planner (Apache-2.0), anvaka/ngraph.path and ngraph.path.demo (MIT), bgrins/javascript-astar (MIT), and motion-planning/rrt-algorithms (MIT). I also looked at ethz-asl/polygon_coverage_planning (GPL-3.0) and nav2_amcl (LGPL-2.1-or-later) as idea-only references; no code was derived from either.
  • Build dependencies, not relicensed, as listed in NOTICE and the build files: CMake FetchContent pulls GoogleTest (BSD-3-Clause, tests only), nlohmann/json (MIT), yaml-cpp (MIT), and pybind11 (BSD-3-Clause, Python bindings). Python tests use pytest 9.2.0 (MIT). The web demo's direct devDependencies are Vite (MIT), Vitest (MIT), @types/node (MIT), TypeScript (Apache-2.0), and Playwright Test (Apache-2.0).
  • The repo license is Apache-2.0.
  • Commands, paths, APIs, and the golden numbers in this tutorial were checked against the repo at f9bde19. Relative to e645e8c, the NOTICE file was completed and planning-doc wording was cleaned up; the fixtures and planner code are unchanged.
  • This project is simulation only and has not been tested on real hardware.

Limits

This is simulation only, on static maps, with a single robot. It's not a Nav2 plugin and it hasn't been tested on hardware. The goldens capture deterministic path and metric values, not wall-clock performance. The timing numbers above come from one recorded bench run, not a guarantee. The browser demo is a separate TypeScript implementation, checked against the same fixtures as the C++ core, but it is still a port, not the same binary.

How I built a Nav2-style planner comparison: A*, Dijkstra, Lazy Theta*, RRT*, and boustrophedon coverage | Apply Coding