#!/usr/bin/env python3 """Run an isolated Gazebo navigation scenario and score it using simulator truth.""" import argparse import hashlib import json import math import os from pathlib import Path import signal import subprocess import sys import time import uuid from collections import Counter import rclpy from rclpy.node import Node from rclpy.action import ActionClient from action_msgs.msg import GoalStatus from rclpy.parameter import Parameter from lifecycle_msgs.srv import GetState from tf2_msgs.msg import TFMessage from nav2_msgs.srv import IsPathValid from nav2_msgs.action import ComputePathToPose, FollowPath from nav_msgs.msg import Odometry from geometry_msgs.msg import PoseStamped, Twist from rclpy.qos import qos_profile_sensor_data from std_msgs.msg import Bool from rcl_interfaces.srv import GetParameters from std_srvs.srv import Trigger from rclpy.utilities import get_rmw_implementation_identifier sys.path[:0] = [str(Path(__file__).resolve().parents[1] / '_internal'), str(Path(__file__).resolve().parents[1])] import project_env from arena_grid import ARENA_GOALS, START, ArenaGrid from nav2_startup import path_probe_request from dds_environment import defaults as dds_defaults from lio_metrics import cylinder_clearance, metrics from verify_lio_stack import NODES, process_environment ROUND_TRIP = ((0.0, 0.0), (-5.0, 3.0), (0.0, 0.0), (-5.0, 3.0), (0.0, 0.0)) ROUND_TRIP_PAUSES = (0, 24, 10, 35, 16) def check_field_coverage(node, grid): coverage = grid.coverage() client = ActionClient(node, ComputePathToPose, '/compute_path_to_pose') try: if not client.wait_for_server(timeout_sec=8): raise RuntimeError('compute_path_to_pose unavailable for field coverage') def pose(point): message = PoseStamped() message.header.frame_id = 'map' message.pose.position.x, message.pose.position.y = point message.pose.orientation.w = 1.0 return message checks = [] for point in coverage.pop('samples'): request = ComputePathToPose.Goal() request.start = pose(START) request.goal = pose(point) request.use_start = True future = client.send_goal_async(request) rclpy.spin_until_future_complete(node, future, timeout_sec=5) handle = future.result() if future.done() else None check = {'target': point, 'passed': False} if handle is None or not handle.accepted: check['error'] = 'goal rejected or acceptance timed out' else: future = handle.get_result_async() rclpy.spin_until_future_complete(node, future, timeout_sec=5) wrapped = future.result() if future.done() else None if wrapped is None: cancel = handle.cancel_goal_async() rclpy.spin_until_future_complete(node, cancel, timeout_sec=1) check['error'] = 'planner response timed out' else: outcome = wrapped.result check.update(error_code=outcome.error_code, error=outcome.error_msg) if wrapped.status == GoalStatus.STATUS_SUCCEEDED and outcome.path.poses: endpoint = outcome.path.poses[-1].pose.position check['endpoint_error_m'] = math.hypot(endpoint.x-point[0], endpoint.y-point[1]) check['passed'] = outcome.error_code == 0 and check['endpoint_error_m'] <= 0.30 checks.append(check) finally: client.destroy() coverage.update(planned=sum(c['passed'] for c in checks), sample_count=len(checks), checks=checks) return coverage def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--map', type=Path, required=True) parser.add_argument('--lio-cloud-topic', default=os.environ.get('LIO_POINT_CLOUD_TOPIC') or '/scan/points_lio') parser.add_argument('--launcher', choices=['shell', 'python'], default='shell') parser.add_argument('--output', type=Path, required=True) goals = parser.add_mutually_exclusive_group() goals.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y')) goals.add_argument('--full-field', action='store_true', help='check reachability in 1 m tiles and navigate the whole-field route') goals.add_argument('--round-trip-regression', action='store_true', help='run the five recorded goals without restarting the stack') parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]', help='use an explicitly reserved ROS_DOMAIN_ID for parallel tests') parser.add_argument('--timeout', type=float, default=420.0, help='whole-stack validation deadline, including up to three startup attempts') parser.add_argument('--scenario', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'], default='clear') parser.add_argument('--obstacle-x',type=float,default=-4.0) parser.add_argument('--obstacle-y',type=float,default=-1.5) parser.add_argument('--obstacle-radius',type=float,default=0.22) parser.add_argument('--rviz', action='store_true', help='include offscreen RViz discovery load') args = parser.parse_args() if args.round_trip_regression and args.scenario not in ('clear', 'cylinder'): parser.error('--round-trip-regression requires clear or cylinder') if args.full_field and args.scenario != 'clear': parser.error('--full-field starts the clear-field coverage route') multileg = args.round_trip_regression or args.full_field route = ARENA_GOALS if args.full_field else ROUND_TRIP if args.round_trip_regression else ((args.goal,) if args.goal else ()) pauses = ROUND_TRIP_PAUSES if args.round_trip_regression else (0,)*len(route) if not args.map.is_file(): parser.error('map missing') if args.output.exists(): parser.error('output must be a new directory') workspace = project_env.WORKSPACE try: gz_exe = project_env.find_gz_bin() bin_dir = project_env.find_bin_dir(workspace) recorder_exe = project_env.require_executable(bin_dir/'field_localization_record', 'field_localization_record') grid = ArenaGrid(project_env.find_map_yaml()) if args.full_field else None if route: nav_client = project_env.require_executable(bin_dir/'nav_client', 'nav_client') except (project_env.ProbeError, ValueError, OSError) as error: parser.exit(1, f'{parser.prog}: {error}\n') args.output.mkdir(parents=True) session = uuid.uuid4().hex[:12] os.environ.update(ROS_DOMAIN_ID=str(args.domain if args.domain is not None else 50+int(session[:8], 16) % 50), GZ_PARTITION=f'lio_stack_{session}', ROS2CLI_DISABLE_DAEMON='1', HEADLESS='1', NAV2='1', RVIZ='0', LOCALIZATION='lio', LIO_MODE='localization', LIO_MAP=str(args.map.resolve()), SENTRY_RUNTIME_DIR=str((args.output/'runtime').resolve()), LIO_TRACE_PATH=str((args.output/'filter_trace.csv').resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve())) os.environ.update(GZ_BIN=str(gz_exe), SENTRY_BIN_DIR=str(bin_dir), LIO_POINT_CLOUD_TOPIC=args.lio_cloud_topic) os.environ.update(dds_defaults(os.environ)) os.environ.setdefault('ROS_LOG_DIR', str((args.output/'ros_log').resolve())) os.environ.setdefault('XDG_CACHE_HOME', str((args.output/'cache').resolve())) params_file = workspace/'src/sentry_sim/config/nav2_params.yaml' runtime = { 'domain': os.environ['ROS_DOMAIN_ID'], 'partition': os.environ['GZ_PARTITION'], 'scenario': args.scenario, 'obstacle': [args.obstacle_x, args.obstacle_y, args.obstacle_radius], 'goals': route, 'pauses_wall_sec': pauses, 'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(), 'lio_map_sha256': hashlib.sha256(args.map.read_bytes()).hexdigest(), 'point_cloud_topic': args.lio_cloud_topic, } (args.output/'runtime.json').write_text(json.dumps(runtime, indent=2)) log = None record_duration = 3600.0 if args.full_field else 1200.0 if multileg else 600.0 record_log = open(args.output/'record.log', 'w', encoding='utf8') recorder = subprocess.Popen([str(recorder_exe), '--ros-args', '-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset', '-p', f'duration_sec:={record_duration}', '-p', f'point_cloud_topic:={args.lio_cloud_topic}'], stdout=record_log, stderr=subprocess.STDOUT, start_new_session=True) if args.launcher == 'shell': command = ['bash', str(workspace/'scripts/sentry_up.sh')] else: command = ['ros2', 'launch', str(workspace/'src/sentry_sim/launch/sentry_arena.launch.py'), 'headless:=true', 'rviz:=false', 'localization:=lio', f'lio_map:={args.map.resolve()}'] log = open(args.output/'stack.log', 'w', encoding='utf8') started = time.monotonic() process = subprocess.Popen(command, cwd=workspace, start_new_session=True, stdout=log if log else subprocess.DEVNULL, stderr=subprocess.STDOUT) rclpy.init() node = Node('verify_lio_stack', parameter_overrides=[Parameter('use_sim_time', value=True)]) publishers = set() samples = {'truth': [], 'estimate': []} health_events = [] health_transitions = [] actuator = [] last_map_tf_wall = None def on_health(msg): stamp = time.monotonic() if not health_events or msg.data != health_events[-1][1]: health_transitions.append({'wall': stamp, 'sim': sim_now(), 'valid': msg.data}) health_events.append((stamp, msg.data)) def sim_now(): return node.get_clock().now().nanoseconds * 1e-9 def spin_for(seconds): deadline = time.monotonic() + seconds while time.monotonic() < deadline: if process.poll() is not None: raise RuntimeError('stack exited during navigation') rclpy.spin_once(node, timeout_sec=0.02) subscription_actuator=node.create_subscription(Twist,'/model/sentry/cmd_vel',lambda msg:actuator.append((time.monotonic(),msg.linear.x,msg.linear.y,msg.angular.z)),100) subscriptions_health=node.create_subscription(Bool,'/field_localization/navigation_valid', on_health, 10) subscriptions = [] def sample(message, name): p = message.pose.pose if name == 'estimate' else message.pose samples[name].append([message.header.stamp.sec+1e-9*message.header.stamp.nanosec, p.position.x,p.position.y,p.position.z,p.orientation.x,p.orientation.y,p.orientation.z,p.orientation.w]) subscriptions.append(node.create_subscription(PoseStamped, '/evaluation/ground_truth', lambda msg: sample(msg, 'truth'), qos_profile_sensor_data)) subscriptions.append(node.create_subscription(Odometry, '/field_localization/odometry', lambda msg: sample(msg, 'estimate'), qos_profile_sensor_data)) counts = {'map_to_odom': 0, 'map_to_base_link': 0} def on_tf(msg, info): nonlocal last_map_tf_wall for transform in msg.transforms: if transform.header.frame_id != 'map': continue if transform.child_frame_id == 'odom': gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid publishers.add(json.dumps(gid, sort_keys=True, default=str)) counts['map_to_odom'] += 1 last_map_tf_wall = time.monotonic() if transform.child_frame_id == 'base_link': counts['map_to_base_link'] += 1 subscription = node.create_subscription(TFMessage, '/tf', on_tf, 500) clients = {name: node.create_client(GetState, f'/{name}/get_state') for name in NODES} path_client = node.create_client(IsPathValid, '/is_path_valid') active_client = node.create_client(Trigger, '/lifecycle_manager_nav2/is_active') parameter_client = node.create_client(GetParameters, '/lifecycle_manager_nav2/get_parameters') states = {} processes = [] rviz = None goal = None reached_readiness = False result = {} try: if args.rviz: rviz = subprocess.Popen(['ros2', 'run', 'rviz2', 'rviz2', '-d', str(workspace/'src/sentry_sim/config/sentry.rviz'), '--ros-args', '-p', 'use_sim_time:=true'], env={**os.environ, 'QT_QPA_PLATFORM': 'offscreen'}, start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) deadline = time.monotonic()+args.timeout last_check = 0.0 stable_since = None manager_completed = False while time.monotonic() < deadline: rclpy.spin_once(node, timeout_sec=0.1) if process.poll() is not None: raise RuntimeError('stack exited') if time.monotonic()-last_check < 0.5: continue last_check = time.monotonic() if not processes and time.monotonic()-started > 8: processes = process_environment(process.pid) states = {} pending = {} for name, client in clients.items(): if not client.service_is_ready(): continue pending[name] = client.call_async(GetState.Request()) poll_end = time.monotonic()+1 while time.monotonic() < poll_end and any(not f.done() for f in pending.values()): rclpy.spin_once(node, timeout_sec=0.02) for name, future in pending.items(): if future.done() and future.result(): states[name] = future.result().current_state.id else: clients[name].remove_pending_request(future) log_path = args.output/'stack.log' text = log_path.read_text(errors='replace') if log_path.exists() else '' manager_completed = any('lifecycle_manager_nav2' in line and 'Managed nodes are active' in line for line in text.splitlines()) if all(states.get(name) == 3 for name in NODES) and counts['map_to_odom'] > 20 and manager_completed and health_events and health_events[-1][1]: if stable_since is None: stable_since = time.monotonic() if time.monotonic()-stable_since >= 2: reached_readiness = True break else: stable_since = None processes = process_environment(process.pid) names = sorted(set(node.get_node_names())) path_ready = path_client.wait_for_service(timeout_sec=2) path_response = None if path_ready: future = path_client.call_async(path_probe_request()) rclpy.spin_until_future_complete(node, future, timeout_sec=3) if future.done() and future.result() is not None: path_response = str(future.result()) manager_active = False if active_client.wait_for_service(timeout_sec=1): future = active_client.call_async(Trigger.Request()) rclpy.spin_until_future_complete(node, future, timeout_sec=2) manager_active = bool(future.done() and future.result() and future.result().success) managed_nodes = [] if parameter_client.wait_for_service(timeout_sec=1): future = parameter_client.call_async(GetParameters.Request(names=['node_names'])) rclpy.spin_until_future_complete(node, future, timeout_sec=2) if future.done() and future.result() and future.result().values: managed_nodes = list(future.result().values[0].string_array_value) result = {'launcher': args.launcher, 'startup_seconds': time.monotonic()-started, 'startup_attempts': sum('startup attempt ' in line for line in text.splitlines()), 'rmw': get_rmw_implementation_identifier(), 'processes': processes, 'node_counts': dict(Counter(node.get_node_names())), 'services': dict(node.get_service_names_and_types()), 'path_service_endpoints': {'servers': list(map(str, node.get_servers_info_by_service('/is_path_valid'))), 'clients': list(map(str, node.get_clients_info_by_service('/is_path_valid')))}, 'is_path_valid_discovered': path_ready, 'is_path_valid_response': path_response, 'topic_qos': { topic: [{'node': p.node_name, 'reliability': str(p.qos_profile.reliability)} for p in node.get_publishers_info_by_topic(topic)] for topic in dict.fromkeys(('/scan/points', '/scan/points_filtered', args.lio_cloud_topic, '/imu')) }, 'manager_active': manager_active, 'managed_nodes': managed_nodes, 'manager_completed': manager_completed, 'lifecycle_states': states, 'amcl_present': 'amcl' in names, 'lio_present': 'field_localization' in names, 'map_to_odom_publishers': len(publishers), **counts} result['passed'] = (reached_readiness and manager_completed and manager_active and path_response is not None and bool(managed_nodes) and all(states.get(name) == 3 for name in managed_nodes) and all(states.get(name) == 3 for name in NODES) and not result['amcl_present'] and result['lio_present'] and len(publishers) == 1 and counts['map_to_odom'] > 0 and counts['map_to_base_link'] == 0) if grid is not None and result['passed']: coverage = check_field_coverage(node, grid) result['field_coverage'] = coverage print(f'field coverage: {coverage["planned"]}/{coverage["sample_count"]} representative goals planned', flush=True) (args.output/'result.json').write_text(json.dumps(result, indent=2)) if args.scenario in ('cylinder','blocked') and result['passed']: # Obstacle lies on the initial straight corridor; a route around the cylinder exists. shape = f'{args.obstacle_radius}0.8' pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0' if args.scenario == 'blocked': shape = '1.6 1.6 0.8' pose = '0 0 0.4 0 0 0' sdf = f'true{pose}{shape}{shape}' gz = project_env.run_gz(gz_exe, 'service', '-s', '/world/rmul_arena/create', '--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000', '--req', 'sdf: '+json.dumps(sdf), timeout=10) (args.output/'obstacle.log').write_text(gz.stdout+gz.stderr) if gz.returncode or 'data: true' not in gz.stdout: raise RuntimeError('obstacle insertion failed') until=time.monotonic()+2 while time.monotonic()= 5 and actuator and sum(abs(v) for v in actuator[-1][1:]) > 0.1): owned = process_environment(process.pid) sensors = [p['pid'] for p in owned if p['executable'] and Path(p['executable'][0]).name == 'self_filter'] if len(sensors) != 1: raise RuntimeError('cannot identify the owned self_filter for fault injection') fault_time = time.monotonic() os.kill(sensors[0], signal.SIGTERM) timed_out = goal.poll() is None if timed_out: os.killpg(goal.pid, signal.SIGINT) goal.wait(timeout=5) goal_end_wall = time.monotonic() spin_for(0.3) goal_end_sim = sim_now() output = goal_log.read_text() truth_goal = [row for row in samples['truth'] if goal_start_sim <= row[0] <= goal_end_sim] estimate_goal = [row for row in samples['estimate'] if goal_start_sim <= row[0] <= goal_end_sim] leg = { 'goal': target, 'goal_exit_code': goal.returncode, 'goal_succeeded': not timed_out and goal.returncode == 0 and '结果: ✅ SUCCEEDED' in output, 'goal_elapsed_wall_sec': goal_end_wall-goal_start_wall, 'start_sim': goal_start_sim, 'end_sim': goal_end_sim, 'timed_out': timed_out, 'trajectory_metrics': metrics(estimate_goal, truth_goal), 'truth_goal_error_m': math.hypot(truth_goal[-1][1]-target[0], truth_goal[-1][2]-target[1]) if truth_goal else None, 'minimum_cylinder_clearance_m': min(cylinder_clearance(row, args.obstacle_x, args.obstacle_y, args.obstacle_radius) for row in truth_goal) if truth_goal and args.scenario == 'cylinder' else None, 'health_failures_during_goal': sum(not value for stamp, value in health_events if goal_start_wall <= stamp <= goal_end_wall), } if args.scenario == 'blocked': stopped = bool(actuator and actuator[-1][0] > goal_end_wall and actuator[-1][1:] == (0, 0, 0)) result['blocked_zero_output'] = stopped leg['passed'] = (not timed_out and '结果: ❌ ABORTED' in output and stopped and leg['health_failures_during_goal'] == 0 and leg['truth_goal_error_m'] is not None and leg['truth_goal_error_m'] > 0.30) elif args.scenario == 'lidar_loss': spin_for(0.7) stops = [t for t, x, y, z in actuator if fault_time is not None and t >= fault_time and x == y == z == 0] delay = min(stops)-fault_time if stops else None lost = next((event for event in health_transitions if fault_time is not None and event['wall'] >= fault_time and not event['valid']), None) canceled = '结果: ❌ CANCELED' in output # Once TF stops, FollowPath can complete with TF_ERROR before the relay's # cancel request returns. Both outcomes terminate the in-flight goal. tf_abort = ('结果: ❌ ABORTED' in output and f'Nav2 error_code={FollowPath.Result.TF_ERROR} ' in output) terminated = bool(lost and lost['wall'] <= goal_end_wall and (canceled or tf_abort)) result.update(fault_goal_canceled=canceled, fault_goal_tf_aborted=tf_abort, fault_goal_terminated=terminated, fault_stop_delay_sec=delay, fault_tf_halted=bool(lost and last_map_tf_wall is not None and last_map_tf_wall <= lost['wall']+0.1)) if lost: retry_log = args.output/'retry_invalid_localization.log' with retry_log.open('w') as stream: retry = subprocess.run(command, stdout=stream, stderr=subprocess.STDOUT, timeout=20) retry_text = retry_log.read_text() result['invalid_retry_blocked'] = (retry.returncode != 0 and '定位不可用' in retry_text and '目标已接受' not in retry_text) else: result['invalid_retry_blocked'] = False leg['passed'] = (terminated and not timed_out and delay is not None and delay < 0.5 and result['fault_tf_halted'] and result['invalid_retry_blocked']) else: leg['passed'] = (leg['goal_succeeded'] and leg['truth_goal_error_m'] is not None and leg['truth_goal_error_m'] <= 0.30 and (leg['minimum_cylinder_clearance_m'] is None or leg['minimum_cylinder_clearance_m'] > 0)) quality = leg['trajectory_metrics'] leg['passed'] = (leg['passed'] and quality['matched'] > 100 and quality['rpe_pairs'] > 0 and quality['maximum_position_error_m'] < 0.25 and quality['ate_translation_m'] < 0.1) legs.append(leg) result.update(leg) result['legs'] = legs (args.output/'result.json').write_text(json.dumps(result, indent=2)) print(f'leg {index+1}/{len(route)} {tuple(target)}: passed={leg["passed"]} ' f'goal={leg["goal_succeeded"]} max_error={quality["maximum_position_error_m"]}', flush=True) if multileg and not leg['goal_succeeded']: spin_for(8) break result.update(counts) result['map_to_odom_publishers'] = len(publishers) result['amcl_present'] = 'amcl' in node.get_node_names() # Include drift during the pauses, but keep each goal's outcome independent. if multileg: end_sim = legs[-1]['end_sim'] quality = metrics(*([row for row in samples[name] if start_sim <= row[0] <= end_sim] for name in ('estimate', 'truth'))) result['trajectory_metrics'] = quality result['first_localization_loss'] = next( (event for event in health_transitions if event['wall'] >= start_wall and not event['valid']), None) clearances = [leg['minimum_cylinder_clearance_m'] for leg in legs if leg['minimum_cylinder_clearance_m'] is not None] result['minimum_cylinder_clearance_m'] = min(clearances) if clearances else None result['passed'] = (quality['maximum_position_error_m'] is not None and quality['maximum_position_error_m'] < 0.25 and quality['ate_translation_m'] < 0.1 and result['first_localization_loss'] is None) if grid is not None: result['passed'] = (result['passed'] and coverage['sample_count'] > 0 and coverage['planned'] == coverage['sample_count']) result['passed'] = (result['passed'] and len(legs) == len(route) and all(leg['passed'] for leg in legs) and len(publishers) == 1 and counts['map_to_base_link'] == 0 and not result['amcl_present']) (args.output/'result.json').write_text(json.dumps(result, indent=2)) print(json.dumps({k: v for k, v in result.items() if k not in ('processes', 'services', 'node_counts', 'path_service_endpoints')}, indent=2), flush=True) if not result['passed']: raise RuntimeError('stack integration validation failed') except Exception as error: result.update(passed=False, error=str(error)) (args.output/'result.json').write_text(json.dumps(result, indent=2)) raise finally: _ = subscription, subscriptions, subscriptions_health, subscription_actuator (args.output/'health_events.json').write_text(json.dumps(health_events)) (args.output/'health_transitions.json').write_text(json.dumps(health_transitions, indent=2)) for name, rows in samples.items(): with open(args.output/(name+'.tum'),'w') as output: for row in rows: output.write(' '.join(map(str,row))+'\n') if goal is not None and goal.poll() is None: os.killpg(goal.pid, signal.SIGINT) try: goal.wait(timeout=5) except subprocess.TimeoutExpired: os.killpg(goal.pid, signal.SIGKILL) goal.wait() if recorder.poll() is None: os.killpg(recorder.pid, signal.SIGINT) try: recorder.wait(timeout=10) except subprocess.TimeoutExpired: os.killpg(recorder.pid, signal.SIGKILL) recorder.wait() record_log.close() if process.poll() is None: os.killpg(process.pid, signal.SIGINT) try: process.wait(timeout=20) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() if rviz is not None: os.killpg(rviz.pid, signal.SIGINT) try: rviz.wait(timeout=5) except subprocess.TimeoutExpired: os.killpg(rviz.pid, signal.SIGKILL) rviz.wait() if log: log.close() node.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()