Skip to content

nav2_kit API reference

Use Nav2 algorithm components from Python. nav2_kit.bringup_nav2() returns the C++ nav2_costmap_2d and nav2_navfn_planner namespaces. The kit adds NumPy grid conversion and planning helpers. Smac 2D and Regulated Pure Pursuit use in-process lifecycle nodes, initialized by their helpers (Patterns 6–9). Hybrid-A* is not exposed; see the binding report.

In a Pixi project configured with the channels in Getting Started, install pixi add ros-jazzy-nav2-kit numpy and run scripts with pixi run python your_script.py. See the kit overview for examples. Commands using pixi run -e nav2 require this repository checkout.

Usage requirements

  • Call nav2_kit.bringup_nav2() once; it returns (nav2_costmap_2d, nav2_navfn_planner). Idempotent (~70 ms, once). Call nav2_kit.warmup() during init to move the one-time first-use JIT off your first real call.
  • A NumPy grid is (H, W) = (rows=y, cols=x), indexed grid[y, x]; a costmap cell is (mx=x, my=y); NavFn path coords are (x, y) in cells. Same row-major layout as a nav_msgs/OccupancyGrid (data[y*W + x]), so a plan lines up with a published grid with no flip.
  • Costs are nav2_costmap_2d values, exposed as plain ints: nav2_kit.FREE_SPACE (0), LETHAL_OBSTACLE (254), INSCRIBED_INFLATED_OBSTACLE (253), MAX_NON_OBSTACLE (252), NO_INFORMATION (255).
  • unsigned char gotcha: costmap.getCost(mx, my) returns a 1-char Python str, not an int (cppyy maps unsigned char to str). Compare with ord(costmap.getCost(mx, my)). The bulk costmap_to_numpy path avoids this.

Pattern 1, plan on a synthetic grid (the minimal path)

Use for: global planning where you have (or synthesize) an occupancy grid.

import numpy as np
import nav2_kit
nav2_kit.bringup_nav2()

grid = np.zeros((200, 200), dtype=np.uint8)          # 0 = free
grid[:, 100] = nav2_kit.LETHAL_OBSTACLE              # a wall down the middle
grid[95:105, 100] = nav2_kit.FREE_SPACE             # ... with a doorway

costmap = nav2_kit.costmap_from_numpy(grid, resolution=0.05, origin=(0.0, 0.0))
path = nav2_kit.plan_navfn(costmap, start=(20, 100), goal=(180, 100))  # (mx,my) cells
if path is not None:
    print(path.shape, path[0], path[-1])             # (N,2) float32, start..goal
plan_navfn returns None when there is no plan. See grid-planning example.


Pattern 2, use Nav2's own classes directly (mirror)

Use for: anything the two helpers don't cover, the namespaces are the real Nav2.

cns, nns = nav2_kit.bringup_nav2()
cm = cns.Costmap2D(100, 100, 0.05, 0.0, 0.0, 0)      # Nav2's own ctor, verbatim
cm.setCost(10, 20, nav2_kit.LETHAL_OBSTACLE)
print(ord(cm.getCost(10, 20)))                       # 254  (note the ord())
nav = nns.NavFn(100, 100)                            # the planner algorithm, no node
Costmap2D and NavFn are C++ classes. Methods such as getSizeInCellsX, mapToWorld, worldToMap, and resizeMap use their C++ argument conventions.


Pattern 3, cells ↔ world coordinates

Use for: turning a cell-coordinate plan into metric poses (e.g. a nav_msgs/Path).

def cell_to_world(cx, cy, res=0.05, origin=(0.0, 0.0)):
    return origin[0] + (cx + 0.5) * res, origin[1] + (cy + 0.5) * res

path_xy = [cell_to_world(cx, cy) for cx, cy in path]  # path from plan_navfn
Costmap2D.mapToWorld(mx, my, wx, wy) does the same for integer cells (via C++ output references); the formula above also works for the subpixel path coordinates.


