Skip to main content

Nav2 Path Planning for Humanoid Locomotion

Overview​

Navigation2 (Nav2) is the navigation stack for ROS 2 that enables robots to autonomously navigate through environments. For humanoid robots, path planning requires special considerations due to their bipedal locomotion, balance requirements, and unique kinematics. This chapter explores how to adapt Nav2 for humanoid robot navigation, including specialized costmaps, path planners, and locomotion controllers.

Learning Objectives​

After completing this chapter, you will be able to:

  1. Configure Nav2 for humanoid robot navigation requirements
  2. Implement terrain-aware path planning for bipedal locomotion
  3. Customize costmaps for humanoid-specific obstacles
  4. Integrate balance and stability constraints into navigation
  5. Implement dynamic path replanning for humanoid locomotion
  6. Validate navigation performance on humanoid robots

Introduction to Navigation2 for Humanoid Robots​

Differences from Wheeled Navigation​

Humanoid robot navigation differs significantly from wheeled robot navigation:

  1. Terrain Requirements: Humanoids need traversable ground, not just obstacle-free paths
  2. Balance Constraints: Paths must consider the robot's center of mass and stability
  3. Step Planning: Precise footstep planning for bipedal locomotion
  4. Dynamic Obstacles: Need to handle moving obstacles differently due to slower acceleration/deceleration
  5. Safety Margins: Larger safety margins needed for fall prevention

The Nav2 stack includes:

  • Navigation System: Coordinates navigation tasks
  • Planner Server: Global path planning
  • Controller Server: Local path following
  • Recovery Server: Behavior when stuck
  • Lifecycle Manager: Manages node states
  • Costmap 2D: Maps for planning and control

Configuring Nav2 for Humanoid Robots​

Setting Up the Navigation Stack​

The navigation stack configuration for humanoid robots requires special parameters:

# humanoid_navigation_params.yaml
amcl:
ros__parameters:
use_sim_time: False
alpha1: 0.2
alpha2: 0.2
alpha3: 0.2
alpha4: 0.2
alpha5: 0.2
base_frame_id: "base_footprint"
beam_skip_distance: 0.5
beam_skip_error_threshold: 0.9
beam_skip_threshold: 0.3
do_beamskip: false
global_frame_id: "map"
lambda_short: 0.1
laser_likelihood_max_dist: 2.0
laser_max_range: 100.0
laser_min_range: -1.0
laser_model_type: "likelihood_field"
max_beams: 60
max_particles: 2000
min_particles: 500
odom_frame_id: "odom"
pf_err: 0.05
pf_z: 0.99
recovery_alpha_fast: 0.0
recovery_alpha_slow: 0.0
resample_interval: 1
robot_model_type: "nav2_amcl::DifferentialMotionModel"
save_pose_rate: 0.5
sigma_hit: 0.2
tf_broadcast: true
transform_tolerance: 1.0
update_min_a: 0.2
update_min_d: 0.25
z_hit: 0.5
z_max: 0.05
z_rand: 0.5
z_short: 0.05

amcl_map_client:
ros__parameters:
use_sim_time: False

amcl_rclcpp_node:
ros__parameters:
use_sim_time: False

bt_navigator:
ros__parameters:
use_sim_time: False
enable_groot_monitoring: True
groot_zmq_publisher_port: 1666
groot_zmq_server_port: 1667
default_bt_xml_filename: "navigate_w_replanning_and_recovery.xml"
plugin_lib_names:
- nav2_compute_path_to_pose_action_bt_node
- nav2_follow_path_action_bt_node
- nav2_back_up_action_bt_node
- nav2_spin_action_bt_node
- nav2_wait_action_bt_node
- nav2_clear_costmap_service_bt_node
- nav2_is_stuck_condition_bt_node
- nav2_are_error_recovery_conditions_bt_node
- nav2_are_goal_reached_conditions_bt_node
- nav2_initial_pose_received_condition_bt_node
- nav2_goal_updated_condition_bt_node
- nav2_reinitialize_global_localization_service_bt_node
- nav2_rate_controller_bt_node
- nav2_distance_controller_bt_node
- nav2_speed_controller_bt_node
- nav2_truncate_path_action_bt_node
- nav2_goal_updater_node_bt_node
- nav2_recovery_node_bt_node
- nav2_pipeline_sequence_bt_node
- nav2_round_robin_node_bt_node
- nav2_transform_available_condition_bt_node
- nav2_time_expired_condition_bt_node
- nav2_path_expiring_timer_condition
- nav2_distance_traveled_condition_bt_node
- nav2_single_trigger_bt_node
- nav2_is_battery_low_condition_bt_node
- nav2_navigate_through_poses_action_bt_node
- nav2_navigate_to_pose_action_bt_node
- nav2_remove_passed_goals_action_bt_node
- nav2_planner_selector_bt_node
- nav2_controller_selector_bt_node
- nav2_goal_checker_selector_bt_node

bt_navigator_rclcpp_node:
ros__parameters:
use_sim_time: False

controller_server:
ros__parameters:
use_sim_time: False
controller_frequency: 10.0
min_x_velocity_threshold: 0.001
min_y_velocity_threshold: 0.001
min_theta_velocity_threshold: 0.001
progress_checker_plugin: "progress_checker"
goal_checker_plugin: "goal_checker"
controller_plugins: ["FollowPath"]

