Skip to content
←Back to Open Source

OPEN SOURCE DEEP DIVE

LiDAR LocalizationNDTGICPROS2

Prior-map LiDAR localization with guarded relocalization

A ROS 2 global LiDAR localizer for robots that already have a 3D prior map. This 1.10.0 refresh covers NDT and GICP registration, verified startup ordering, map-identity-bound saved poses, guarded G1-G3 relocalization, Nav2 TF contracts, the Go2 low-resource preset, and measured failure boundaries.

rsasaki0109/lidar_localization_ros2600PythonBSD-2-Clause19 min read

lidar_localization_ros2 addresses a deliberately narrow question: the robot already has a trusted prior point-cloud map, and each new LiDAR scan must answer “where am I on that map?” It does not build the map, control the robot, or replace wheel, leg, or LiDAR-inertial odometry. Instead, it connects scan matching, tracking-health checks, and guarded relocalization into a ROS 2 localization stack that can run standalone or supply the global pose required by Nav2.

This refresh is based on repository commit 6303352 on main, with package version 1.10.0 and the newer MID-360 low-resource preset that is still under the unreleased section of the changelog. The important change is not just faster matching. The project has turned two operational rules into executable behavior: do not invent a pose at startup, and do not reset from a single confident-looking match after tracking is lost.

Handheld MID-360 localization along a trajectory on a prior outdoor point-cloud map
A handheld MID-360 replay on the Koide outdoor dataset. The cyan trajectory follows localization against the prior map; the robot does not rebuild the map while it runs.

The boundary: localization, not mapping

A mobile robot usually has three layers of spatial state. The innermost layer is the calibrated transform from the robot body to each sensor, such as base_link to the LiDAR frame. The middle layer is continuous local odometry, commonly odom to base_link. The outer layer is the global map pose, commonly map to odom. This package consumes a prebuilt .pcd or .ply point cloud and a live PointCloud2 stream. It publishes the robot pose in that map, a path, diagnostic state, and TF.

The map must therefore exist before localization starts. It may come from the author’s lidar_slam_ros2 project or from another offline mapping system. New scans are not continuously fused into the map. Even a very good match does not alter the prior cloud. That separation lets the runtime concentrate on latency, observability, and rejection behavior, but it also means mapping drift, changed structure, temporary obstacles, and stale map revisions become localization concerns rather than being silently absorbed.

Area Package responsibility Outside the package
Map Load the prior cloud, build occupancy data for global search, switch maps at runtime LiDAR mapping, loop closure, map revision policy
Localization Scan registration, motion prediction, acceptance gates, health state, guarded relocalization Wheel or leg state estimation, chassis control, global planning
Frames Publish map -> base_link or map -> odom according to mode Duplicate robot TF publication; multiple owners of one transform cause a flickering tree
Navigation Provide a map-frame pose suitable for Nav2 Costmap generation, path planning, velocity execution

ROS 2 targets and registration backends

ROS 2 Jazzy is the primary target, Humble is supported, and Foxy remains best-effort even though it is end-of-life. All three build from main; the old long-lived foxy, humble, and jazzy branches have been removed, with their final commits retained as archive tags. Foxy still runs in CI and received compatibility work for its PCL version, point-cloud QoS, TF listener, and older rosbag2 interfaces. Passing CI does not make an end-of-life distribution the recommended choice for a production robot.

ndt_omp_ros2 is mandatory. The repository’s workspace bootstrap builds that dependency alongside the localizer. On Jazzy, ros-jazzy-small-gicp-vendor can optionally enable SMALL_GICP and SMALL_VGICP. Those backends are not automatic replacements for NDT: public-data experiments found SMALL_GICP strong on an easy window but unable to retain tracking through the longer Koide outdoor sequence. The default path therefore remains NDT-based.

mkdir -p ~/lidarloc_ws/src
cd ~/lidarloc_ws/src
git clone https://github.com/rsasaki0109/lidar_localization_ros2.git
cd lidar_localization_ros2
scripts/bootstrap_colcon_workspace.sh --build
source ~/lidarloc_ws/install/setup.bash

The documented workspace build takes roughly thirty minutes on eight cores. A first deployment should budget for that dependency build rather than treating the localizer as a tiny standalone node. The repository also provides a Docker image and smoke check for systems without a local ROS installation, but those checks validate the build and basic interfaces, not sensor extrinsics, clock behavior, or motion on a real robot.

