"""Nav2 Humble parameters derived from the selected rover, without map data. The drive limits remain the simulation profile's engineering assumptions. Compiling or activating these parameters does not qualify physical dynamics. """ import copy import hashlib import json import math import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from rig_collision import collision_geometry # noqa: E402 def configuration(inputs, robot): body = {key: value for key, value in inputs.items() if key != 'sha256'} actual = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest() if actual != inputs['sha256']: raise ValueError('Execution inputs identity changed') geometry = collision_geometry(inputs['robot']['geometry'], inputs['sensors']['mounts']) x, y = geometry['collision_length_m'] / 2, geometry['collision_width_m'] / 2 control = robot['control'] speed = float(inputs['behavior']['max_speed_mps']) acceleration = float(control['acceleration_mps2']) deceleration = float(control['deceleration_mps2']) yaw = float(control['max_yaw_rps']) track_width = float(robot['physics']['track_width_m']) track_centres = [(band['lower_xy_m'][1]+band['upper_xy_m'][1])/2 for band in inputs['robot']['geometry']['ground_contact']['bands']] if not all(math.isfinite(v) and v > 0 for v in (x, y, speed, acceleration, deceleration, yaw, track_width)): raise ValueError('Invalid rover envelope') footprint = json.dumps([[x, y], [-x, y], [-x, -y], [x, -y]]) costmap = dict( use_sim_time=False, global_frame='map', robot_base_frame='base_link', update_frequency=10.0, publish_frequency=5.0, resolution=0.05, rolling_window=False, track_unknown_space=True, footprint=footprint, footprint_padding=0.05, transform_tolerance=0.2, always_send_full_costmap=True, plugins=['static_layer', 'inflation_layer'], static_layer=dict(plugin='nav2_costmap_2d::StaticLayer', map_topic='/observed_map', map_subscribe_transient_local=True, subscribe_to_updates=False), inflation_layer=dict(plugin='nav2_costmap_2d::InflationLayer', cost_scaling_factor=3.0, inflation_radius=math.hypot(x, y) + 0.15), ) # Bound the corner displacement from a full angular bin to half a map # cell. Humble floors the start heading; a coarse primitive lattice can # classify an actually clear rectangular start as colliding. Hybrid-A* # exposes angular resolution without generating custom motion primitives. # Round to quarter-turn symmetry, independent of world coordinates. radius = math.hypot(x + costmap['footprint_padding'], y + costmap['footprint_padding']) angle_step = 2 * math.asin(min(1.0, costmap['resolution'] / (4 * radius))) heading_bins = max(8, 4 * math.ceil((2 * math.pi / angle_step) / 4)) return { 'behavior_server': {'ros__parameters': dict( use_sim_time=False, global_frame='map', robot_base_frame='base_link', costmap_topic='local_costmap/costmap_raw', footprint_topic='local_costmap/published_footprint', cycle_frequency=20.0, transform_tolerance=0.2, behavior_plugins=['spin', 'backup'], spin=dict(plugin='nav2_behaviors/Spin'), backup=dict(plugin='nav2_behaviors/BackUp'), simulate_ahead_time=0.8+speed/deceleration, max_rotational_vel=yaw, min_rotational_vel=0.0, rotational_acc_lim=2*acceleration/track_width, )}, 'planner_server': {'ros__parameters': dict( use_sim_time=False, expected_planner_frequency=5.0, planner_plugins=['GridBased'], GridBased=dict(plugin='nav2_smac_planner/SmacPlannerHybrid', motion_model_for_search='DUBIN', # Retain the former differential lattice's 0.5 m # minimum arc radius; explicit Spin/BackUp stay # separate native behaviors behind unchanged gates. minimum_turning_radius=0.5, angle_quantization_bins=heading_bins, allow_unknown=False, tolerance=0.0, max_planning_time=0.5, cache_obstacle_heuristic=False, smooth_path=False), )}, 'controller_server': {'ros__parameters': dict( use_sim_time=False, controller_frequency=20.0, odom_topic='/odom', min_x_velocity_threshold=0.001, min_y_velocity_threshold=0.001, min_theta_velocity_threshold=0.001, failure_tolerance=0.0, progress_checker_plugin='progress_checker', goal_checker_plugins=['goal_checker'], controller_plugins=['FollowPath'], progress_checker=dict(plugin='nav2_controller::SimpleProgressChecker', required_movement_radius=0.05, movement_time_allowance=8.0), goal_checker=dict(plugin='nav2_controller::SimpleGoalChecker', stateful=True, xy_goal_tolerance=float(inputs['mission']['arrival_radius_m']), yaw_goal_tolerance=0.15), FollowPath={ 'plugin': 'dwb_core::DWBLocalPlanner', # Upstream default: score acceleration-integrated trajectories # over sim_time. A one-control-period DWA window at rest has # sub-cell endpoints on this rover's 5 cm costmap and aliases # the distance critics. The actuator still applies its own # unchanged acceleration/deceleration limits. 'trajectory_generator_name': 'dwb_plugins::StandardTrajectoryGenerator', 'min_vel_x': 0.0, 'max_vel_x': speed, 'min_vel_y': 0.0, 'max_vel_y': 0.0, 'max_vel_theta': yaw, 'min_speed_xy': 0.0, 'max_speed_xy': speed, 'min_speed_theta': 0.0, 'acc_lim_x': acceleration, 'decel_lim_x': -deceleration, 'acc_lim_y': 0.0, 'decel_lim_y': 0.0, 'acc_lim_theta': 2 * acceleration / track_width, 'decel_lim_theta': -2 * deceleration / track_width, 'vx_samples': 20, 'vy_samples': 1, 'vtheta_samples': 20, 'sim_time': 0.8 + speed / deceleration, 'linear_granularity': 0.025, 'angular_granularity': 0.025, 'transform_tolerance': 0.2, 'trans_stopped_velocity': 0.01, 'xy_goal_tolerance': float(inputs['mission']['arrival_radius_m']), 'short_circuit_trajectory_evaluation': True, 'critics': ['ndc_rover_critics::ForwardTracksCritic', 'RotateToGoal', 'Oscillation', 'ObstacleFootprint', 'PreferForward', 'GoalAlign', 'PathAlign', 'PathDist', 'GoalDist'], 'ndc_rover_critics::ForwardTracksCritic.track_centres_y_m': track_centres, # Upstream angular preference; no arbitrary minimum speed in # the initial acceleration window. Geometry gates stay hard. 'PreferForward.strafe_x': 0.0, 'PreferForward.strafe_theta': 0.0, 'ObstacleFootprint.scale': 0.02, 'PathAlign.scale': 32.0, 'PathAlign.forward_point_distance': x, 'GoalAlign.scale': 24.0, 'GoalAlign.forward_point_distance': x, 'PathDist.scale': 32.0, 'GoalDist.scale': 24.0, 'RotateToGoal.scale': 32.0, 'RotateToGoal.slowing_factor': 5.0, 'RotateToGoal.lookahead_time': -1.0, }, )}, 'global_costmap': {'global_costmap': {'ros__parameters': costmap}}, 'local_costmap': {'local_costmap': {'ros__parameters': copy.deepcopy(costmap)}}, } def observed_configuration(inputs, robot, origin_count): """Use upstream ray clearing/obstacle marking for a rolling collision map. Ground support and surface permission are separate inputs/gates. In particular, a free collision cell is not evidence of supporting pavement. """ if type(origin_count) is not int or not 1 <= origin_count <= 16: raise ValueError('Invalid observed sensor origin count') config = configuration(inputs, robot) sources = { 'hazards': dict(topic='/observed_hazards', data_type='PointCloud2', sensor_frame='base_link', marking=True, clearing=False, min_obstacle_height=-0.01, max_obstacle_height=0.01, obstacle_min_range=0.0, obstacle_max_range=16.0, observation_persistence=0.0), } for index in range(origin_count): sources['range' + str(index)] = dict( topic='/observed_rays_' + str(index), data_type='PointCloud2', sensor_frame='range' + str(index), marking=False, clearing=True, min_obstacle_height=-0.01, max_obstacle_height=0.01, raytrace_min_range=0.0, raytrace_max_range=8.0, observation_persistence=0.0, ) layer = dict(plugin='nav2_costmap_2d::ObstacleLayer', footprint_clearing_enabled=True, observation_sources=' '.join(sources), **sources) for name in ('global_costmap', 'local_costmap'): costmap = config[name][name]['ros__parameters'] costmap.pop('static_layer') costmap.update(rolling_window=True, width=16, height=16, plugins=['obstacle_layer', 'inflation_layer'], obstacle_layer=copy.deepcopy(layer)) return config