# Humanoid-specific controller
FollowPath:
plugin: "nav2_mppi_controller::MPPIController"
time_steps: 50
model_dt: 0.05
batch_size: 1000
vx_std: 0.2
vy_std: 0.05
wz_std: 0.3
vx_max: 0.8
vx_min: -0.3
vy_max: 0.3
wz_max: 1.0
simulation_time: 2.0
speed_scaling_factor: 0.2
transform_tolerance: 0.1
alpha: 0.0
beta: 0.9
momentum_scaling: 0.0
collision_cost: 1000.0
goal_dist_cost: 2.0
goal_angle_cost: 0.1
path_angle_cost: 0.2
path_dist_cost: 0.1
prefer_speed: 0.1
xy_goal_tolerance: 0.25
yaw_goal_tolerance: 0.15
stateful: True

controller_server_rclcpp_node:
ros__parameters:
use_sim_time: False

local_costmap:
local_costmap:
ros__parameters:
update_frequency: 5.0
publish_frequency: 2.0
global_frame: odom
robot_base_frame: base_link
use_sim_time: False
rolling_window: true
width: 6
height: 6
resolution: 0.05
robot_radius: 0.35 # Humanoid-specific radius
plugins: ["voxel_layer", "inflation_layer"]
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
voxel_layer:
plugin: "nav2_costmap_2d::VoxelLayer"
enabled: True
publish_voxel_map: True
origin_z: 0.0
z_resolution: 0.2
z_voxels: 8
max_obstacle_height: 2.0
mark_threshold: 0
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
local_costmap_client:
ros__parameters:
use_sim_time: False
local_costmap_rclcpp_node:
ros__parameters:
use_sim_time: False

global_costmap:
global_costmap:
ros__parameters:
update_frequency: 1.0
publish_frequency: 1.0
global_frame: map
robot_base_frame: base_link
use_sim_time: False
robot_radius: 0.35 # Humanoid-specific radius
resolution: 0.05
plugins: ["static_layer", "obstacle_layer", "inflation_layer"]
obstacle_layer:
plugin: "nav2_costmap_2d::ObstacleLayer"
enabled: True
observation_sources: scan
scan:
topic: /scan
max_obstacle_height: 2.0
clearing: True
marking: True
data_type: "LaserScan"
raytrace_max_range: 3.0
raytrace_min_range: 0.0
obstacle_max_range: 2.5
obstacle_min_range: 0.0
static_layer:
plugin: "nav2_costmap_2d::StaticLayer"
map_subscribe_transient_local: True
inflation_layer:
plugin: "nav2_costmap_2d::InflationLayer"
cost_scaling_factor: 3.0
inflation_radius: 0.55
global_costmap_client:
ros__parameters:
use_sim_time: False
global_costmap_rclcpp_node:
ros__parameters:
use_sim_time: False

planner_server:
ros__parameters:
expected_planner_frequency: 20.0
planner_plugins: ["GridBased"]
GridBased:
plugin: "nav2_navfn_planner::NavfnPlanner"
tolerance: 0.5
use_astar: false
allow_unknown: true

planner_server_rclcpp_node:
ros__parameters:
use_sim_time: False

recoveries_server:
ros__parameters:
costmap_topic: local_costmap/costmap_raw
footprint_topic: local_costmap/published_footprint
cycle_frequency: 10.0
recovery_plugins: ["spin", "backup", "wait"]
spin:
plugin: "nav2_recoveries::Spin"
sim_frequency: 5
sim_step_time: 0.05
max_rotational_vel: 0.2
min_rotational_vel: 0.05
rotational_acc_lim: 3.2
backup:
plugin: "nav2_recoveries::BackUp"
sim_frequency: 5
sim_step_time: 0.05
max_vel: 0.05
min_vel: 0.025
tolerance: 0.15
samples: 25
wait:
plugin: "nav2_recoveries::Wait"
sim_frequency: 5
sim_step_time: 0.05
wait_duration: 5.0

robot_state_publisher:
ros__parameters:
use_sim_time: False

Launch File for Humanoid Navigation​

<!-- humanoid_nav2.launch.py -->
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from nav2_common.launch import RewrittenYaml


def generate_launch_description():
use_sim_time = LaunchConfiguration('use_sim_time')
params_file = LaunchConfiguration('params_file')
namespace = LaunchConfiguration('namespace')

lifecycle_nodes = ['controller_server',
'planner_server',
'recoveries_server',
'bt_navigator',
'waypoint_follower']

# Map fully qualified names to relative ones so the node's namespace can be prepended.
# In case of the transforms (tf), currently, there are a few ones for which (e.g. /tf_static)
# which get created automatically. For these, the namespace will be empty.
remappings = [('/tf', 'tf'),
('/tf_static', 'tf_static')]