From one scan to a map pose

The online loop has five practical stages: predict, prepare, register locally, gate the result, and either publish or bridge. The prediction starts from the last accepted pose. If the robot is moving, odometry, direct twist prediction, or IMU preintegration advances that pose toward the current scan. The scan is then range-cropped, voxel-filtered, and deskewed. Continuous-time deskew is enabled by default, but it leaves the cloud unchanged until point timing, IMU data, and motion information are trustworthy enough to support the operation.

The target is a local portion of the prior map around the predicted pose. The default NDT_OMP backend models local voxels probabilistically and iterates scan points against them; GICP or an optional small backend can be selected instead. A returned optimizer result is not accepted by itself. The node checks convergence, fitness score, inlier ratio, and the size of the correction relative to prediction. Only when the combined gates pass does the current pose become the next observation anchor.

LiDAR scan
  -> range crop / voxel filter / deskew
  -> predict from previous pose, odometry, twist, or IMU
  -> crop the map near the prediction and register
  -> combine convergence, score, inlier, and correction gates
  -> accepted: publish /pcl_pose, /path, and TF
  -> rejected with odometry: bridge from the trusted motion
  -> repeatedly rejected: raise /reinitialization_requested

Odometry has two distinct roles here. It can seed the scan with a better initial guess, and it can carry the pose through periods when scans do not match the map. The bridge is not a new map observation. Diagnostics distinguish normal tracking, weak scan quality, odometry-only operation, and a lost track. Poor odometry degrades both the seed and the bridge, so it cannot hide a wrong map, timestamp, or extrinsic transform.

Prior point-cloud map and localization trajectory displayed in RViz
RViz displays the surrounding point cloud and the trajectory produced by accepted localization poses.

Startup order and the saved-pose contract

The most common cold-start mistake is to treat the map origin as the robot’s current location. This package explicitly rejects an implicit (0,0,0) fallback. The startup manager follows a fixed order: an explicit initial pose first, a previously verified pose for the same map second, guarded map-wide or route-crop search third, and an operator’s 2D pose estimate last.

  1. Explicit initial pose: the caller owns correctness. The manager continues to watch diagnostics but does not publish the explicit value a second time.
  2. Verified saved pose: restoration is allowed only when the map contents match and the current scan converges from the stored pose under the score gate.
  3. Guarded global search: generate candidates over the full map or a route crop, score them in 3D, require agreement, then verify against fresh scans.
  4. Operator 2D pose estimate: if every automatic source is rejected, a human supplies a map-frame position and heading in RViz.

The saved pose is not tied to a filename. Its state file records the full SHA-256 digest and byte size of the .pcd or .ply, so renaming an unchanged map is safe while changing any map content invalidates the old pose. The write is atomic, preventing an interrupted process from leaving a partial JSON record. A pose is not saved as soon as it appears. Fresh diagnostics must show stable tracking and acceptable fitness for a configured number of consecutive samples. On the next start, the current scan must still converge from that stored pose. If the optional scorer cannot load, automatic restoration is skipped rather than trusting the old file blindly.

Guard Failure it prevents Fallback
Full map SHA-256 and size Restoring an old location after a same-named map was replaced Reject the saved pose and search globally
Atomic state write A crash or power loss leaving a truncated state file Keep the previous file or mark the record unusable
Fresh-scan verification The robot was moved while the previous session’s pose remained on disk Search again or request an operator pose
Consecutive stable diagnostics A single lucky scan becoming the basis of the next startup Do not update the saved pose

Global localization has three distinct stages

Without an initial pose, the project does not jump directly from a whole-map search to an accepted robot pose. G1 generates candidates offline or during startup by projecting the point-cloud map into a 2D occupancy grid and running a 2D branch-and-bound search over position and heading. By default, only points roughly 0.4 to 2.0 meters above the map ground are treated as obstacles, which prevents tree canopy and ceilings from dominating the projection. G2 exposes the search as a runtime service, removes redundant candidates with non-maximum suppression, rescoring with 3D NDT, and returns the ranked poses plus query, scan, and candidate timing. G3 is the guarded recovery supervisor. It watches the tracking-lost signal, calls G2, and publishes a new initial pose only after several independent safety conditions pass.

