test(localization): replay contact regressions and validate arena navigation
This commit is contained in:
1 parent
28ac7c488e
commit
0602144ac5
29 files changed
+762
-22
No files matched your search
@@ -0,0 +1,65 @@
|
||||
"""Independent-frame trajectory metrics; no alignment or ground-truth feedback."""
|
||||
import bisect
|
||||
import math
|
||||
|
||||
|
||||
def conjugate(q):
|
||||
return [-q[0],-q[1],-q[2],q[3]]
|
||||
|
||||
|
||||
def multiply(a,b):
|
||||
x,y,z,w=a;X,Y,Z,W=b
|
||||
return [w*X+x*W+y*Z-z*Y,w*Y-x*Z+y*W+z*X,w*Z+x*Y-y*X+z*W,w*W-x*X-y*Y-z*Z]
|
||||
|
||||
|
||||
def rotate(q,p):
|
||||
return multiply(multiply(q,[*p,0]),conjugate(q))[:3]
|
||||
|
||||
|
||||
def angle(q):
|
||||
return 2*math.acos(min(1,abs(q[3])/math.sqrt(sum(x*x for x in q))))
|
||||
|
||||
|
||||
def interpolate(rows,t,gap=0.05):
|
||||
i=bisect.bisect_left(rows,[t])
|
||||
if i<len(rows) and abs(rows[i][0]-t)<1e-8:return rows[i][1:]
|
||||
if i==0 or i==len(rows) or rows[i][0]-rows[i-1][0]>gap:return None
|
||||
a,b=rows[i-1],rows[i];u=(t-a[0])/(b[0]-a[0])
|
||||
p=[(1-u)*a[j]+u*b[j] for j in range(1,4)]
|
||||
sign=1 if sum(a[j]*b[j] for j in range(4,8))>=0 else -1
|
||||
q=[(1-u)*a[j]+u*sign*b[j] for j in range(4,8)];norm=math.sqrt(sum(x*x for x in q))
|
||||
return p+[x/norm for x in q]
|
||||
|
||||
|
||||
def metrics(estimate,truth):
|
||||
# A single pose per stamp; ordering changes never create false zero-duration RPE.
|
||||
estimate=sorted({row[0]:row for row in estimate}.values())
|
||||
truth=sorted({row[0]:row for row in truth}.values())
|
||||
translation=[];rotation=[];relative_t=[];relative_r=[]
|
||||
for row in estimate:
|
||||
t=row[0];e=row[1:];g=interpolate(truth,t)
|
||||
if g is None:continue
|
||||
translation.append(sum((e[j]-g[j])**2 for j in range(3)))
|
||||
rotation.append(angle(multiply(conjugate(g[3:]),e[3:]))**2)
|
||||
en=interpolate(estimate,t+1);gn=interpolate(truth,t+1)
|
||||
if en is None or gn is None:continue
|
||||
ep=rotate(conjugate(e[3:]),[en[j]-e[j] for j in range(3)])
|
||||
gp=rotate(conjugate(g[3:]),[gn[j]-g[j] for j in range(3)])
|
||||
relative_t.append(sum((ep[j]-gp[j])**2 for j in range(3)))
|
||||
eq=multiply(conjugate(e[3:]),en[3:]);gq=multiply(conjugate(g[3:]),gn[3:])
|
||||
relative_r.append(angle(multiply(conjugate(gq),eq))**2)
|
||||
def rmse(values):return math.sqrt(sum(values)/len(values)) if values else None
|
||||
return {'matched':len(translation),'total':len(estimate),'rpe_pairs':len(relative_t),
|
||||
'ate_translation_m':rmse(translation),'ate_rotation_deg':None if not rotation else math.degrees(rmse(rotation)),
|
||||
'rpe_1s_translation_m':rmse(relative_t),'rpe_1s_rotation_deg':None if not relative_r else math.degrees(rmse(relative_r)),
|
||||
'maximum_position_error_m':math.sqrt(max(translation)) if translation else None}
|
||||
|
||||
|
||||
def cylinder_clearance(row,x,y,radius):
|
||||
q=row[4:];yaw=math.atan2(2*(q[3]*q[2]+q[0]*q[1]),1-2*(q[1]*q[1]+q[2]*q[2]))
|
||||
dx,dy=x-row[1],y-row[2]
|
||||
bx=math.cos(yaw)*dx+math.sin(yaw)*dy;by=-math.sin(yaw)*dx+math.cos(yaw)*dy
|
||||
# Union of the actual SDF chassis and gimbal collision boxes.
|
||||
chassis=math.hypot(max(0,abs(bx)-0.289),max(0,abs(by)-0.2605))
|
||||
gimbal=math.hypot(max(0,abs(bx-0.12)-0.20),max(0,abs(by)-0.15))
|
||||
return min(chassis,gimbal)-radius
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run three cold starts per route/launcher, plus a blocked-goal check."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--launcher',choices=['shell','python'],required=True)
|
||||
parser.add_argument('--output',type=Path,required=True)
|
||||
parser.add_argument('--map',type=Path,required=True)
|
||||
parser.add_argument('--domain', type=int, choices=range(1, 233), metavar='[1–232]')
|
||||
parser.add_argument('--scenario', action='append', choices=['clear', 'cylinder', 'blocked', 'lidar_loss'])
|
||||
parser.add_argument('--repeats', type=int)
|
||||
args=parser.parse_args()
|
||||
if args.repeats is not None and args.repeats < 1:
|
||||
parser.error('repeats must be positive')
|
||||
if args.output.exists():parser.error('output must be new')
|
||||
args.output.mkdir(parents=True)
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
results=[]
|
||||
for scenario in args.scenario or ['clear', 'cylinder', 'blocked']:
|
||||
count = args.repeats if args.repeats is not None else (3 if scenario in ('clear', 'cylinder') else 1)
|
||||
for index in range(1, count+1):
|
||||
name=f'{scenario}_{index}';folder=args.output/name
|
||||
with open(args.output/(name+'.log'),'w') as log:
|
||||
command=[sys.executable,str(root/'tools/validate_lio_navigation.py'),
|
||||
'--launcher',args.launcher,'--map',str(args.map.resolve()),'--output',str(folder.resolve()),
|
||||
'--scenario',scenario,'--goal','0','0']
|
||||
if args.domain is not None:
|
||||
command.extend(['--domain', str(args.domain)])
|
||||
child=subprocess.Popen(command,cwd=root,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
|
||||
try:code=child.wait()
|
||||
except KeyboardInterrupt:
|
||||
child.send_signal(signal.SIGINT)
|
||||
child.wait(timeout=30)
|
||||
raise
|
||||
file=folder/'result.json'
|
||||
result=json.loads(file.read_text()) if file.exists() else {'passed':False,'error':'no result'}
|
||||
results.append({'name':name,'exit_code':code,**result})
|
||||
(args.output/'summary.json').write_text(json.dumps(results,indent=2))
|
||||
print(f'{args.launcher} {name}: passed={result.get("passed")} goal={result.get("goal_succeeded")} metrics={result.get("trajectory_metrics")}',flush=True)
|
||||
return 0 if all(r['passed'] and r['exit_code']==0 for r in results) else 1
|
||||
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user