return LaunchDescription([
# Declare launch arguments
DeclareLaunchArgument(
'namespace', default_value='',
description='Top-level namespace'),
DeclareLaunchArgument(
'use_sim_time', default_value='false',
description='Use simulation (Gazebo) clock if true'),
DeclareLaunchArgument(
'params_file',
default_value='package://humanoid_navigation/config/nav2_params.yaml',
description='Full path to the ROS2 parameters file to use for all launched nodes'),

# Lifecycle manager
Node(
package='nav2_lifecycle_manager',
executable='lifecycle_manager',
name='lifecycle_manager_navigation',
parameters=[{'use_sim_time': use_sim_time},
{'autostart': True},
{'node_names': lifecycle_nodes}],
remappings=remappings),

# Planner server
Node(
package='nav2_planner',
executable='planner_server',
name='planner_server',
output='screen',
parameters=[params_file],
remappings=remappings),

# Controller server
Node(
package='nav2_controller',
executable='controller_server',
name='controller_server',
output='screen',
parameters=[params_file],
remappings=remappings),

# Behavior tree navigator
Node(
package='nav2_bt_navigator',
executable='bt_navigator',
name='bt_navigator',
output='screen',
parameters=[params_file],
remappings=remappings),

# Waypoint follower
Node(
package='nav2_waypoint_follower',
executable='waypoint_follower',
name='waypoint_follower',
output='screen',
parameters=[params_file],
remappings=remappings),

# Recovery server
Node(
package='nav2_recoveries',
executable='recoveries_server',
name='recoveries_server',
output='screen',
parameters=[params_file],
remappings=remappings),

# Robot state publisher
Node(
package='robot_state_publisher',
executable='robot_state_publisher',
name='robot_state_publisher',
output='screen',
parameters=[params_file],
remappings=remappings),
])

Humanoid-Specific Path Planning Considerations​

Terrain Analysis and Step Planning​

Humanoid robots require careful analysis of terrain traversability:

# terrain_analyzer.py
import numpy as np
from scipy import ndimage
from nav2_costmap_2d_py.costmap_2d import Costmap2D
import cv2

class TerrainAnalyzer:
def __init__(self, costmap):
self.costmap = costmap
self.foot_size = 0.15 # Size of humanoid foot (meters)
self.max_step_height = 0.1 # Maximum step height (meters)
self.min_roughness = 0.05 # Minimum acceptable surface roughness

def analyze_traversability(self, x, y, width, height):
"""Analyze a region of the costmap for traversability"""
# Get costmap data in the specified region
region = self.get_costmap_region(x, y, width, height)

# Check for obstacles
obstacle_ratio = np.sum(region > 50) / region.size

# Check for height differences (step analysis)
height_variance = self.calculate_height_variance(region)

# Check surface roughness
roughness = self.calculate_roughness(region)

# Determine traversability score
traversability_score = self.compute_traversability_score(
obstacle_ratio, height_variance, roughness
)

return traversability_score

def get_costmap_region(self, x, y, width, height):
"""Extract a region from the costmap"""
# Convert world coordinates to map coordinates
map_x, map_y = self.costmap.worldToMap(x, y)