Stage Role Safety consequence
G1 Map-wide branch-and-bound over an occupancy grid built from the prior cloud A candidate is only a hypothesis and must not be published as a pose
G2 On-demand query service with ranked candidates and 3D registration scores Must check age, score, score lead, and whether 3D scoring actually ran
G3 Watches lost tracking, queries G2, applies a reset, and verifies recovery Debounce, bounded attempts, cooldowns, cross-checks, rejection of stale answers

The hard part is not finding a similar place in the map. It is deciding whether one place is actually unique. Long corridors, repeated stairs, rows of trees, and symmetric rooms can all produce strong 2D matches. 3D NDT reduces some aliases, but truly repeated geometry may remain ambiguous. Instead of lowering the threshold until the system reports success, the startup path requires results from distinct scan times to agree after motion compensation and then requires the localizer to demonstrate stable tracking over fresh diagnostics. Weak, stale, non-leading, inconsistent, and unverified candidates consume a bounded attempt budget. When that budget is exhausted, the system asks for an operator pose. It does not publish the map origin as a convenience fallback.

Global localization candidate, recovered path, and robot pose on a 2D occupancy map
A 2D view after recovery. The green curve is the recovered trajectory, the red arrow is the current pose, and the dark background is the occupancy grid derived from the prior point cloud.

Route cropping is a narrower alternative. During replay of the mapping session, a reference-trajectory CSV can restrict G2 candidates to places near the scan timestamp, which avoids many along-corridor aliases. It is appropriate for regression testing and controlled replays, not for a robot starting the next day in the same building because that live scan is outside the recorded time span. A practical deployment can use route cropping during the valid interval and fall back to map-wide search outside it.

Why G3 is guarded

Automatic reset after losing track is a high-risk action. A wrong pose that looks excellent locally can capture subsequent scans, producing a smooth trajectory in the wrong part of the map. G3 therefore does not forward the top G2 candidate directly to /initialpose. A request must persist long enough to reject a transient failure. Resets have a minimum separation. One continuous episode has a hard attempt limit. A candidate must clear the minimum score and lead the next candidate by a configured margin, and its age must remain inside the allowed window.

After the reset, the supervisor waits for fresh localization diagnostics to show low fitness and stable tracking for several samples. It then performs another query and compares that result with the localizer pose at the matching scan time. A mismatch beyond the threshold means the current “stable” state may simply be a stable alias, so the recovery episode continues. An /initialpose from an operator or another node is treated as authoritative. A reset not published by G3 ends the current episode, preventing the supervisor from reasoning about a trajectory that no longer exists.

Latency is also a safety issue. On a moving platform, G2 returns the pose associated with the scan it queried, not automatically the pose at the instant the answer arrives. Applying a multi-second-old answer to the current scan can turn a correct map location into an incorrect live pose. The service reports candidate age, and some configurations can replay an older reset through retained scans until it catches up with the newest scan. That replay remains opt-in because it needs compute headroom and strict abort conditions; it is not a universally safe default.

ROS interfaces, TF ownership, and Nav2

The default frame names are map, odom, and base_link. Standalone mode publishes map -> base_link, which is simple for replay and localization-only nodes. Nav2 mode publishes map -> odom and requires the robot state estimator to publish odom -> base_link. This is the conventional mobile-robot tree: odometry preserves smooth local motion, while prior-map localization corrects global drift.

Nav2 mode:
map -> odom       published by lidar_localization_ros2
odom -> base_link published by wheel, leg, or LiDAR-inertial odometry
base_link -> sensors published by the robot's calibrated sensor TF

Standalone mode:
map -> base_link  published by lidar_localization_ros2

use_odom means the localizer consumes odometry messages to predict motion. enable_map_odom_tf controls whether it composes and publishes map -> odom. They are not the same switch. If another global estimator already owns map -> odom, set publish_tf to false and consume /pcl_pose. Conversely, Nav2 mode without an external odom -> base_link has no complete TF chain, so the localizer cannot publish a valid map -> odom.

Every static LiDAR and IMU transform must have exactly one publisher. Quickstart can publish an identity transform when two frames have no existing TF connection, and it prints a hint when doing so. That identity is valid only when the sensor frame physically coincides with the robot base. A real height, pitch, or lateral offset must use the measured extrinsic and disable the temporary publisher; otherwise a systematic scan offset will look like localization error.