Pattern 4, publish map + plan to ROS 2 / rviz2 (via rclcppyy)

Use for: visualizing or feeding a real ROS 2 graph. Build C++ messages.

import cppyy
import rclcpp_kit
rclcpp = rclcpp_kit.bringup_rclcpp()
if not rclcpp.ok():
    rclcpp.init()
from nav_msgs.msg import Path                          # Python type registers topic
cppyy.include("nav_msgs/msg/path.hpp")
cppyy.include("geometry_msgs/msg/pose_stamped.hpp")

msg = cppyy.gbl.nav_msgs.msg.Path()                    # the C++ message; poses is a vector
msg.header.frame_id = "map"
for wx, wy in path_xy:
    pose = cppyy.gbl.geometry_msgs.msg.PoseStamped()
    pose.header.frame_id = "map"
    pose.pose.position.x, pose.pose.position.y = float(wx), float(wy)
    pose.pose.orientation.w = 1.0
    msg.poses.push_back(pose)

node = rclcpp.Node("planner")
node.create_publisher(Path, "plan", 1).publish(msg)
nav_msgs/OccupancyGrid works the same way (fill info + data); see the full showcase navigation example (map + plan + TwistStamped). ROS visualization needs ros-jazzy-nav-msgs and ros-jazzy-geometry-msgs.


Pattern 5, a follow loop (pure pursuit) (a lightweight Python controller)