# Extract the specified region
start_x = max(0, map_x - width//2)
end_x = min(self.costmap.getSizeInCellsX(), map_x + width//2)
start_y = max(0, map_y - height//2)
end_y = min(self.costmap.getSizeInCellsY(), map_y + height//2)

region = self.costmap.getCharMap()[start_y:end_y, start_x:end_x]
return region

def calculate_height_variance(self, region):
"""Calculate height variance in the region"""
# This is a simplified approach; real implementation would use depth/height data
# Convert cost values to height estimates (this is application specific)
height_map = (region / 255.0) * 2.0 # Assuming max height of 2 meters

# Calculate variance
variance = np.var(height_map)
return variance

def calculate_roughness(self, region):
"""Calculate surface roughness in the region"""
# Use Sobel filter to detect edges/roughness
sobelx = cv2.Sobel(region, cv2.CV_64F, 1, 0, ksize=3)
sobely = cv2.Sobel(region, cv2.CV_64F, 0, 1, ksize=3)

gradient_magnitude = np.sqrt(sobelx**2 + sobely**2)
roughness = np.mean(gradient_magnitude)

return roughness

def compute_traversability_score(self, obstacle_ratio, height_variance, roughness):
"""Compute overall traversability score"""
# Weight the different factors
obstacle_penalty = obstacle_ratio * 0.8
height_penalty = min(height_variance / self.max_step_height, 1.0) * 0.1
roughness_penalty = min(roughness / self.min_roughness, 1.0) * 0.1

total_penalty = obstacle_penalty + height_penalty + roughness_penalty
traversability_score = 1.0 - total_penalty

return max(0.0, traversability_score) # Ensure non-negative score

Balance and Stability Constraints​

For humanoid navigation, balance constraints must be considered:

// balance_constraint_planner.cpp
#include <nav2_core/global_planner.hpp>
#include <nav2_costmap_2d/costmap_2d_ros.h>
#include <geometry_msgs/msg/pose_stamped.hpp>
#include <nav_msgs/msg/path.hpp>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <cmath>

class BalanceConstraintPlanner : public nav2_core::GlobalPlanner
{
public:
void configure(
const rclcpp_lifecycle::LifecycleNode::WeakPtr & parent,
std::string name,
std::shared_ptr<tf2_ros::Buffer> tf,
std::shared_ptr<nav2_costmap_2d::Costmap2DROS> costmap_ros) override
{
node_ = parent.lock();
name_ = name;
tf_ = tf;
costmap_ = costmap_ros->getCostmap();
global_frame_ = costmap_ros->getGlobalFrameID();

// Get humanoid-specific parameters
node_->get_parameter_or("foot_separation", foot_separation_, 0.2); // Distance between feet
node_->get_parameter_or("zmp_margin", zmp_margin_, 0.05); // Zero moment point safety margin
node_->get_parameter_or("max_incline", max_incline_, 15.0); // Maximum allowed incline (degrees)
}

void cleanup() override
{
RCLCPP_INFO(node_->get_logger(), "Cleaning up planner: %s", name_.c_str());
}

void activate() override
{
RCLCPP_INFO(node_->get_logger(), "Activating planner: %s", name_.c_str());
}

void deactivate() override
{
RCLCPP_INFO(node_->get_logger(), "Deactivating planner: %s", name_.c_str());
}

nav_msgs::msg::Path createPlan(
const geometry_msgs::msg::PoseStamped & start,
const geometry_msgs::msg::PoseStamped & goal) override
{
nav_msgs::msg::Path path;

// Check if start and goal are in the same frame
if (start.header.frame_id != global_frame_ || goal.header.frame_id != global_frame_) {
RCLCPP_ERROR(node_->get_logger(), "Start and goal poses must be in the global frame");
return path;
}

// Get start and goal coordinates
double start_x = start.pose.position.x;
double start_y = start.pose.position.y;
double goal_x = goal.pose.position.x;
double goal_y = goal.pose.position.y;

// Perform A* planning with balance constraints
path = planWithBalanceConstraints(start_x, start_y, goal_x, goal_y);

return path;
}

private:
nav_msgs::msg::Path planWithBalanceConstraints(double start_x, double start_y,
double goal_x, double goal_y)
{
nav_msgs::msg::Path path;
path.header.frame_id = global_frame_;
path.header.stamp = node_->now();

// This is a simplified implementation - a full implementation would include:
// 1. A* or Dijkstra's algorithm adapted for humanoid constraints
// 2. Balance constraint checking at each potential step
// 3. Terrain slope analysis
// 4. ZMP (Zero Moment Point) constraint checking

// For this example, we'll use a simple grid-based approach with balance constraints
std::vector<std::pair<double, double>> waypoints;

// Add start point
waypoints.push_back({start_x, start_y});

// Plan a straight-line path with intermediate waypoints
double step_size = 0.1; // 10cm steps
double dx = goal_x - start_x;
double dy = goal_y - start_y;
double distance = sqrt(dx*dx + dy*dy);
int num_steps = static_cast<int>(distance / step_size);

for (int i = 1; i <= num_steps; ++i) {
double ratio = static_cast<double>(i) / num_steps;
double x = start_x + ratio * dx;
double y = start_y + ratio * dy;

// Check balance constraints before adding waypoint
if (isBalanceSafe(x, y)) {
waypoints.push_back({x, y});
} else {
// If balance is not safe, find an alternative route
auto alternative_waypoints = findAlternativePath(start_x, start_y, x, y);
waypoints.insert(waypoints.end(), alternative_waypoints.begin(), alternative_waypoints.end());
}
}

// Add goal point
waypoints.push_back({goal_x, goal_y});

// Convert waypoints to Path message
for (const auto& waypoint : waypoints) {
geometry_msgs::msg::PoseStamped pose;
pose.header.frame_id = global_frame_;
pose.pose.position.x = waypoint.first;
pose.pose.position.y = waypoint.second;
pose.pose.position.z = 0.0;
pose.pose.orientation.w = 1.0; // Default orientation

path.poses.push_back(pose);
}

return path;
}

bool isBalanceSafe(double x, double y)
{
// Check if the proposed step maintains balance
// This would involve checking ZMP, terrain slope, etc.

// Get map coordinates
unsigned int map_x, map_y;
if (!costmap_->worldToMap(x, y, map_x, map_y)) {
return false; // Outside map bounds
}

// Check if the cell is traversable
unsigned char cost = costmap_->getCost(map_x, map_y);
if (cost >= nav2_costmap_2d::INSCRIBED_INFLATED_OBSTACLE) {
return false; // Occupied cell
}

// Check terrain slope (simplified)
// In a real implementation, you would analyze elevation data
double slope = estimateSlope(x, y);
if (slope > max_incline_) {
return false; // Too steep
}

return true; // Balance appears safe
}

double estimateSlope(double x, double y)
{
// Estimate terrain slope at the given point
// This is a simplified approach - real implementation would use elevation map
return 0.0; // Placeholder
}

std::vector<std::pair<double, double>> findAlternativePath(double start_x, double start_y,
double dest_x, double dest_y)
{
// Find an alternative path around a balance-unsafe area
// This would use a pathfinding algorithm like A*
std::vector<std::pair<double, double>> alt_path;

// For simplicity, add the destination directly
// In a real implementation, this would find a path around obstacles
alt_path.push_back({dest_x, dest_y});

return alt_path;
}

// Member variables
rclcpp_lifecycle::LifecycleNode::SharedPtr node_;
std::string name_;
std::shared_ptr<tf2_ros::Buffer> tf_;
nav2_costmap_2d::Costmap2D* costmap_;
std::string global_frame_;

// Humanoid-specific parameters
double foot_separation_;
double zmp_margin_;
double max_incline_;
};

Advanced Navigation Behaviors for Humanoids​

Adaptive Path Replanning​

Humanoid robots need to replan their paths when they encounter unexpected obstacles or terrain changes:

# adaptive_replanner.py
import rclpy
from rclpy.node import Node
from nav_msgs.msg import Path, OccupancyGrid
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import LaserScan
import numpy as np
from scipy.spatial import KDTree
import copy

class AdaptiveReplanner(Node):
def __init__(self):
super().__init__('adaptive_replanner')

# Subscribers
self.path_sub = self.create_subscription(
Path, 'plan', self.path_callback, 10)
self.scan_sub = self.create_subscription(
LaserScan, 'scan', self.scan_callback, 10)
self.costmap_sub = self.create_subscription(
OccupancyGrid, 'global_costmap/costmap',
self.costmap_callback, 10)

# Publishers
self.replan_path_pub = self.create_publisher(
Path, 'replanned_path', 10)
self.replan_request_pub = self.create_publisher(
PoseStamped, 'replan_request', 10)

# Parameters
self.replan_threshold = 0.7 # If 70% of path is blocked, replan
self.local_window_size = 5.0 # Size of local window for replanning
self.min_distance_to_replan = 2.0 # Minimum distance to obstacle to trigger replan

# Internal state
self.current_path = None
self.current_costmap = None
self.path_tree = None
self.replan_timer = self.create_timer(1.0, self.check_replan_needed)

self.get_logger().info('Adaptive Replanner initialized')

def path_callback(self, msg):
"""Store the current path"""
self.current_path = msg
# Build KD-tree for efficient nearest neighbor search
if len(msg.poses) > 0:
points = [(pose.pose.position.x, pose.pose.position.y) for pose in msg.poses]
self.path_tree = KDTree(points)

def scan_callback(self, msg):
"""Process laser scan to detect obstacles"""
# Check if obstacles are blocking the current path
if self.current_path:
self.check_path_obstacles(msg)

def costmap_callback(self, msg):
"""Store the current costmap"""
self.current_costmap = msg

def check_path_obstacles(self, scan_msg):
"""Check if current path is blocked by obstacles"""
if not self.current_path or not self.path_tree:
return

# Get robot position (assuming we can get this from TF or another source)
robot_x, robot_y = 0.0, 0.0 # Placeholder - should get from TF

# Find the closest point on path to robot
robot_pos = np.array([robot_x, robot_y])
_, closest_idx = self.path_tree.query(robot_pos)

# Check upcoming path segments
start_idx = closest_idx
end_idx = min(closest_idx + 20, len(self.current_path.poses))

blocked_count = 0
total_checked = 0

for i in range(start_idx, end_idx):
pose = self.current_path.poses[i]
path_point = np.array([pose.pose.position.x, pose.pose.position.y])
dist_to_robot = np.linalg.norm(path_point - robot_pos)

# Check if this path point is blocked
if self.is_obstacle_near_path_point(path_point, scan_msg):
blocked_count += 1
total_checked += 1

# Calculate blocked ratio
if total_checked > 0:
blocked_ratio = blocked_count / total_checked
if blocked_ratio > self.replan_threshold:
self.get_logger().info(f'Replanning needed: {blocked_ratio:.2f} of path blocked')
self.trigger_replan()

def is_obstacle_near_path_point(self, path_point, scan_msg):
"""Check if there are obstacles near a path point using laser scan"""
# Convert path point to robot frame
robot_x, robot_y = 0.0, 0.0 # Should get from TF

# Simple check: if there's an obstacle within a certain distance
for i, range_val in enumerate(scan_msg.ranges):
if range_val < scan_msg.range_min or range_val > scan_msg.range_max:
continue # Invalid range

# Calculate angle of this laser beam
angle = scan_msg.angle_min + i * scan_msg.angle_increment

# Calculate position of obstacle point
obstacle_x = robot_x + range_val * np.cos(angle)
obstacle_y = robot_y + range_val * np.sin(angle)

# Check distance to path point
obstacle_point = np.array([obstacle_x, obstacle_y])
dist = np.linalg.norm(path_point - obstacle_point)

if dist < 0.5: # 50cm threshold
return True

return False

def check_replan_needed(self):
"""Check if replanning is needed based on costmap changes"""
# Check if costmap has changed significantly in path area
if not self.current_path or not self.current_costmap:
return

# Implement logic to detect significant changes in costmap
# along the current path
pass

def trigger_replan(self):
"""Request a new path from the global planner"""
if not self.current_path:
return

# Create replan request with current robot position and goal
robot_pose = PoseStamped()
robot_pose.header.frame_id = self.current_path.header.frame_id

# Get goal from current path
goal_pose = self.current_path.poses[-1] if self.current_path.poses else None
if goal_pose:
robot_pose.pose = goal_pose.pose # This should be robot's current pose in practice
self.replan_request_pub.publish(robot_pose)

# Optionally, clear the local costmap to help with replanning
self.clear_local_costmap()

def clear_local_costmap(self):
"""Clear the local costmap to help with replanning"""
# In practice, this would call the clear_costmap service
self.get_logger().info('Clearing local costmap')

def interpolate_path(self, path, resolution=0.1):
"""Interpolate path to have points at regular intervals"""
if len(path.poses) < 2:
return path

interpolated_path = Path()
interpolated_path.header = path.header

for i in range(len(path.poses) - 1):
start_pose = path.poses[i]
end_pose = path.poses[i + 1]

start_point = np.array([start_pose.pose.position.x, start_pose.pose.position.y])
end_point = np.array([end_pose.pose.position.x, end_pose.pose.position.y])

segment_length = np.linalg.norm(end_point - start_point)
num_interpolations = int(segment_length / resolution)

for j in range(num_interpolations + 1):
ratio = j / num_interpolations if num_interpolations > 0 else 0
interp_pose = PoseStamped()
interp_pose.header = path.header
interp_pose.pose.position.x = start_point[0] + ratio * (end_point[0] - start_point[0])
interp_pose.pose.position.y = start_point[1] + ratio * (end_point[1] - start_point[1])

# Interpolate orientation similarly
# (Simplified - in practice, you'd want to interpolate the quaternions properly)
interp_pose.pose.orientation = start_pose.pose.orientation

interpolated_path.poses.append(interp_pose)

return interpolated_path

def main(args=None):
rclpy.init(args=args)
replanner = AdaptiveReplanner()

try:
rclpy.spin(replanner)
except KeyboardInterrupt:
pass
finally:
replanner.destroy_node()
rclpy.shutdown()

if __name__ == '__main__':
main()

Integration with Humanoid Locomotion Controller​

Footstep Planning Integration​

The navigation plan needs to be integrated with the humanoid's locomotion controller:

# footstep_planner.py
import numpy as np
from scipy.spatial.distance import cdist
from geometry_msgs.msg import Point

class FootstepPlanner:
def __init__(self, step_length=0.3, step_width=0.2, max_turn_rate=0.3):
self.step_length = step_length # Forward step length
self.step_width = step_width # Lateral step width (half between feet)
self.max_turn_rate = max_turn_rate # Max turning rate per step

# Current state of the robot
self.left_foot_pos = np.array([0.0, 0.1, 0.0]) # Initial left foot position
self.right_foot_pos = np.array([0.0, -0.1, 0.0]) # Initial right foot position
self.support_foot = 'right' # Which foot supports the body weight

def plan_footsteps(self, path, robot_pose):
"""Plan footstep sequence based on navigation path"""
footsteps = []

if len(path.poses) == 0:
return footsteps

# Start from robot's current position (not the path start)
current_pos = np.array([
robot_pose.pose.position.x,
robot_pose.pose.position.y,
robot_pose.pose.position.z
])

# Current orientation
from tf_transformations import euler_from_quaternion
quat = robot_pose.pose.orientation
current_yaw = euler_from_quaternion([quat.x, quat.y, quat.z, quat.w])[2]

# Initialize stance phase position
robot_stance_x, robot_stance_y = current_pos[0], current_pos[1]
robot_yaw = current_yaw

path_idx = 0
max_iterations = 1000 # Prevent infinite loops
iteration = 0

while path_idx < len(path.poses) and iteration < max_iterations:
iteration += 1

# Get the next path target
target = np.array([
path.poses[path_idx].pose.position.x,
path.poses[path_idx].pose.position.y,
path.poses[path_idx].pose.position.z
])

# Calculate desired position and orientation
desired_dx = target[0] - robot_stance_x
desired_dy = target[1] - robot_stance_y
desired_yaw = np.arctan2(desired_dy, desired_dx)

# Limit turning rate
yaw_diff = desired_yaw - robot_yaw
# Normalize angle to [-π, π]
while yaw_diff > np.pi:
yaw_diff -= 2 * np.pi
while yaw_diff < -np.pi:
yaw_diff += 2 * np.pi

# Apply turn rate limit
if abs(yaw_diff) > self.max_turn_rate:
yaw_diff = np.sign(yaw_diff) * self.max_turn_rate

robot_yaw += yaw_diff

# Determine next footstep position
if self.support_foot == 'right':
# Plan left footstep
next_step_x = robot_stance_x + self.step_length * np.cos(robot_yaw)
next_step_y = robot_stance_y + self.step_length * np.sin(robot_yaw) + self.step_width
next_step_z = 0.0 # Assume flat ground for simplicity
self.support_foot = 'left'
foot_label = 'left'
else:
# Plan right footstep
next_step_x = robot_stance_x + self.step_length * np.cos(robot_yaw)
next_step_y = robot_stance_y + self.step_length * np.sin(robot_yaw) - self.step_width
next_step_z = 0.0
self.support_foot = 'right'
foot_label = 'right'

# Update robot stance to the new foot position
robot_stance_x = next_step_x
robot_stance_y = next_step_y

# Create footstep
footstep = {
'position': Point(x=next_step_x, y=next_step_y, z=next_step_z),
'yaw': robot_yaw,
'foot': foot_label,
'step_type': 'walk' # Could also be 'step_over', 'step_up', etc.
}

footsteps.append(footstep)

# Move to the next path point if we're close enough
dist_to_path = np.sqrt((target[0] - robot_stance_x)**2 + (target[1] - robot_stance_y)**2)
if dist_to_path < 0.1: # Close enough to target
path_idx += 1

return footsteps

def validate_footstep(self, footstep_pos, costmap, inflation_radius=0.1):
"""Validate if a footstep is safe based on the costmap"""
# Convert footstep position to costmap coordinates
map_x = int((footstep_pos.x - costmap.info.origin.position.x) / costmap.info.resolution)
map_y = int((footstep_pos.y - costmap.info.origin.position.y) / costmap.info.resolution)

# Check if the footstep is within map bounds
if (map_x < 0 or map_x >= costmap.info.width or
map_y < 0 or map_y >= costmap.info.height):
return False

# Check a small area around the footstep position
radius_cells = int(inflation_radius / costmap.info.resolution)
for dx in range(-radius_cells, radius_cells + 1):
for dy in range(-radius_cells, radius_cells + 1):
check_x = map_x + dx
check_y = map_y + dy

# Check bounds again
if 0 <= check_x < costmap.info.width and 0 <= check_y < costmap.info.height:
idx = check_y * costmap.info.width + check_x
if costmap.data[idx] >= 50: # Consider cells with cost >= 50 as unsafe
return False # Obstacle detected

return True # Safe footstep

def main():
# Example usage
from nav_msgs.msg import Path
from geometry_msgs.msg import PoseStamped

# Create a sample path
path = Path()
path.header.frame_id = "map"
for i in range(10):
pose = PoseStamped()
pose.pose.position.x = i * 0.5
pose.pose.position.y = 0.0
pose.pose.orientation.w = 1.0
path.poses.append(pose)

# Create footstep planner
planner = FootstepPlanner()

# Create a robot pose
robot_pose = PoseStamped()
robot_pose.pose.position.x = 0.0
robot_pose.pose.position.y = 0.0
robot_pose.pose.orientation.w = 1.0

# Plan footsteps
footsteps = planner.plan_footsteps(path, robot_pose)

print(f"Planned {len(footsteps)} footsteps:")
for i, step in enumerate(footsteps):
print(f" Step {i+1}: {step['foot']} foot at ({step['position'].x:.2f}, {step['position'].y:.2f})")

if __name__ == "__main__":
main()

Performance Optimization and Tuning​

Parameter Tuning Guidelines​

Tuning Nav2 for humanoid robots requires careful parameter adjustment:

# tuning_guidelines.yaml
# Key parameters for humanoid navigation

# Costmap parameters
global_costmap:
robot_radius: 0.35 # Adjust based on actual robot dimensions
inflation_radius: 0.55 # Larger radius for safety with bipedal robots
resolution: 0.05 # Higher resolution for detailed terrain analysis

local_costmap:
robot_radius: 0.35 # Same as global costmap for consistency
inflation_radius: 0.40 # Slightly smaller than global for tighter navigation
width: 6 # Local window size appropriate for humanoid step length
height: 6
resolution: 0.05

# Controller parameters for humanoid-specific motion
controller_server:
controller_frequency: 10.0 # Lower frequency appropriate for humanoid dynamics
FollowPath:
# MPPI controller parameters tuned for humanoid
time_steps: 50 # Prediction horizon
model_dt: 0.05 # Time step for prediction
vx_max: 0.8 # Maximum forward velocity (lower than wheeled robots)
vx_min: -0.3 # Maximum backward velocity
wz_max: 1.0 # Maximum angular velocity
xy_goal_tolerance: 0.25 # Larger tolerance for humanoid precision
yaw_goal_tolerance: 0.15

# Planner parameters
planner_server:
GridBased:
tolerance: 0.5 # Larger tolerance for humanoid navigation
allow_unknown: true # Plan through unknown areas if needed

# Recovery behaviors tuned for humanoid
recoveries_server:
spin:
max_rotational_vel: 0.2 # Slower rotation for stability
min_rotational_vel: 0.05
backup:
max_vel: 0.05 # Very slow backup for stability
min_vel: 0.025
tolerance: 0.15

Troubleshooting and Validation​

Common Navigation Issues in Humanoids​

  1. Frequent Replanning: Often caused by sensors that don't match the costmap configuration
  2. Path Following Drift: Usually due to odometry errors or controller tuning
  3. Conservative Behavior: Costmap inflation or controller parameters set too high
  4. Stability Issues: Path not accounting for balance constraints

Validation Metrics​

# navigation_metrics.py
import numpy as np
import matplotlib.pyplot as plt

class NavigationMetrics:
def __init__(self):
self.path_lengths = []
self.execution_times = []
self.success_rates = []
self.energy_consumptions = []

def calculate_path_efficiency(self, planned_path, optimal_path):
"""Calculate path efficiency as ratio of planned to optimal length"""
planned_length = self.calculate_path_length(planned_path)
optimal_length = self.calculate_path_length(optimal_path)

if optimal_length > 0:
return planned_length / optimal_length
else:
return float('inf') # Path planning failed

def calculate_path_length(self, path):
"""Calculate the total length of a path"""
if len(path.poses) < 2:
return 0

length = 0
for i in range(len(path.poses) - 1):
p1 = path.poses[i].pose.position
p2 = path.poses[i+1].pose.position
segment_length = np.sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)
length += segment_length

return length

def evaluate_navigation_performance(self, robot_trajectory, planned_path, goal_tolerance=0.5):
"""Evaluate overall navigation performance"""
# Check if goal was reached
if len(robot_trajectory) == 0:
success = False
execution_time = float('inf')
else:
final_pos = robot_trajectory[-1]
goal_pos = planned_path.poses[-1].pose.position
dist_to_goal = np.sqrt((final_pos[0] - goal_pos.x)**2 + (final_pos[1] - goal_pos.y)**2)
success = dist_to_goal <= goal_tolerance
execution_time = len(robot_trajectory) * 0.1 # Assuming 10Hz control rate

# Calculate path efficiency
if success:
optimal_path_length = self.calculate_path_length(planned_path)
efficiency = self.calculate_path_efficiency(robot_trajectory, planned_path) if planned_path else 1.0
else:
optimal_path_length = float('inf')
efficiency = float('inf')

# Store metrics
self.success_rates.append(success)
self.execution_times.append(execution_time)

return {
'success': success,
'execution_time': execution_time,
'path_efficiency': efficiency,
'optimal_path_length': optimal_path_length
}

def plot_performance(self):
"""Plot navigation performance metrics"""
fig, axes = plt.subplots(2, 2, figsize=(12, 10))

# Success rates
axes[0, 0].bar(range(len(self.success_rates)), [1 if x else 0 for x in self.success_rates])
axes[0, 0].set_title('Navigation Success Rate')
axes[0, 0].set_xlabel('Trial')
axes[0, 0].set_ylabel('Success (1) / Failure (0)')

# Execution times
if self.execution_times:
axes[0, 1].plot(self.execution_times)
axes[0, 1].set_title('Execution Time per Trial')
axes[0, 1].set_xlabel('Trial')
axes[0, 1].set_ylabel('Time (s)')

# Path lengths if available
if self.path_lengths:
axes[1, 0].hist(self.path_lengths, bins=10)
axes[1, 0].set_title('Distribution of Path Lengths')
axes[1, 0].set_xlabel('Path Length (m)')
axes[1, 0].set_ylabel('Frequency')

plt.tight_layout()
plt.show()

def main():
# Example usage
metrics = NavigationMetrics()

# Sample evaluation
success = True
execution_time = 15.5 # seconds
path_efficiency = 1.2 # 1.2x optimal length

print(f"Navigation Success: {success}")
print(f"Execution Time: {execution_time}s")
print(f"Path Efficiency: {path_efficiency}")

if __name__ == "__main__":
main()

Hands-on Lab: Implementing Humanoid Navigation​

In this lab, you'll configure and test Nav2 for humanoid robot navigation.

Step 1: Environment Setup​

  1. Set up a simulation environment with a humanoid robot model
  2. Configure sensors (LiDAR, camera, IMU) for navigation
  3. Install Nav2 and humanoid-specific packages

Step 2: Costmap Configuration​

  1. Configure global and local costmaps for humanoid navigation
  2. Adjust inflation parameters for safe navigation
  3. Test costmap responses to different obstacle types

Step 3: Navigation Testing​

  1. Implement the navigation stack in simulation
  2. Test navigation with different path types (straight, curved, with obstacles)
  3. Evaluate navigation performance and adjust parameters

Step 4: Integration with Locomotion​

  1. Integrate the navigation path with footstep planning
  2. Test full navigation-locomotion pipeline
  3. Evaluate overall system performance

Troubleshooting Notes​

  1. Path Oscillation: Check controller parameters and costmap inflation settings.
  2. Frequent Replanning: Verify sensor configuration and costmap update frequency.
  3. Balance Issues: Ensure path planning accounts for balance constraints.
  4. Performance Problems: Optimize costmap resolution and update rates.

Summary​

In this chapter, we explored how to adapt the Navigation2 stack for humanoid robot navigation. We covered special considerations for bipedal locomotion, terrain analysis, balance constraints, and integration with locomotion controllers. By properly configuring Nav2 with humanoid-specific parameters and behaviors, we can enable safe and efficient navigation for humanoid robots.

Next Steps​

The next chapter will explore reinforcement learning control for humanoid robots, building on the navigation capabilities we've implemented to enable adaptive and learning-based control strategies.

References​

  1. Nav2 Documentation: https://navigation.ros.org/
  2. Humanoid Navigation Research: https://ieeexplore.ieee.org/document/9166261
  3. Footstep Planning: https://www.ri.cmu.edu/pub_files/2007/3/ICRA07-0556.pdf
  4. ROS Navigation Tutorials: http://wiki.ros.org/navigation/Tutorials
  5. Locomotion Control: https://arxiv.org/abs/1908.02124
💬
🤖
ROBO-ASSISTANT
Hello! I'm your AI assistant for Physical AI & Humanoid Robotics. How can I help you today?