Common inputs are /cloud, /initialpose, /odom, /imu, and /map_switch. Outputs include /pcl_pose, /path, /alignment_status, and /reinitialization_requested. Quickstart also provides a human-readable status line and RViz marker. /map_switch replaces the point-cloud map at runtime while retaining the current pose; if the new map has a different origin, an initial pose should follow immediately. The global localization node continues to hold the map it loaded at startup, so callers need an explicit policy when map switching and global relocalization coexist.

The twist EKF is gone; direct twist prediction is not

Version 1.9.0 removed ten old features that no maintained preset enabled, including the twist EKF. This does not mean the package stopped using velocity information. Direct twist prediction remains available, and /odom or TwistWithCovarianceStamped can still advance the pose before scan registration. What disappeared is the extra filtered twist state. A legacy YAML that sets use_twist_ekf: true now fails configuration with a message naming the switch instead of silently behaving differently. The corresponding old thresholds are no longer declared.

The cleanup leaves one primary path for twist prediction and keeps IMU preintegration and its correction guards separate. Existing deployments need no YAML change if they did not enable a removed feature. New deployments get a clearer failure mode: unsupported configuration appears at startup rather than as a difficult-to-observe behavioral regression.

The low-resource MID-360 preset

The standard legged MID-360 preset uses four NDT threads, a 0.25-meter scan voxel, a 0.8 to 60-meter range crop, TF publication at 20 Hz, and IMU preintegration. It intentionally loads the whole map as the registration target instead of frequently rebuilding an 80-meter local crop; recropping a dense map can stall output for about two seconds.

The new low-resource preset targets an Orin Nano or Orin NX that also runs perception. It increases the scan voxel to 0.5 meters, uses two NDT threads and at most 15 iterations, disables the 20 Hz pose timer, and seeds every scan from odometry TF. It also scales MID-360 acceleration from g into meters per second squared. The central constraint is that the low-resource preset needs odometry.

Setting Standard legged preset Low resource Reason
Scan voxel0.25 m0.5 mLarge reduction in points per scan
NDT threads and iterations4 threads, 30 iterations2 threads, 15 iterationsLower CPU peaks
Odometry prediction and lost-scan bridgeOff by defaultOnThe coarse scan needs a continuous seed
Pose publication20 Hz timerAfter each aligned scanOdometry maintains motion between scans
Acceleration scale1.09.80665The MID-360 driver reports acceleration in g

The preset is not unconditionally “faster and therefore better.” Without odometry, the 0.5-meter scan locked onto the wrong stair level on a Go2 sequence. Even a 0.25-meter variant that only reduced threads and iterations lost the robot by more than ten meters. A deployment without a reliable odom -> base_link source should keep the standard preset instead of switching solely to save CPU.

Measured behavior

The public benchmarks begin every run without a saved or explicit pose. Error is measured in the map frame without aligning the estimated trajectory to ground truth. That detail matters: a run initialized at the wrong but self-consistent place can look excellent after alignment, while map-frame scoring exposes the full global error.

Scenario Condition Result
Unitree Go2, JEPLO Long_Stairs Upside-down MID-360, no initial pose, replay on a map built from the same recording Search began at 6.8 s and the first pose arrived at 11.3 s; two queries returned 32 candidates each, with the correct place ranked first; first-pose error was 0.02 m
Unitree Go2, Long_Stairs tracking Only the motion-capture room was scored; one repeat Median, p95, and maximum horizontal error were 0.02, 0.04, and 0.07 m
Koide outdoor_hard_02b Version 1.10.0, two complete online replays Map-frame RMSE 0.242 m; 0.170 to 0.171 m when measured only on the map; 100% diagnostic coverage
Koide alignment cost Four virtual CPUs, full replay 16 ms median alignment and 39 to 41 ms at p95
Boreas, first 120 s Release-check configuration 0.132 m RMSE, or 0.127 m with IMU preintegration; every scan accepted in the release check

The resource-constrained tests show why the preset’s dependencies matter. On Go2 EIL_Stairs, the standard preset produced 0.077 m RMSE and the low-resource preset 0.067 m; the latter averaged 0.20 to 0.21 CPU cores and peaked around 121 to 132 MB resident memory. Across Koide replays, the standard preset measured 0.245 to 0.25 m and the low-resource preset 0.227 to 0.228 m, while average CPU fell from about 0.70 cores to 0.45 to 0.50. The Go2 result depends on continuous odometry seeds, and memory is governed mainly by map size rather than thread count.

