test(localization): replay contact regressions and validate arena navigation

This commit is contained in:
mzx committed 2026-11-22 12:02:14 +08:00
1 parent 28ac7c488e
commit 0602144ac5
29 files changed
+762 -22

No files matched your search

+334
View File
@@ -0,0 +1,334 @@
#!/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 time
import uuid
from collections import Counter
import rclpy
from rclpy.node import Node
from rclpy.parameter import Parameter
from lifecycle_msgs.srv import GetState
from tf2_msgs.msg import TFMessage
from nav2_msgs.srv import IsPathValid
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
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
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--map', type=Path, required=True)
parser.add_argument('--launcher', choices=['shell', 'python'], default='shell')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--goal', nargs=2, type=float, metavar=('X', 'Y'))
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 not args.map.is_file():
parser.error('map missing')
if args.output.exists():
parser.error('output must be a new directory')
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(dds_defaults(os.environ))
workspace = Path(__file__).resolve().parents[1]
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],
'nav2_config_sha256': hashlib.sha256(params_file.read_bytes()).hexdigest(),
}
(args.output/'runtime.json').write_text(json.dumps(runtime, indent=2))
log = None
record_log = open(args.output/'record.log', 'w', encoding='utf8')
recorder = subprocess.Popen([str(workspace/'build/bin/field_localization_record'), '--ros-args',
'-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}/dataset',
'-p', 'duration_sec:=600.0'], 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=[]
actuator=[]
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',
lambda msg:health_events.append((time.monotonic(),msg.data)),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):
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
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 ['/scan/points','/scan/points_filtered','/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)
(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'<cylinder><radius>{args.obstacle_radius}</radius><length>0.8</length></cylinder>'
pose = f'{args.obstacle_x} {args.obstacle_y} 0.4 0 0 0'
if args.scenario == 'blocked':
shape = '<box><size>1.6 1.6 0.8</size></box>'
pose = '0 0 0.4 0 0 0'
sdf = f'<sdf version="1.9"><model name="validation_obstacle"><static>true</static><pose>{pose}</pose><link name="body"><collision name="collision"><geometry>{shape}</geometry></collision><visual name="visual"><geometry>{shape}</geometry></visual></link></model></sdf>'
gz = subprocess.run(['/usr/bin/gz', 'service', '-s', '/world/rmul_arena/create',
'--reqtype', 'gz.msgs.EntityFactory', '--reptype', 'gz.msgs.Boolean', '--timeout', '5000',
'--req', 'sdf: '+json.dumps(sdf)], capture_output=True,text=True,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()<until:
rclpy.spin_once(node,timeout_sec=0.02)
if args.goal and result['passed']:
goal_start_sim=node.get_clock().now().nanoseconds*1e-9
goal_start_wall=time.monotonic()
goal = subprocess.Popen([str(workspace/'build/bin/nav_client'), *map(str, args.goal), '0'],
stdout=open(args.output/'goal.log','w'), stderr=subprocess.STDOUT, text=True, start_new_session=True)
until=time.monotonic()+(240 if args.scenario=="blocked" else 120)
fault_time=None
while goal.poll() is None and time.monotonic()<until:
rclpy.spin_once(node,timeout_sec=0.02)
if args.scenario=='lidar_loss' and fault_time is None and time.monotonic()-goal_start_wall>=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)
if goal.poll() is None:
os.killpg(goal.pid,signal.SIGINT)
goal.wait(timeout=5)
goal.stdout_text=(args.output/'goal.log').read_text()
if args.scenario == 'blocked':
terminal_time = time.monotonic()
while time.monotonic() - terminal_time < 0.5:
rclpy.spin_once(node, timeout_sec=0.02)
result['blocked_zero_output'] = bool(
actuator and actuator[-1][0] > terminal_time and actuator[-1][1:] == (0, 0, 0)
)
result['passed'] = result['passed'] and result['blocked_zero_output']
result.update(counts)
result['map_to_odom_publishers'] = len(publishers)
result['amcl_present'] = 'amcl' in node.get_node_names()
result['passed'] = (result['passed'] and len(publishers) == 1
and counts['map_to_base_link'] == 0
and not result['amcl_present'])
result['goal_exit_code'] = goal.returncode
if args.scenario=='lidar_loss':
stops=[t for t,x,y,z in actuator if fault_time is not None and t>=fault_time and x==0 and y==0 and z==0]
result['fault_stop_delay_sec']=min(stops)-fault_time if stops else None
result['fault_goal_canceled']='结果: ❌ CANCELED' in goal.stdout_text
result['goal_succeeded'] = '结果: ✅ SUCCEEDED' in goal.stdout_text
result['goal_elapsed_wall_sec']=time.monotonic()-goal_start_wall
result['trajectory_metrics']=metrics(samples['estimate'],samples['truth'])
truth_goal=[row for row in samples['truth'] if row[0]>=goal_start_sim]
result['truth_goal_error_m']=math.hypot(truth_goal[-1][1]-args.goal[0],truth_goal[-1][2]-args.goal[1]) if truth_goal else None
result['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
result['health_failures_during_goal']=sum(not value for stamp,value in health_events if stamp>=goal_start_wall)
quality=result['trajectory_metrics']
result['passed']=result['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
if args.scenario not in ('blocked','lidar_loss'):
result['passed']=result['passed'] and result['truth_goal_error_m'] is not None and result['truth_goal_error_m']<=0.30
if result['minimum_cylinder_clearance_m'] is not None:
result['passed']=result['passed'] and result['minimum_cylinder_clearance_m']>=0
result['passed'] = result['passed'] and ((args.scenario == 'blocked' and '结果: ❌ ABORTED' in goal.stdout_text) or (args.scenario == 'lidar_loss' and result['fault_goal_canceled'] and result['fault_stop_delay_sec'] is not None and result['fault_stop_delay_sec']<0.5) or (goal.returncode == 0 and result['goal_succeeded']))
(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))
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()