Use for: driving along a plan when you want a tiny, dependency-free controller. (For Nav2's real controller, use Pattern 9, RPPController.) Classic pure pursuit steers by curvature toward a lookahead point:

import math
def pure_pursuit(pose, path_xy, idx, lookahead, max_v, max_w):
    x, y, th = pose
    while idx < len(path_xy) - 1 and math.hypot(path_xy[idx][0]-x, path_xy[idx][1]-y) < lookahead:
        idx += 1
    tx, ty = path_xy[idx]
    dist = math.hypot(tx-x, ty-y)
    alpha = math.atan2(math.sin(a := math.atan2(ty-y, tx-x)-th), math.cos(a))  # wrap
    kappa = 2.0 * math.sin(alpha) / max(dist, 1e-3)
    v = max_v
    return v, max(-max_w, min(max_w, v*kappa)), idx
d02_own_nav_stack.py wires this to a simulated diff-drive and publishes TwistStamped.


Pattern 6: construct a LifecycleNode

Use for: anything Nav2 that wants a LifecycleNode (Smac's collision checker, RPP's parent). It is a plain class you build in-process, no lifecycle server.

node = nav2_kit.lifecycle_node("my_lc", parameters={"use_sim_time": False})
# -> a real rclcpp_lifecycle::LifecycleNode, walked UNCONFIGURED->INACTIVE->ACTIVE
node.get_clock(); node.get_logger()                  # live; call any node method
inactive = nav2_kit.lifecycle_node("n2", transitions=("configure",))   # stop at INACTIVE
raw = nav2_kit.lifecycle_node("n3", transitions=())                    # leave UNCONFIGURED
Requires rclcpp (the kit brings it up + initializes it). Tracked for ordered teardown.

Pattern 7, Smac 2D planning (real AStarAlgorithm<Node2D>)

Use for: grid planning with Nav2's Smac 2D instead of NavFn. Same inputs/outputs as plan_navfn (cells in, (N,2) float32 start..goal out).

cm = nav2_kit.costmap_from_numpy(grid, resolution=0.05)     # a plain Costmap2D is fine
path = nav2_kit.smac_plan_2d(cm, start=(20, 50), goal=(80, 50))   # or pass a costmap_ros
if path is not None:
    print(path.shape, path[0], path[-1])                    # (N,2), start..goal
Returns None if unreachable. A LifecycleNode is created internally if you don't pass node=.... (Only 2D, Hybrid-A* is not surfaced.)

Pattern 8, a plugin-free Costmap2DROS (for RPP / a ROS costmap wrapper)

Use for: when a Nav2 class needs a Costmap2DROS (RPP does). No static map, no tf, no sensor layers, a blank master grid you fill from NumPy.

cm_ros = nav2_kit.costmap_ros("my_costmap", grid=grid, resolution=0.05)  # configured
cm_ros.getCostmap()                                  # the real master Costmap2D
costmap_ros(...) sizes itself to grid (or pass width_m/height_m). It is configured (INACTIVE) but not activated (no map-update thread), so your fill stays.

Pattern 9, the real RegulatedPurePursuit controller

Use for: following a plan with Nav2's actual RPP controller instead of Pattern 5.

cm_ros = nav2_kit.costmap_ros("costmap", grid=grid, resolution=0.05)
rpp = nav2_kit.RPPController(cm_ros, parameters={"desired_linear_vel": 0.6})
rpp.set_plan(path_xy)                                # world (x,y) waypoints, or a Path msg
for step in range(N):
    v, w = rpp.compute((x, y, theta))                # one real RPP step -> (v, w)
    ...                                              # integrate your kinematics
Notes: RPP is the real controller, it can raise cppyy.gbl.nav2_core.NoValidControl (its forward collision check; pass use_collision_detection=False if your plan is already collision-free) and it enters rotate-to-heading near the goal (pass use_rotate_to_heading=False + a tight goal_xy_tolerance to drive straight in). See d02_own_nav_stack.py --planner smac --controller rpp.


Gotchas (short version)

  • getCost returns a 1-char str, use ord(...). Kit constants (nav2_kit.LETHAL_OBSTACLE …) are plain ints for you.
  • plan_navfn needs cell coordinates (mx, my), returns (N,2) float32 cells (start→goal), or None if unreachable. Convert to world with Pattern 3.
  • NavFn call order matters: the kit does it for you, but if you drive NavFn yourself, setNavArr before setCostmap (it resets the cost array), then calcNavFnAstar and then calcPath (calcNavFnAstar only builds the potential field; it does not populate a path).
  • setCostmap(..., isROS=True) rescales ROS cost values into NavFn's internal band and adds an obstacle border, exactly like the Nav2 server.
  • Grid orientation: (H, W), grid[y, x]; matches OccupancyGrid row-major.
  • Smac 2D and the real RPP controller ARE surfaced via the in-process LifecycleNode key (Patterns 6–9); they need rclcpp (auto) + a costmap_ros where noted. Hybrid-A* is not, a flaky OMPL-under-Cling crash (REPORT §Probe D2).
  • Smac plans goal→start internally; smac_plan_2d reverses it to start..goal (matching plan_navfn), so both planners return the same convention.
  • warmup() once during init for the pure cores; warmup_lifecycle() for the LifecycleNode / Smac / RPP first-use JIT.

Export a Python DWB trajectory critic

This source-checkout path uses the installed DWB headers and libraries. Install ros-jazzy-dwb-core in the active environment. Use activated pixi run so compiler and library paths match.

from nav2_kit.python_critic import install_python_critic_plugin
install_python_critic_plugin("/absolute/path/to/overlay")

Prepend the returned overlay to AMENT_PREFIX_PATH before launching Nav2. Add a named critic to the DWB critics list and set its .class to nav2_kit_python::PythonCritic. Its parameters are python_module, python_class, absolute python_path, JSON-object string python_options, and optional lookahead_distance in metres. The normal DWB .scale controls its contribution. Preserve the other collision and goal critics.

The Python policy implements configure(options), prepare(yaw, path_heading, goal_distance), and score(vx, vy, wz, final_heading). prepare runs once per cycle; score runs per candidate reaching the critic. Return None to reject a candidate, or a finite nonnegative score. The bridge converts Python exceptions and invalid scores into DWB trajectory errors. Python uses the GIL. Keep callbacks short because they run in the controller scoring loop.

See the source navigation guide for configuration and launch ordering. Header and C++ implementation files are included in the kit package data.