A separate 1.9.0 Boreas soak test peaked at 576 MiB resident memory over one hour. The authors do not present that as an equivalent 1.10.0 result because the hour-long soak was not rerun on the newer release. Keeping version and host conditions attached to each number is more useful than collapsing them into a single headline.

Where it fits, and where it does not

The package fits deployments with a stable prior map, repeatable geometry, a continuous odometry source, and a need for global pose in ROS 2 and Nav2. Warehouse aisles, fixed stairs, recurring inspection routes, mixed indoor-outdoor sites, and handheld MID-360 replays are direct targets. It also works as a research baseline because startup order, global candidates, safety gates, TF modes, and resource use are documented and backed by regression data.

It is not a map-maintenance system, and it cannot repair missing time synchronization, bad extrinsics, or an unusable odometry source. Large structural changes reduce correspondence with the prior map. Long corridors and repeated geometry can remain multi-modal. High speed makes global-query answers age quickly. If the map itself contains inconsistent floors, ramps, or loop-closure drift, the localizer can only search for the best match inside that flawed representation.

Explicit limits

  • There is no long multi-hour validation and no physical Jetson, MID-360, or legged-robot hardware validation. The resource measurements come from x86 virtual CPUs and public-data replay; an Orin’s ARM cores should be budgeted at roughly two to three times the per-core cost until measured.
  • The successful Go2 Long_Stairs global result used a map built from the same recording and was repeated once. Motion capture also covers only the room, not the full stairs and outdoor extension.
  • In six later wide-map replays, one Outdoor2 run remained ambiguous and requested a manual pose. That failure is retained in the documented result rather than removed from the sample.
  • Tracking can be lost, and recovery can still fail. G3 limits unsafe resets; it does not guarantee recovery from every kidnapping or dynamic scene.
  • Fast global settings reduced a Boreas query from about 19 seconds to about 2 seconds, but the answer could still be tens of meters behind a moving vehicle. Closed-loop recovery failed without replaying the stale reset through retained scans.
  • In one Koide outdoor_hard_02b run, RKO-LIO briefly dropped odometry because of too few ICP keypoints. The supervisor then accepted one answer without odometry confirmation and reset 128 meters away. The dropout waiver remains a real failure mode.
  • SMALL_GICP and SMALL_VGICP are optional backends, not universally validated replacements. Teams should repeat tests on their own map, motion profile, and sensor before changing the default.

A practical start

With a point-cloud map and correct robot, LiDAR, and odometry transforms already available, the shortest path is to start the sensor and odometry, then point quickstart.py at the map. The script inspects live topics, the clock, and TF, writes a parameter file, launches the localizer, and prints the appropriate bringup checks. On the first run it attempts guarded global initialization and asks for a 2D pose estimate only when no safe automatic result exists.

ros2 run lidar_localization_ros2 quickstart.py \
  --map /absolute/path/to/map.pcd

ros2 run lidar_localization_ros2 check_lidar_localization_bringup.py \
  --profile standalone

After launch, watch /alignment_status and the quickstart status line rather than judging success only from a moving arrow in RViz. Startup should move through waiting for a scan, searching, confirming a candidate, checking later scans, and localized. Online operation should explicitly report tracking, weak matching, odometry-only support, or loss. Persistent fitness failures usually point back to the initial pose, map frame, cloud frame, LiDAR extrinsic, timestamps, or units. Lowering the threshold is more likely to hide one of those faults than to fix it.

Ground-truth and NDT plus IMU trajectories during a Koide kidnapped-sensor replay
A Koide kidnapped-sensor replay. The dashed blue line is ground truth and the green line is NDT with IMU preintegration. A large error while the sensor is carried is expected; the important question is whether recovery later returns to a verified place.

The project’s strongest engineering contribution is not a single registration score. It is the chain of rejection points around the pose: map identity, saved-pose verification, candidate scoring, cross-scan agreement, post-reset evidence, and explicit TF ownership. A deployment that preserves those boundaries will be easier to diagnose than one that asks a lower threshold to make every run appear successful.

As an Amazon Associate, we earn from qualifying purchases.