完善双雷达仿真与自动上坡任务,更新使用文档

加入下置 MID360 前向补盲与双雷达融合,修复北侧走廊导航、坐标适配和数据时效处理。

实现接近坡脚、姿态辅助上坡与平台停车任务,增加独立快模式、命令仲裁及失效停车保护,保留测试与分阶段验收记录。

同步实车尺寸及雷达安装参数,调整 Gazebo 红方默认视角,完善根目录 README、仿真使用和实车迁移说明。
This commit is contained in:
2026-11-12 16:42:07 +08:00
parent cac93cae11
commit 6f1d837b46
95 changed files with 13667 additions and 244 deletions
+332
View File
@@ -0,0 +1,332 @@
#!/usr/bin/python3
"""Physical dual-MID360 perception, low-obstacle navigation and loss-stop acceptance."""
import argparse,hashlib,json,math,os,shlex,shutil,sys,time
from collections import deque
from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.srv import SpawnEntity
from geometry_msgs.msg import PoseStamped
from livox_ros_driver2.msg import CustomMsg
from sensor_msgs.msg import PointCloud2
from scan_planner_msgs.msg import Bspline
from rosidl_runtime_py.convert import message_to_ordereddict
from std_msgs.msg import String
from std_srvs.srv import Trigger
from rclpy.qos import qos_profile_sensor_data
from check_omni_robot import Sim,sim_env,shutdown_probe
import check_omni_robot
from ament_index_python.packages import get_package_share_directory,get_package_prefix
from check_lio_navigation import LioNavProbe,graph_evidence
from check_scan_navigation import run_goal
from check_mid360 import rotate,interpolate,json_value
from check_sim_lidar import points
LOW=np.array([.325,0.,.044]);UP=np.array([.015,0.,.33])
R_LOW=np.array([[0.,-1.,0.],[1.,0.,0.],[0.,0.,1.]])
SCENARIOS={
'front':(-math.pi/2,(-4.5,3.)),
'side_right':(0.,(-4.,3.)),
'side_left':(math.pi,(-5.,3.)),
'diagonal_right':(-math.pi/4,(-4.5,3.)),
'diagonal_left':(-3*math.pi/4,(-4.5,3.)),
}
def rectangle_gap(position,yaw,center):
"""SAT separation of oriented 0.8 m robot and axis-aligned 0.25 m box.
Positive values bound Euclidean clearance from below; nonpositive means
touching/overlap. Unlike the historical enclosing AABB, this respects yaw.
"""
c,s=math.cos(yaw),math.sin(yaw)
axes=np.array([[1.,0.],[0.,1.],[c,s],[-s,c]])
body_axes=np.array([[c,s],[-s,c]])
radii=.4*np.abs(axes@body_axes.T).sum(axis=1)+.125*np.abs(axes).sum(axis=1)
return float(np.max(np.abs(axes@(np.asarray(position[:2])-center))-radii))
def swept_clearance(states,center):
"""Conservative bound between truth samples, with <=2 mm corner steps.
Each interpolated half-step is padded by its maximum corner displacement.
This assumes linear position/shortest yaw between samples; raw samples and
their maximum gap are retained so it is not called continuous ground truth.
"""
minimum=float('inf');max_gap=0.
for a,b in zip(states,states[1:]):
max_gap=max(max_gap,b['stamp']-a['stamp'])
delta=np.asarray(b['pos'][:2])-a['pos'][:2]
angle=math.atan2(math.sin(b['yaw']-a['yaw']),math.cos(b['yaw']-a['yaw']))
travel=float(np.linalg.norm(delta))+.4*math.sqrt(2)*abs(angle)
steps=max(1,math.ceil(travel/.002))
for t in np.linspace(0.,1.,steps+1):
gap=rectangle_gap(np.asarray(a['pos'][:2])+t*delta,a['yaw']+t*angle,center)
minimum=min(minimum,gap-travel/(2*steps))
return dict(min_gap_bound_m=minimum,max_sample_gap_s=max_gap,
method='oriented SAT; interpolated poses padded by half-step corner travel')
def historical_wheel_overlay(out):
"""A/B diagnostic only: old unmeasured wheel proxy, never edit source/install.
A private ament prefix lets the normal launch load a copy of the old xacro.
The real sensor ray-intersection code is unchanged in both arms.
"""
package='r2027_robot_description';share=Path(get_package_share_directory(package))
prefix=out/'historical_model_overlay';target=prefix/'share'/package
target.mkdir(parents=True,exist_ok=False)
for child in share.iterdir():
if child.name=='sdf':shutil.copytree(child,target/child.name)
else:(target/child.name).symlink_to(child.resolve(),target_is_directory=child.is_dir())
model=target/'sdf'/'r2027_omni_robot.sdf.xacro';text=model.read_text()
old="${0.20 if '$(arg dual_lidar)'.lower() == 'true' else 0.30}"
if text.count(old)!=1:raise ValueError('historical wheel replacement no longer matches current source')
model.write_text(text.replace(old,'0.30'))
marker=prefix/'share'/'ament_index'/'resource_index'/'packages'/package
marker.parent.mkdir(parents=True);marker.touch()
(prefix/'lib').symlink_to(Path(get_package_prefix(package))/'lib',target_is_directory=True)
(prefix/'setup.bash').write_text('source '+shlex.quote(str(Path(check_omni_robot.INSTALL)/'setup.bash'))+'\n'+
'export AMENT_PREFIX_PATH='+shlex.quote(str(prefix))+':"$AMENT_PREFIX_PATH"\n')
check_omni_robot.INSTALL=str(prefix)
return dict(path=str(model),sha256=hashlib.sha256(model.read_bytes()).hexdigest(),wheel_x_m=.30)
def fields(m,names):
lookup={f.name:f for f in m.fields}
return [np.ndarray((m.height,m.width),dtype=('>' if m.is_bigendian else '<')+'f4',buffer=m.data,
offset=lookup[n].offset,strides=(m.row_step,m.point_step)).reshape(-1) for n in names]
def samples(m):
lookup={f.name:f for f in m.fields}
def read(name,dtype):return np.ndarray((m.height,m.width),dtype=dtype,buffer=m.data,offset=lookup[name].offset,strides=(m.row_step,m.point_step)).reshape(-1)
return read('time_sec','<i4').astype(np.int64)*1000000000+read('time_nanosec','<u4'),read('sensor_id','u1')
class DualProbe(LioNavProbe):
def __init__(self):
super().__init__();self.raw=[None,None];self.raw_recent=[deque(maxlen=25),deque(maxlen=25)];self.dual_status=[];self.fused=None;self.frames=[];self.collect=False
self.truth_poses=[]
self.diagnostic_center=None;self.fused_diagnostics=[]
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda m,i=i:self.on_raw(i,m),qos_profile_sensor_data)
self.create_subscription(PointCloud2,'/sim/navigation/fused_cloud',self.on_fused,qos_profile_sensor_data)
self.create_subscription(String,'/sim/dual_lidar/status',lambda m:self.dual_status.append(json.loads(m.data)),10)
def _on_odom(self,m):
super()._on_odom(m)
if m.header.frame_id!='odom' or m.child_frame_id!='base_link':raise ValueError('unexpected physical truth frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear
quaternion=[q.x,q.y,q.z,q.w]
self.truth_poses.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pos=[p.x,p.y,p.z],quaternion=quaternion,yaw=self.odom[-1]['yaw'],
twist_world=rotate(np.array(quaternion),np.array([v.x,v.y,v.z])).tolist(),wz=m.twist.twist.angular.z))
def on_raw(self,i,m):
self.raw[i]=m;self.raw_recent[i].append(m)
def on_fused(self,m):
self.fused=m
if self.collect:self.frames.append(m)
if self.diagnostic_center is not None:
xyz=points(m) if m.width*m.height else np.empty((0,3))
selected=(np.max(np.abs(xyz[:,:2]-self.diagnostic_center),axis=1)<.16)&(xyz[:,2]>.015)&(xyz[:,2]<.1)
self.fused_diagnostics.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
received=self.now(),points=xyz[selected].tolist()))
def raw_fixture_hits(m,state,i,center):
xyz=np.array([[p.x,p.y,p.z] for p in m.points]);local=xyz if i==0 else xyz@R_LOW.T
world=rotate(np.array(state['quaternion']),local+(UP if i==0 else LOW))+state['pos']
hit=(abs(world[:,0]-center[0])<.126)&(abs(world[:,1]-center[1])<.126)&(world[:,2]>.005)&(world[:,2]<.082)
return int(hit.sum())
def blocked_goal(p,x,y):
first=p.get_state();old=p.status[-1].goal_id;si=len(p.status);ci=len(p.commands)
goal=PoseStamped();goal.header.frame_id='world';goal.header.stamp=p.get_clock().now().to_msg()
goal.pose.position.x=x;goal.pose.position.y=y;goal.pose.position.z=.15;goal.pose.orientation.w=1.;p.goal_pub.publish(goal)
deadline=time.monotonic()+30
while time.monotonic()<deadline:
p.pump(.05)
if p.status[-1].goal_id>old and p.status[-1].state in (p.status[-1].FAILED,p.status[-1].SUCCEEDED):break
p.pump(1.1);last=p.get_state();status=p.status[-1]
checks=dict(rejected=status.goal_id>old and status.state==status.FAILED,
never_active=not any(s.state==s.ACTIVE for s in p.status[si:]),
stationary=math.dist(first['pos'],last['pos'])<.01,
zero_commands=all(math.hypot(c['vx'],c['vy'])<.01 and abs(c['wz'])<.02 for c in p.commands[ci:]))
return dict(checks=checks,ok=all(checks.values()),reason=status.reason,initial=first,final=last)
def loss_stop(p):
first=p.get_state();goal=PoseStamped();goal.header.frame_id='world';goal.header.stamp=p.get_clock().now().to_msg()
goal.pose.position.x=-4.5;goal.pose.position.y=4.5;goal.pose.position.z=.15;goal.pose.orientation.w=1.;p.goal_pub.publish(goal)
deadline=time.monotonic()+45
while time.monotonic()<deadline:
p.pump(.03);s=p.get_state()
if s and math.hypot(*s['twist_world'][:2])>.10:break
else:raise RuntimeError('no moving vehicle for lower-lidar fault')
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
if not cli.wait_for_service(timeout_sec=5):raise RuntimeError('missing independent lower disable service')
start=p.now();upper_before=int(p.raw[0].timebase);lower_before=int(p.raw[1].timebase)
response=p._call(cli,Trigger.Request(),timeout=5)
if not response or not response.success:raise RuntimeError('lower disable failed')
states=[];ready=[];t=p.now()
while p.now()-start<1.5:
p.pump(.02);states.append(p.get_state());ready.append(p.ready)
if any(s is None for s in states):raise RuntimeError('missing physical fault samples')
latency=next((s['stamp']-start for s in states if math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02),None)
late=[s for s in states if s['stamp']-start>.6]
checks=dict(lower_stopped=int(p.raw[1].timebase)-lower_before<=100000000,
upper_kept_running=int(p.raw[0].timebase)-upper_before>1000000000,
readiness_revoked=not all(ready) and not p.ready,stop_latency=latency is not None and latency<=.50,
stayed_stopped=all(math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02 for s in late),
stationary=all(math.dist(s['pos'],late[0]['pos'])<.02 for s in late))
return dict(ok=all(checks.values()),checks=checks,latency_sim_s=latency,truth=states)
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--gui',action='store_true')
ap.add_argument('--scenario',choices=SCENARIOS,default='front')
ap.add_argument('--diagnostics',action='store_true',help='record local map, planned splines and estimated/physical poses')
ap.add_argument('--historical-wheel-proxy',action='store_true',help='A/B evidence only: copy the old +/-0.30 m proxy into a private ament prefix')
ap.add_argument('--goal-y',type=float,default=1.5,help='world goal Y; retain historical route by default')
ap.add_argument('--goal-x',type=float,default=-4.5,help='world goal X; retain historical route by default')
ap.add_argument('--fixture-x',type=float,help='explicit world fixture X for additional routes; original scenarios stay unchanged')
ap.add_argument('--navigation-only',action='store_true',help='explicit navigation scope; independent lower-loss test is not executed')
args=ap.parse_args();heading,fixture_center=SCENARIOS[args.scenario]
if not all(math.isfinite(v) for v in (args.goal_x,args.goal_y)):ap.error('--goal-x/y must be finite')
if args.fixture_x is not None:
if not math.isfinite(args.fixture_x):ap.error('--fixture-x must be finite')
fixture_center=(args.fixture_x,fixture_center[1])
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True);os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report=dict(status='INVALID',checks={},scope='navigation_only' if args.navigation_only else 'navigation_and_loss_stop',scenario=args.scenario,fixture_center=list(fixture_center),requested_goal=[args.goal_x,args.goal_y,heading],collector_sha256=hashlib.sha256(source).hexdigest());sim=Sim(str(out/'sim'));p=None
try:
if args.historical_wheel_proxy:report['historical_model']=historical_wheel_overlay(out)
ok,why=sim.start(lio_navigation=True,dual_lidar=True,gui=args.gui,spawn=(-4.5,4.5,.15,heading));report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=DualProbe()
if not p.wait_clock():raise RuntimeError('no clock')
deadline=time.monotonic()+80
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if p.ready and p.status and p.fused is not None and all(m is not None for m in p.raw):break
else:raise RuntimeError('dual perception not ready')
report['graph']=graph_evidence(out,p,'/sim/navigation/fused_planning_cloud',extra_nodes=('/dual_lidar_fusion',))
checks=report['checks'];checks['no_truth_feedback']=report['graph']['ok']
mounts={t['child']:t for t in p.tf_static_raw if t['frame_id']=='base_link'}
lower_tf=mounts.get('lidar_low');checks['actual_lower_tf']=lower_tf is not None and np.allclose(lower_tf['translation'],LOW,atol=1e-9) and np.allclose(lower_tf['rotation'],[0,0,math.sqrt(.5),math.sqrt(.5)],atol=1e-9)
report['runtime_sensor_tf']=mounts
# Stationary controlled fixture: same physical entity observed by both.
center=np.array(fixture_center);req=SpawnEntity.Request();req.name='dual_low_obstacle';req.reference_frame='world'
if args.diagnostics:p.diagnostic_center=center
req.initial_pose.position.x=float(center[0]);req.initial_pose.position.y=float(center[1]);req.initial_pose.position.z=.04;req.initial_pose.orientation.w=1.
req.xml='<sdf version="1.6"><model name="dual_low_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.08</size></box></geometry></collision><visual name="box"><geometry><box><size>0.25 0.25 0.08</size></box></geometry></visual></link></model></sdf>'
response=p._call(p.spawn,req,timeout=15)
if not response or not response.success:raise RuntimeError('fixture spawn failed')
(out/'obstacle.sdf').write_text(req.xml)
maps=[];splines=[]
def on_map(m):
p.clouds['occupancy']=m
if args.diagnostics:
xyz=points(m) if m.width*m.height else np.empty((0,3))
near=(np.max(np.abs(xyz[:,:2]-center),axis=1)<2.)&(xyz[:,2]<.75)
maps.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
received=p.now(),points=xyz[near].tolist()))
sub=p.create_subscription(PointCloud2,'/grid_map/occupancy',on_map,qos_profile_sensor_data)
if args.diagnostics:
p.create_subscription(Bspline,'/planning/bspline',lambda m:splines.append(dict(received=p.now(),message=message_to_ordereddict(m))),10)
p.pump(1.);state=p.get_state();start_fixture_ns=round(p.now()*1e9)
p.frames.clear();p.collect=True;p.pump(2.);p.collect=False
hit_samples=[[raw_fixture_hits(m,state,i,center) for m in messages if m.timebase>=start_fixture_ns] for i,messages in enumerate(p.raw_recent)]
hits=[sum(v) for v in hit_samples]
report['raw_fixture_returns_per_frame']=hit_samples
checks['low_obstacle_only_seen_by_lower']=hits[0]==0 and hits[1]>=5;report['raw_fixture_returns']=hits
xyz=np.concatenate([points(m) for m in p.frames]);ids=np.concatenate([samples(m)[1] for m in p.frames]);report['fixture_fused_frames']=len(p.frames)
selected=(abs(xyz[:,0]-center[0])<.15)&(abs(xyz[:,1]-center[1])<.15)&(xyz[:,2]>.015)&(xyz[:,2]<.1)
checks['low_obstacle_fused']=len(p.frames)>=10 and int(np.count_nonzero(selected&(ids==1)))>=10
report['fused_fixture_returns_by_sensor']=[int(np.count_nonzero(selected&(ids==i))) for i in (0,1)]
if 'occupancy' not in p.clouds:raise RuntimeError('no independent map publication')
occupied=points(p.clouds['occupancy']);mapped=(abs(occupied[:,0]-center[0])<.16)&(abs(occupied[:,1]-center[1])<.16)&(occupied[:,2]>.015)&(occupied[:,2]<.125)
checks['low_obstacle_occupied']=int(mapped.sum())>0;report['occupied_fixture_voxels']=int(mapped.sum())
np.savez_compressed(out/'fixture.npz',fused=xyz,ids=ids,occupied=occupied)
if not args.diagnostics:p.destroy_subscription(sub);p.clouds.pop('occupancy',None)
report['blocked_goal']=blocked_goal(p,*center);checks['occupied_goal_rejected']=report['blocked_goal']['ok']
print('fixture checks',checks,flush=True)
# Capture fused samples and physical poses live; analyze only after motion.
p.frames.clear();p.collect=True;states=[p.get_state()]
route=run_goal(p,'low_obstacle_detour',args.goal_x,args.goal_y,heading,timeout=80.,goal_z=.15,settle_timeout=.2,sample_hook=states.append,sample_interval=.03)
p.collect=False
checks['navigation_around_low_obstacle']=route['ok']
clearances=[]
for s in route['samples']:
extent=.4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw'])))
clearances.append(max(abs(s['pos'][0]-center[0])-.125-extent,abs(s['pos'][1]-center[1])-.125-extent))
# /odom is the existing contact plugin's 100 Hz WorldPose stream. It is
# validation-only. Cross-check it against timestamped entity queries;
# no truth subscription or fallback is added to the running algorithms.
truth=[s for s in p.truth_poses if states[0]['stamp']-.05<=s['stamp']<=route['stop_samples'][-1]['stamp']+.05]
if len(truth)<2:raise RuntimeError('missing high-rate physical truth')
query_states=[s for s in states+route['braking_samples']+route['stop_samples'] if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
if len(query_states)<20:raise RuntimeError('insufficient independent truth service cross-checks')
query_times=np.array([s['stamp'] for s in query_states]);query_pos,query_q=interpolate(truth,query_times)
query_errors=np.linalg.norm(query_pos-np.array([s['pos'] for s in query_states]),axis=1)
query_angles=2*np.arccos(np.clip(np.abs(np.sum(query_q*np.array([s['quaternion'] for s in query_states]),axis=1)),0.,1.))
report['truth_service_agreement']=dict(source='contact plugin /odom: WorldPose at source simulation time; evaluation only',
samples=len(query_states),max_position_error_m=float(max(query_errors)),max_angle_error_rad=float(max(query_angles)))
checks['truth_service_agreement']=max(query_errors)<.002 and max(query_angles)<.005
exact=swept_clearance(truth,center)
report['oriented_swept_clearance']=exact
checks['physical_footprint_clearance']=bool(clearances) and exact['min_gap_bound_m']>.015 and exact['max_sample_gap_s']<=.12
route['min_low_obstacle_clearance_m']=min(clearances,default=None);report['navigation']=route
# Independent pose queries are requested every .03 sim seconds.
# Check physical origin alignment without using truth in any pipeline.
errors=[];fusion_errors=[];front=[];saved_origins=[];saved_estimated=[];saved_truth=[];saved_times=[];saved_ids=[]
estimated=[]
for m in p.nav_odom:
pos=m.pose.pose.position;q=m.pose.pose.orientation
estimated.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pos=[pos.x,pos.y,pos.z],quaternion=[q.x,q.y,q.z,q.w]))
for m in p.frames[::max(1,len(p.frames)//12)]:
ns,ids=samples(m);times=ns*1e-9;valid=(times>max(truth[0]['stamp'],estimated[0]['stamp']))&(times<min(truth[-1]['stamp'],estimated[-1]['stamp']))
take=np.flatnonzero(valid)[::max(1,int(valid.sum())//400)]
if not len(take):continue
pos,q=interpolate(truth,times[take]);origin=np.stack(fields(m,('origin_x','origin_y','origin_z')),axis=-1)[take]
mount=np.where(ids[take,None]==0,UP,LOW);expected=pos+rotate(q,mount)
errors.extend(np.linalg.norm(origin-expected,axis=1))
estimated_pos,estimated_q=interpolate(estimated,times[take])
expected_estimated=estimated_pos+rotate(estimated_q,mount)
fusion_errors.extend(np.linalg.norm(origin-expected_estimated,axis=1))
saved_origins.append(origin);saved_estimated.append(expected_estimated);saved_truth.append(expected);saved_times.append(ns[take]);saved_ids.append(ids[take])
world=points(m)[take];inverse=q.copy();inverse[:,:3]*=-1;directions=rotate(inverse,world-origin)
front.extend(directions[ids[take]==1,0])
if not errors:raise RuntimeError('no time-bracketed fusion origins')
np.savez_compressed(out/'motion_geometry.npz',origin=np.concatenate(saved_origins),expected_estimated=np.concatenate(saved_estimated),
expected_physical=np.concatenate(saved_truth),sample_ns=np.concatenate(saved_times),sensor_id=np.concatenate(saved_ids),
input_estimated_poses=np.array([[v['stamp'],*v['pos'],*v['quaternion']] for v in estimated]))
# Keep the existing independent Point-LIO position bound (.10 m);
# separately require sub-millimetre fusion algebra against its input.
checks['localization_origins_match_independent_truth']=float(np.max(errors))<.10
checks['fusion_origins_match_estimated_inputs']=float(np.max(fusion_errors))<.001
checks['front_sector_follows_vehicle']=len(front)>100 and float(np.quantile(front,.001))>-.05
report['motion_geometry']=dict(fusion_error_p95_m=float(np.quantile(fusion_errors,.95)),fusion_error_max_m=float(np.max(fusion_errors)),origin_error_p95_m=float(np.quantile(errors,.95)),origin_error_max_m=float(np.max(errors)),front_min_m=min(front,default=None),samples=len(errors))
print('navigation checks',checks,flush=True)
if args.navigation_only:report['lower_loss_stop']=dict(status='NOT_RUN',reason='explicit --navigation-only scope')
else:
report['lower_loss_stop']=loss_stop(p);checks['lower_loss_stop']=report['lower_loss_stop']['ok']
report['dual_status']=p.dual_status[-6:];report['status']='PASS' if all(checks.values()) else 'FAIL'
print(json.dumps(dict(status=report['status'],checks=checks),indent=2,default=json_value),flush=True)
except Exception as error:report['error']=repr(error);print(report['error'],flush=True)
finally:
if args.diagnostics and p is not None and 'maps' in locals():
(out/'diagnostics.json').write_text(json.dumps(dict(maps=maps,splines=splines,
fused_fixture=p.fused_diagnostics,
physical_poses=p.truth_poses,
navigation_health=p.navigation_status,fusion_health=p.dual_status,
estimated_poses=[message_to_ordereddict(m) for m in p.nav_odom]),default=json_value)+'\n')
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':sys.exit(main())
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/python3
"""Reproduce the user's north-corridor goal with estimated navigation only.
No fixture is added, no drive command is injected. Physical truth and map/cloud
snapshots are collected strictly by this evaluator, not fed to navigation.
"""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import time
import numpy as np
import rclpy
from sensor_msgs.msg import PointCloud2
from rclpy.qos import qos_profile_sensor_data
from scan_planner_msgs.msg import Bspline
from rosidl_runtime_py.convert import message_to_ordereddict
from check_dual_lidar import DualProbe
from check_lio_navigation import graph_evidence
from check_omni_robot import Sim,sim_env,shutdown_probe
from check_scan_navigation import run_goal
from check_sim_lidar import points
from check_mid360 import json_value,interpolate
class CorridorProbe(DualProbe):
def __init__(self):
super().__init__();self.snapshots=[];self.latest={};self.last_snapshot={};self.splines=[]
for topic in ('/grid_map/occupancy','/sim/navigation/fused_planning_cloud'):
self.create_subscription(PointCloud2,topic,lambda m,t=topic:self.capture(t,m),qos_profile_sensor_data)
self.create_subscription(Bspline,'/planning/bspline',lambda m:self.splines.append(
dict(received=self.now(),message=message_to_ordereddict(m))),10)
def on_fused(self,m):
super().on_fused(m)
self.capture('/sim/navigation/fused_cloud',m)
def capture(self,topic,m):
self.latest[topic]=m
if self.now()-self.last_snapshot.get(topic,-1)<.5:return
self.last_snapshot[topic]=self.now()
xyz=points(m) if m.width*m.height else np.empty((0,3))
finite=np.isfinite(xyz).all(1);roi=finite&(xyz[:,0]>-3.5)&(xyz[:,0]<4.5)&(xyz[:,1]>3.8)&(xyz[:,1]<5.6)&(xyz[:,2]>-.15)&(xyz[:,2]<.8)
self.snapshots.append(dict(topic=topic,source_stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
received=self.now(),frame=m.header.frame_id,points=xyz[roi].tolist()))
def verify_physical_corridor(p,route):
"""Independent source-stamped truth, checked against the entity service.
Production geometry: stair/ramp north edge <=Y=4, outer wall inner face
Y=5.5. Conservatively extend the Y=4 barrier across X=-3..3, including the
parts where the actual platform ends earlier. No runtime obstacle is added.
"""
first=route['samples'][0]['stamp'];last=route['stop_samples'][-1]['stamp']
truth=[s for s in p.truth_poses if first-.05<=s['stamp']<=last+.05]
if len(truth)<20:raise RuntimeError('insufficient high-rate physical samples')
queries=[s for s in route['samples'] if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
if len(queries)<20:raise RuntimeError('insufficient independent entity queries')
pos,q=interpolate(truth,np.array([s['stamp'] for s in queries]))
errors=np.linalg.norm(pos-np.array([s['pos'] for s in queries]),axis=1)
angles=2*np.arccos(np.clip(abs(np.sum(q*np.array([s['quaternion'] for s in queries]),axis=1)),0.,1.))
clearance=[];max_gap=0.
for a,b in zip(truth,truth[1:]):
max_gap=max(max_gap,b['stamp']-a['stamp'])
angle=abs(math.atan2(math.sin(b['yaw']-a['yaw']),math.cos(b['yaw']-a['yaw'])))
travel=math.dist(a['pos'][:2],b['pos'][:2])+.4*math.sqrt(2)*angle
for s in (a,b):
extent=.4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw'])))
if s['pos'][0]+extent>=-3. and s['pos'][0]-extent<=3.:
clearance.append(min(s['pos'][1]-extent-4.,5.5-s['pos'][1]-extent)-travel/2)
route['corridor_physics']=dict(minimum_gap_bound_m=min(clearance,default=None),
max_truth_gap_s=max_gap,query_samples=len(queries),max_query_position_error_m=float(max(errors)),
max_query_angle_error_rad=float(max(angles)),band_y_m=[4.,5.5],scope='flat corridor envelope; linear interpolation bound between truth samples')
route['checks']['crossed_north_corridor']=route['samples'][-1]['pos'][0]>3.
route['checks']['physical_clearance']=bool(clearance) and min(clearance)>=.03
route['checks']['truth_service_agreement']=max(errors)<.002 and max(angles)<.005 and max_gap<=.12
route['ok']=all(route['checks'].values())
def main():
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--out',required=True)
ap.add_argument('--repeat',type=int,default=1);ap.add_argument('--single-lidar',action='store_true')
ap.add_argument('--spawn-x',type=float,default=-4.5);ap.add_argument('--spawn-y',type=float,default=4.5)
ap.add_argument('--goal-x',type=float,default=3.5);ap.add_argument('--goal-y',type=float,default=4.8)
args=ap.parse_args()
if args.repeat<1:ap.error('--repeat must be positive')
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
report=dict(status='INVALID',cases=[],goal=[args.goal_x,args.goal_y,.15,0.],dual_lidar=not args.single_lidar,
collector_sha256=hashlib.sha256(source).hexdigest());sim=Sim(str(out/'sim'));p=None
root=Path(__file__).resolve().parents[2]
report['source_sha256']={f:hashlib.sha256((root/f).read_bytes()).hexdigest() for f in (
'sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py',
'sim_ws/src/br_sim_bringup/config/dual_lidar.yaml',
'sim_ws/src/br_sim_bringup/config/scan_sim.yaml')}
try:
ok,why=sim.start(lio_navigation=True,dual_lidar=not args.single_lidar,
spawn=(args.spawn_x,args.spawn_y,.15,0.));report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=CorridorProbe()
if not p.wait_clock():raise RuntimeError('clock unavailable')
deadline=time.monotonic()+90
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if p.ready and p.status and p.goal_pub.get_subscription_count()>=2:break
else:raise RuntimeError('navigation never became ready')
planning='/sim/navigation/planning_cloud' if args.single_lidar else '/sim/navigation/fused_planning_cloud'
report['graph']=graph_evidence(out,p,planning,extra_nodes=() if args.single_lidar else ('/dual_lidar_fusion',))
for i in range(args.repeat):
route=run_goal(p,'north_corridor_%d'%(i+1),args.goal_x,args.goal_y,0.,timeout=100.,
goal_z=.15,settle_timeout=.2,sample_interval=.05)
verify_physical_corridor(p,route)
report['cases'].append(route)
print('attempt',i+1,'ok',route['ok'],'checks',route['checks'],'arrival',route['position_error_m'],flush=True)
if route['ok']:break
report['status']='PASS' if report['graph']['ok'] and report['cases'][-1]['ok'] else 'FAIL'
except Exception as exc:
report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:
(out/'diagnostics.json').write_text(json.dumps(dict(snapshots=p.snapshots,splines=p.splines,
estimated_poses=[message_to_ordereddict(m) for m in p.nav_odom],physical_poses=p.truth_poses,
navigation_health=p.navigation_status,fusion_health=p.dual_status),default=json_value)+'\n')
for topic,m in p.latest.items():
np.savez_compressed(out/(topic.strip('/').replace('/','_')+'.npz'),xyz=points(m) if m.width*m.height else np.empty((0,3)),
stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9)
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':raise SystemExit(main())
+150 -27
View File
@@ -1,11 +1,15 @@
#!/usr/bin/python3
"""Independent physical acceptance of LIO reference-path navigation on known ramps."""
import argparse,hashlib,json,math,os,signal,sys,time
from collections import deque
from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.msg import ContactsState
from gazebo_msgs.srv import SpawnEntity
from std_srvs.srv import Trigger
from std_msgs.msg import String
from livox_ros_driver2.msg import CustomMsg
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Path as NavPath
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
@@ -20,21 +24,61 @@ def height(x):return 0. if x>=2.7 else (.6 if x<=-.8 else (1.6119-.597*x)/3.5)
class TerrainProbe(LioNavProbe):
def __init__(self,out):
def __init__(self,out,dual=False):
super().__init__();self.out=out;self.contacts=[];self.snapshots=[];self.next_snapshot=0.
self.dual=dual;self.raw=[None,None];self.dual_status=[];self.metadata_checks=[];self.truth_poses=[]
self.paired_clouds=deque(maxlen=50);self.pending_cloud_pairs={}
if dual:
for topic in ('/sim/navigation/fused_cloud','/sim/navigation/fused_planning_cloud','/sim/navigation/terrain_planning_cloud'):
self.create_subscription(PointCloud2,topic,lambda m,topic=topic:self.on_dual_cloud(topic,m),qos_profile_sensor_data)
for i,topic in enumerate(('/sim/mid360/lidar','/sim/mid360_low/lidar')):
self.create_subscription(CustomMsg,topic,lambda m,i=i:self.raw.__setitem__(i,m),qos_profile_sensor_data)
self.create_subscription(String,'/sim/dual_lidar/status',lambda m:self.dual_status.append(json.loads(m.data)),10)
self.path_pub=self.create_publisher(NavPath,'/initial_path',QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.create_subscription(ContactsState,'/sim/drive_contacts',self.contacts.append,100)
def on_dual_cloud(self,topic,m):
self.clouds[topic]=m
if topic=='/sim/navigation/terrain_planning_cloud':return
ns=m.header.stamp.sec*1000000000+m.header.stamp.nanosec
pair=self.pending_cloud_pairs.setdefault(ns,{})
pair[topic]=m
if len(pair)==2:
self.paired_clouds.append((ns,pair['/sim/navigation/fused_cloud'],pair['/sim/navigation/fused_planning_cloud']))
del self.pending_cloud_pairs[ns]
for key in sorted(self.pending_cloud_pairs)[:-20]:del self.pending_cloud_pairs[key]
def _on_odom(self,m):
super()._on_odom(m)
if m.header.frame_id!='odom' or m.child_frame_id!='base_link':raise ValueError('unexpected physical truth frames')
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear
quaternion=np.array([q.x,q.y,q.z,q.w]);yaw=self.odom[-1]['yaw']
roll=math.atan2(2*(q.w*q.x+q.y*q.z),1-2*(q.x*q.x+q.y*q.y))
pitch=math.asin(np.clip(2*(q.w*q.y-q.z*q.x),-1.,1.))
self.truth_poses.append(dict(stamp=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
pos=[p.x,p.y,p.z],quaternion=quaternion.tolist(),yaw=yaw,rpy=[roll,pitch,yaw],
twist_world=rotate(quaternion,np.array([v.x,v.y,v.z])).tolist(),wz=m.twist.twist.angular.z))
def capture(self):
if self.now()<self.next_snapshot:return
full=self.clouds.get('/sim/navigation/cloud_registered');filtered=self.clouds.get('/sim/navigation/planning_cloud')
full=self.clouds.get('/sim/navigation/fused_cloud' if self.dual else '/sim/navigation/cloud_registered')
filtered=self.clouds.get('/sim/navigation/fused_planning_cloud' if self.dual else '/sim/navigation/planning_cloud')
if full is None or filtered is None or full.header.stamp!=filtered.header.stamp:return
self.next_snapshot=self.now()+1.
name='cloud_%03d.npz'%len(self.snapshots)
np.savez_compressed(self.out/name,world=points(full),filtered=points(filtered))
self.snapshots.append(dict(file=name,stamp=full.header.stamp.sec+full.header.stamp.nanosec*1e-9))
if self.dual:
final=self.clouds.get('/sim/navigation/terrain_planning_cloud')
if final is not None and final.header.stamp==filtered.header.stamp:
def read(m,offset,dtype):return np.ndarray((m.width,),dtype=dtype,buffer=m.data,offset=offset,strides=(m.point_step,))
real_ids=read(full,32,'u1');ids=read(final,32,'u1');prior=ids==255
same=bytes(final.data[:len(filtered.data)])==bytes(filtered.data)
metadata=all(bytes(full.data[i*33+12:(i+1)*33])==bytes(filtered.data[i*33+12:(i+1)*33]) for i in range(full.width))
zero_rays=all(np.array_equal(read(final,i*4,'<f4')[prior],read(final,(i+3)*4,'<f4')[prior]) for i in range(3))
zero_time=all((read(final,offset,dtype)[prior]==0).all() for offset,dtype in ((24,'<i4'),(28,'<u4')))
self.metadata_checks.append(dict(stamp=self.now(),both_sources=bool((real_ids==0).any() and (real_ids==1).any()),
real_bytes_preserved=same,filter_metadata_preserved=metadata,explicit_prior_ids=bool(prior.any()),zero_length_priors=zero_rays,prior_has_no_acquisition_time=zero_time))
def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None,lower_loss=False):
old_id=p.status[-1].goal_id if p.status else 0;si=len(p.status);ci=len(p.commands);ki=len(p.contacts);ei=len(p.nav_odom)
first=p.get_state()
if first is None:raise RuntimeError('missing initial independent truth')
@@ -50,17 +94,32 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
if s is None:raise RuntimeError('missing physical state')
states.append(s);readiness.append(dict(t=p.now(),ready=p.ready));p.capture()
if fault_sim is not None and not fault and 1.2<s['pos'][0]<1.8 and math.hypot(*s['twist_world'][:2])>.08:
candidates=[pid for pid in fault_sim.known if fault_sim.owns(pid) and b'/step_blocker' in Path('/proc/%d/cmdline'%pid).read_bytes()]
if len(candidates)!=1:raise RuntimeError('cannot identify one owned step_blocker')
pid=candidates[0];fault.update(start=p.now(),owned_pid=pid,samples=[],readiness=[])
pid=None
if not lower_loss:
candidates=[pid for pid in fault_sim.known if fault_sim.owns(pid) and b'/step_blocker' in Path('/proc/%d/cmdline'%pid).read_bytes()]
if len(candidates)!=1:raise RuntimeError('cannot identify one owned step_blocker')
pid=candidates[0]
fault.update(start=p.now(),owned_pid=pid,kind='lower_lidar_loss' if lower_loss else 'downstream_loss',samples=[],readiness=[])
if lower_loss:
fault['upper_before']=int(p.raw[0].timebase);fault['lower_before']=int(p.raw[1].timebase)
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
if not cli.wait_for_service(timeout_sec=5):raise RuntimeError('missing lower disable service')
response=p._call(cli,Trigger.Request(),timeout=5)
if not response or not response.success:raise RuntimeError('lower disable failed')
try:
os.kill(pid,signal.SIGSTOP)
if pid is not None:os.kill(pid,signal.SIGSTOP)
while p.now()-fault['start']<.8:
p.pump(.04);held=p.get_state()
if held is None:raise RuntimeError('missing independent fault state')
states.append(held);fault['samples'].append(held);fault['readiness'].append(dict(t=p.now(),ready=p.ready));p.capture()
finally:
if fault_sim.owns(pid):os.kill(pid,signal.SIGCONT)
if lower_loss:
fault['upper_after']=int(p.raw[0].timebase);fault['lower_after']=int(p.raw[1].timebase)
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/profile/'+p.sensor_profile)
if not cli.wait_for_service(timeout_sec=5):raise RuntimeError('missing lower enable service')
response=p._call(cli,Trigger.Request(),timeout=5)
if not response or not response.success:raise RuntimeError('lower enable failed')
elif fault_sim.owns(pid):os.kill(pid,signal.SIGCONT)
fault['resumed']=p.now()
status=p.status[-1] if p.status else None
if status and status.goal_id>old_id and status.state in (status.SUCCEEDED,status.FAILED):break
@@ -77,19 +136,33 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
if s is None:raise RuntimeError('missing stopped state')
rest.append(s);p.capture()
statuses=p.status[si:];commands=p.commands[ci:];contacts=p.contacts[ki:];states+=braking+rest
# Dense plugin WorldPose is evaluation-only. Independently cross-check it
# against timestamped service responses, then use it to bracket estimates.
service_states=states
dense=[s for s in p.truth_poses if first['stamp']-.05<=s['stamp']<=states[-1]['stamp']+.05]
if len(dense)<20:raise RuntimeError('missing dense independent physical poses')
queries=[s for s in states if dense[0]['stamp']<=s['stamp']<=dense[-1]['stamp']]
if len(queries)<20:raise RuntimeError('insufficient service cross-checks')
qp,qq=interpolate(dense,[s['stamp'] for s in queries])
position_error=np.linalg.norm(qp-np.array([s['pos'] for s in queries]),axis=1)
angle_error=2*np.arccos(np.clip(np.abs(np.sum(qq*np.array([s['quaternion'] for s in queries]),axis=1)),0.,1.))
states=[s for s in dense if first['stamp']<=s['stamp']<=service_states[-1]['stamp']]
truth_gap=max(np.diff([s['stamp'] for s in states]))
# Align estimated and physical reference points only by their timestamps.
ts=[s['stamp'] for s in states];est=[m for m in p.nav_odom[ei:] if ts[0]<=m.header.stamp.sec+m.header.stamp.nanosec*1e-9<=ts[-1]]
if len(est)<(20 if blocked else 100):raise RuntimeError('not enough estimator/truth pairs')
times=np.array([m.header.stamp.sec+m.header.stamp.nanosec*1e-9 for m in est]);pos,q=interpolate(states,times)
estimated=np.array([[m.pose.pose.position.x,m.pose.pose.position.y,m.pose.pose.position.z] for m in est]);errors=estimated-pos
matrices=np.stack([rotate(np.broadcast_to(np.array(s['quaternion']),(3,4)),np.eye(3)).T for s in states])
extent=np.abs(matrices[:,1,:])@np.array([.4,.4,.15])
physical_y=np.array([s['pos'][1] for s in states])
# Conservative whole-vehicle bounds: local z=[-.15,+.26], not symmetric.
extent=np.abs(matrices[:,1,:])@np.array([.4,.4,.205])
physical_y=np.array([s['pos'][1] for s in states])+.055*matrices[:,1,2]
clearance=np.minimum(np.abs(physical_y)-3.025-extent,4.-np.abs(physical_y)-extent)
xy_error=math.hypot(rest[-1]['pos'][0]-xs[-1],rest[-1]['pos'][1]-target_y)
drift=max(math.dist(s['pos'],rest[0]['pos']) for s in rest)
mid=[s for s in states if -.35<s['pos'][0]<2.2]
checks=dict(acknowledged=status.goal_id>old_id,state_as_expected=status.state==(status.FAILED if blocked else status.SUCCEEDED),
truth_crosschecked=max(position_error)<.002 and max(angle_error)<.005 and truth_gap<=.12,
perception_fresh=p.ready,original_goal_preserved=abs(status.goal.x-xs[-1])<1e-6 and abs(status.goal.y-target_y)<1e-6 and abs(status.goal.z-(msg.poses[-1].pose.position.z+.15))<1e-6,
stopped=drift<.02 and all(math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02 for s in rest),
bounded_braking=latency is not None and 0<=latency<=.2,
@@ -103,13 +176,15 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
downstream_stop_in_time=stopped is not None and 0<=stopped<=.5,
downstream_held_still=bool(late) and all(math.hypot(*s['twist_world'][:2])<.01 and math.dist(s['pos'],late[0]['pos'])<.02 for s in late),
downstream_new_grant='resumed' in fault and any(s.header.stamp.sec+s.header.stamp.nanosec*1e-9>fault['resumed'] and s.state==s.ACTIVE for s in statuses))
if lower_loss:checks.update(upper_continues_during_lower_loss=fault['upper_after']-fault['upper_before']>=500000000,
lower_really_stopped=fault['lower_after']-fault['lower_before']<=100000000)
if blocked:
checks.update(never_active=not any(s.state==s.ACTIVE for s in statuses),stationary=max(math.dist(s['pos'],first['pos']) for s in states)<.02,
zero_commands=bool(commands) and all(max(abs(c[k]) for k in ('vx','vy','wz'))<1e-6 for c in commands))
else:
checks.update(active=any(s.state==s.ACTIVE for s in statuses),physical_arrival=xy_error<.10,
physical_height=abs(rest[-1]['pos'][2]-(height(xs[-1])+.15))<.03,
ramp_pitch=bool(mid) and max(abs(s['rpy'][1]-math.atan2(.597,3.5)) for s in mid)<.05,
ramp_pitch=bool(mid) and max(abs(s['rpy'][1]-math.cos(first['yaw'])*math.atan2(.597,3.5)) for s in mid)<.05,
ramp_height=bool(mid) and max(abs(s['pos'][2]-(height(s['pos'][0])+.15)) for s in mid)<.04,
lane=max(abs(s['pos'][1]-y) for s in states)<.03,
full_body_clearance=float(min(clearance))>.04,
@@ -122,8 +197,9 @@ def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
maximum_depth_m=max((d for m in contacts for c in m.states for d in c.depths),default=None),
collision_pairs=sorted({(c.collision1_name,c.collision2_name) for m in contacts for c in m.states})),
fault_event=fault,
truth_service_agreement=dict(samples=len(queries),max_position_error_m=float(max(position_error)),max_angle_error_rad=float(max(angle_error)),max_dense_gap_s=float(truth_gap)),
estimation_pairs=[dict(stamp=float(t),estimate=e.tolist(),truth_interpolated=g.tolist()) for t,e,g in zip(times,estimated,pos)],
input_path=[[s.pose.position.x,s.pose.position.y,s.pose.position.z] for s in msg.poses],samples=states,
input_path=[[s.pose.position.x,s.pose.position.y,s.pose.position.z] for s in msg.poses],samples=states,service_samples=service_states,
stopped_samples=rest,braking_samples=braking,readiness=readiness,commands=commands,
statuses=[dict(t=s.header.stamp.sec+s.header.stamp.nanosec*1e-9,state=s.state,reason=s.reason,traj_id=s.traj_id,goal_id=s.goal_id) for s in statuses])
@@ -132,59 +208,106 @@ def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--side',choices=('red','blue'),default='red')
group=ap.add_mutually_exclusive_group();group.add_argument('--up-only',action='store_true');group.add_argument('--obstacle-only',action='store_true')
ap.add_argument('--planning-loss',action='store_true')
ap.add_argument('--dual-lidar',action='store_true')
ap.add_argument('--lower-loss',action='store_true',help='disable only lower lidar during uphill; verify stop and same-task recovery')
ap.add_argument('--yaw',type=float,default=0.,help='initial heading; pi faces the front-only lower lidar uphill')
ap.add_argument('--obstacle-height',type=float,default=.6)
ap.add_argument('--obstacle-slope-aligned',action='store_true',help='explicit additional fixture: box bottom parallel to ramp, height measured normal to surface')
ap.add_argument('--sensor-profile',choices=('ideal','mild','stress'),default='ideal')
args=ap.parse_args()
if not math.isfinite(args.yaw) or abs(math.sin(args.yaw))>1e-5:ap.error('--yaw must be 0 or pi modulo 2pi for this slope acceptance')
if args.lower_loss and (not args.dual_lidar or args.planning_loss or args.obstacle_only):ap.error('--lower-loss needs --dual-lidar and uphill, without --planning-loss')
if not math.isfinite(args.obstacle_height) or not .08<=args.obstacle_height<=.6:ap.error('--obstacle-height must be .08.. .6 metres')
out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True);os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
repo=Path(__file__).resolve().parents[2]
for name in ('sim_ws/src/br_sim_bringup/config/lio_terrain.yaml','sim_ws/src/br_sim_bringup/config/point_lio_terrain.yaml','sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py',
'sim_ws/src/br_sim_bringup/launch/scan_lio_terrain.launch.py'):
(out/Path(name).name).write_bytes((repo/name).read_bytes())
report=dict(status='INVALID',cases={},side=args.side,sensor_profile=args.sensor_profile,collector_sha256=hashlib.sha256(source).hexdigest())
if args.dual_lidar:
for name in ('sim_ws/src/br_sim_bringup/config/dual_lidar.yaml','sim_ws/src/br_sim_bringup/config/dual_lidar_terrain.yaml',
'sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py','minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py'):
(out/Path(name).name).write_bytes((repo/name).read_bytes())
report=dict(status='INVALID',cases={},side=args.side,dual_lidar=args.dual_lidar,yaw=args.yaw,obstacle_height=args.obstacle_height,obstacle_slope_aligned=args.obstacle_slope_aligned,sensor_profile=args.sensor_profile,collector_sha256=hashlib.sha256(source).hexdigest())
sim=Sim(str(out/'sim'));p=None;y=3.5125 if args.side=='red' else -3.5125
try:
ok,why=sim.start(navigation=True,terrain=True,lio_navigation=True,sensor_profile=args.sensor_profile,spawn=(3.5,y,.15,0.));report['startup']=why
ok,why=sim.start(navigation=True,terrain=True,lio_navigation=True,dual_lidar=args.dual_lidar,sensor_profile=args.sensor_profile,spawn=(3.5,y,.15,args.yaw));report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out)
rclpy.init();p=TerrainProbe(out,args.dual_lidar);p.sensor_profile=args.sensor_profile
if not p.wait_clock():raise RuntimeError('no clock')
deadline=time.monotonic()+100
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if p.ready and p.status and p.path_pub.get_subscription_count()>0 and len(p.nav_odom)>20:break
else:raise RuntimeError('terrain LIO pipeline not ready')
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/step_blocker',))
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/step_blocker','/dual_lidar_fusion') if args.dual_lidar else ('/step_blocker',))
if not report['graph']['ok']:raise RuntimeError('truth input or incorrect estimator wiring')
p.pump(1.)
cases=[('uphill',[3.5,2.7,-.8,-1.2],False)]
if args.obstacle_only:
req=SpawnEntity.Request();req.name='p6_terrain_obstacle';req.reference_frame='world'
req.initial_pose.position.x=1.;req.initial_pose.position.y=y;req.initial_pose.position.z=height(1.)+.3
req.initial_pose.position.x=1.;req.initial_pose.position.y=y;req.initial_pose.position.z=height(1.)+args.obstacle_height/2
req.initial_pose.orientation.w=1.
if args.obstacle_slope_aligned:
angle=math.atan2(.597,3.5)
req.initial_pose.position.x+=math.sin(angle)*args.obstacle_height/2
req.initial_pose.position.z=height(1.)+math.cos(angle)*args.obstacle_height/2
req.initial_pose.orientation.y=math.sin(angle/2);req.initial_pose.orientation.w=math.cos(angle/2)
report['obstacle_fixture_pose']=dict(position=[req.initial_pose.position.x,req.initial_pose.position.y,req.initial_pose.position.z],
orientation_xyzw=[0.,req.initial_pose.orientation.y,0.,req.initial_pose.orientation.w],dimensions=[.25,.25,args.obstacle_height])
req.xml='<sdf version="1.6"><model name="p6_terrain_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></collision><visual name="box"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></visual></link></model></sdf>'
req.xml=req.xml.replace('0.25 0.25 0.6','0.25 0.25 '+str(args.obstacle_height))
response=p._call(p.spawn,req,timeout=15)
if not response or not response.success:raise RuntimeError('obstacle fixture not spawned')
(out/'obstacle.sdf').write_text(req.xml);p.pump(2.);p.capture()
(out/'obstacle.sdf').write_text(req.xml);fixture_start=p.now();p.pump(2.);p.capture()
ft='/sim/navigation/fused_cloud' if args.dual_lidar else '/sim/navigation/cloud_registered'
pt='/sim/navigation/fused_planning_cloud' if args.dual_lidar else '/sim/navigation/planning_cloud'
deadline=time.monotonic()+5
while p.clouds['/sim/navigation/cloud_registered'].header.stamp!=p.clouds['/sim/navigation/planning_cloud'].header.stamp and time.monotonic()<deadline:p.pump(.02)
if p.clouds['/sim/navigation/cloud_registered'].header.stamp!=p.clouds['/sim/navigation/planning_cloud'].header.stamp:raise RuntimeError('no matched obstacle cloud stamps')
full=points(p.clouds['/sim/navigation/cloud_registered']);filtered=points(p.clouds['/sim/navigation/planning_cloud'])
while p.clouds[ft].header.stamp!=p.clouds[pt].header.stamp and time.monotonic()<deadline:p.pump(.02)
if p.clouds[ft].header.stamp!=p.clouds[pt].header.stamp:raise RuntimeError('no matched obstacle cloud stamps')
full=points(p.clouds[ft]);filtered=points(p.clouds[pt])
np.savez_compressed(out/'obstacle_points.npz',world=full,filtered=filtered)
if len(full)!=len(filtered):raise RuntimeError('unpaired obstacle point clouds')
selected=(np.abs(full[:,0]-1.)<.18)&(np.abs(full[:,1]-y)<.18)&(full[:,2]>height(1.)+.12)&(full[:,2]<height(1.)+.68)
selected=(np.abs(full[:,0]-1.)<.18)&(np.abs(full[:,1]-y)<.18)&(full[:,2]>height(1.)+min(.12,args.obstacle_height-.015))&(full[:,2]<height(1.)+args.obstacle_height+.08)
count=int(np.count_nonzero(selected));retained=int(np.count_nonzero(np.isfinite(filtered[selected]).all(axis=1)))
report['obstacle_returns']=dict(count=count,retained=retained,ok=count>=15 and retained==count)
if not report['obstacle_returns']['ok']:raise RuntimeError('obstacle was not observed and preserved')
if args.dual_lidar:
# Evaluate every paired scan in a fixed two-second interval,
# not whichever sparse scanning pattern happens to be last.
records=[];worlds=[];filtered_frames=[];identities=[]
for ns,raw_cloud,planning_cloud in p.paired_clouds:
if not fixture_start<=ns*1e-9<=fixture_start+2.:continue
world=points(raw_cloud);plan=points(planning_cloud)
ids=np.ndarray((raw_cloud.width,),dtype='u1',buffer=raw_cloud.data,offset=32,strides=(raw_cloud.point_step,))
mask=(np.abs(world[:,0]-1.)<.18)&(np.abs(world[:,1]-y)<.18)&(world[:,2]>height(1.)+min(.12,args.obstacle_height-.015))&(world[:,2]<height(1.)+args.obstacle_height+.08)
records.append(dict(stamp_ns=ns,count=int(mask.sum()),retained=int(np.isfinite(plan[mask]).all(axis=1).sum()),by_sensor=[int(np.count_nonzero(mask&(ids==i))) for i in (0,1)]))
worlds.append(world);filtered_frames.append(plan);identities.append(ids)
count=sum(r['count'] for r in records);retained=sum(r['retained'] for r in records)
by_sensor=[sum(r['by_sensor'][i] for r in records) for i in (0,1)]
report['obstacle_returns']=dict(count=count,retained=retained,by_sensor=by_sensor,frames=records,
criteria='all matched scans in fixed 2 s window; >=10 frames, >=15 selected returns, >=5 lower returns; all selected returns preserved',
ok=len(records)>=10 and count>=15 and by_sensor[1]>=5 and retained==count)
if worlds:np.savez_compressed(out/'obstacle_points.npz',world=np.concatenate(worlds),filtered=np.concatenate(filtered_frames),sensor_id=np.concatenate(identities))
if not report['obstacle_returns']['ok']:
print('valid obstacle sample fails observation/preservation criteria; still checking physical rejection',flush=True)
cases=[('ramp_obstacle_rejected',[3.5,2.7,1.],True)]
elif not args.up_only:cases.extend([('stairs_rejected',[-1.2,-2.5],True),('edge_rejected',[-1.2,1.],True),('downhill',[-1.2,-.8,2.7,3.5],False)])
for name,xs,blocked in cases:
result=run_path(p,xs,y,blocked,fault_sim=sim if args.planning_loss and name=='uphill' else None,
goal_y=(3.9 if y>0 else -3.9) if name=='edge_rejected' else None);report['cases'][name]=result
result=run_path(p,xs,y,blocked,fault_sim=sim if (args.planning_loss or args.lower_loss) and name=='uphill' else None,
goal_y=(3.9 if y>0 else -3.9) if name=='edge_rejected' else None,lower_loss=args.lower_loss);report['cases'][name]=result
(out/(name+'.json')).write_text(json.dumps(result,indent=2,default=json_value)+'\n');print(name,result['checks'],flush=True)
if not result['ok']:break
report['status']='PASS' if len(report['cases'])==len(cases) and all(c['ok'] for c in report['cases'].values()) else 'FAIL'
report['status']='PASS' if len(report['cases'])==len(cases) and all(c['ok'] for c in report['cases'].values()) and report.get('obstacle_returns',{'ok':True})['ok'] else 'FAIL'
if args.dual_lidar:
report['dual_metadata_checks']=p.metadata_checks;report['dual_status']=p.dual_status
report['metadata_ok']=len(p.metadata_checks)>=2 and all(all(v for k,v in c.items() if k!='stamp') for c in p.metadata_checks)
if not report['metadata_ok']:report['status']='FAIL'
report['cloud_snapshots']=p.snapshots;report['navigation_status']=p.navigation_status
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
except Exception as exc:report['status']='INVALID';report['error']=repr(exc);print(report['error'],flush=True)
finally:
if p is not None:
report['navigation_status']=p.navigation_status
if args.dual_lidar:report.update(dual_metadata_checks=p.metadata_checks,dual_status=p.dual_status)
report['ros_cleanup_errors'] = shutdown_probe(p)
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
+3 -3
View File
@@ -26,8 +26,8 @@ def main():
center=np.array([state['pos'][0]+distance,state['pos'][1],height/2])
# The far TOP face can be visible even if the front face is below
# the lower FOV. Include box depth; a point-target approximation
# wrongly predicts that the 8 cm / 3 m fixture is invisible.
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([0.,0.,.3]))
# can misclassify a fixture near the lower-FOV boundary.
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([.015,0.,.33]))
inverse=q.copy();inverse[:3]*=-1
corners=np.array([[center[0]+dx,center[1]+dy,height] for dx in (-.125,.125) for dy in (-.125,.125)])
local=rotate(inverse,corners-origin)
@@ -43,7 +43,7 @@ def main():
p.pump(.2);t=p.now();p.pump(1.5)
frames=[f for f in p.frames if t<f['t'] and f['t']+.1<p.now()]
if len(frames)<8:raise RuntimeError('insufficient actual scans')
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([0.,0.,.3]));all_world=[]
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([.015,0.,.33]));all_world=[]
for f in frames:all_world.append(rotate(q,f['xyz'])+origin)
world=np.concatenate(all_world)
in_box=(abs(world[:,0]-center[0])<.126)&(abs(world[:,1]-center[1])<.126)&(world[:,2]>.005)&(world[:,2]<=height+.002)
+23 -5
View File
@@ -20,7 +20,7 @@ from check_omni_robot import Sim,sim_env, shutdown_probe
from check_slope_drive import SlopeProbe
ROOT=Path(__file__).resolve().parents[2]
MOUNT=np.array([0.,0.,.30])
MOUNT=np.array([.015,0.,.33])
def json_value(value):
@@ -48,11 +48,12 @@ def interpolate(states,times):
return pos[lo]+(pos[hi]-pos[lo])*w[:,None],qq
def scene_shapes():
def scene_shapes(model_path=None):
"""Read authoritative static primitives and triangles; independent of ODE ray code."""
base=ROOT/'sim_ws/src/robocon_gazebo/models/robocon_ground_full'
result=[]
for c in ET.parse(base/'model.sdf').findall('.//collision'):
if model_path is not None:base=Path(model_path).parent
for c in ET.parse(base/'model.sdf' if model_path is None else model_path).findall('.//collision'):
p=np.fromstring(c.findtext('pose','0 0 0 0 0 0'),sep=' ')
r,pitch,y=p[3:];cx,sx=np.cos(r),np.sin(r);cy,sy=np.cos(pitch),np.sin(pitch);cz,sz=np.cos(y),np.sin(y)
R=np.array([[cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx],
@@ -108,6 +109,16 @@ def ray_ranges(origins,directions,shapes):
return best
def vehicle_ranges(directions):
"""Independent local ray/box intersection, including physical roof returns.
Measured roof=.41 m, retained base=.15 m, assumed body bottom=.07 m.
Raw self hits are valid sensor observations, not outliers to hide.
"""
body=[(np.array([0.,0.,.09]),np.eye(3),'box',np.array([.4,.4,.17]))]
return ray_ranges(np.broadcast_to(MOUNT,directions.shape),directions,body)
class SensorProbe(SlopeProbe):
def __init__(self):
super().__init__();self.frames=[];self.imus=[];self.sensor_status=[]
@@ -153,10 +164,10 @@ def geometry_check(p,record,shapes,out,name):
times=f['t']+f['offsets'][idx]*1e-9
pos,q=interpolate(states,times)
origins=pos+rotate(q,np.broadcast_to(MOUNT,pos.shape));directions=rotate(q,direction)
expected=ray_ranges(origins,directions,shapes)
expected=np.minimum(ray_ranges(origins,directions,shapes),vehicle_ranges(direction))
errors.extend(np.abs(expected-ranges).tolist())
end_pos,end_q=interpolate(states,np.full(len(xyz),f['t']+.099))
wrong=ray_ranges(end_pos+rotate(end_q,np.broadcast_to(MOUNT,end_pos.shape)),rotate(end_q,direction),shapes)
wrong=np.minimum(ray_ranges(end_pos+rotate(end_q,np.broadcast_to(MOUNT,end_pos.shape)),rotate(end_q,direction),shapes),vehicle_ranges(direction))
instant_errors.extend(np.abs(wrong-ranges).tolist())
saved[str(i)+'_xyz']=f['xyz'];saved[str(i)+'_offset_ns']=f['offsets']
saved[str(i)+'_query_t']=times;saved[str(i)+'_expected_range']=expected
@@ -207,6 +218,13 @@ def main():
if name!='stop':geometry[name]=geometry_check(p,records[name],shapes,out,name)
frames=[f for f in p.frames if records['stationary']['t0']<=f['t']<records['stop']['t1']-.1]
checks=result['checks']
# Verify the actual transient-local TF messages, not only launch text.
mounts={item['child']:item for item in p.tf_static_raw if item['frame_id']=='base_link'}
for child,expected_mount in (('lidar',MOUNT),('mid360_imu',MOUNT+[.011,.02329,-.04412])):
mount=mounts.get(child)
checks['tf_'+child]=bool(mount is not None and np.allclose(mount['translation'],expected_mount,atol=1e-9,rtol=0)
and np.allclose(mount['rotation'],[0,0,0,1],atol=1e-9,rtol=0))
result['runtime_sensor_tf']=mounts
checks['geometry']=all(g['ok'] for g in geometry.values())
checks['frame_and_count']=all(f['frame']=='lidar' and f['point_num']==len(f['xyz']) and len(f['xyz'])>500 for f in frames)
checks['finite_fov']=all(np.isfinite(f['xyz']).all() and np.min(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))>=math.radians(-7)-1e-6 and np.max(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))<=math.radians(52)+1e-6 for f in frames)
+18 -5
View File
@@ -239,7 +239,7 @@ class Sim(object):
if value.isdigit() and self.owns(int(value)):
self.known[int(value)] = _comm(int(value))
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False):
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False, dual_lidar=False, mission=False, ramp_speed=.3, nav_speed=.3, aligned_start=False, crest_speed=.2, yaw_speed=.8, with_rviz=False, mission_profile='standard'):
if port_open(port=11355):
return False, 'master 端口 11355 已被占用;本工具不去动占用者,直接退出'
if terrain and not navigation:
@@ -252,16 +252,28 @@ class Sim(object):
raise ValueError('MID360 is currently a separate sensor/localization entry')
if sensor_profile not in ('ideal','mild','stress') or (split and not lio_navigation):
raise ValueError('invalid noise profile or split without LIO navigation')
entry = ('br_sim_bringup scan_lio_split.launch.py' if split else
if dual_lidar and (not lio_navigation or split):
raise ValueError('dual lidar acceptance requires the combined LIO entry')
if mission and (not lio_navigation or not dual_lidar or terrain or split):raise ValueError('mission requires combined flat LIO with dual lidar')
entry = ('br_sim_bringup ramp_mission.launch.py' if mission else
'br_sim_bringup scan_lio_split.launch.py' if split else
'br_sim_bringup '+('scan_lio_terrain.launch.py' if terrain else 'scan_lio.launch.py') if lio_navigation else
'br_sim_bringup mid360_sim.launch.py' if localization else
'br_sim_bringup '+('scan_terrain.launch.py' if terrain else 'scan_sim.launch.py') if navigation else
'br_sim_bringup robot_sim.launch.py')
options = ('gui:=%s' % ('true' if gui else 'false'))
if dual_lidar:options += ' dual_lidar:=true'
if mission:
if mission_profile not in ('standard','fast'):raise ValueError('invalid mission profile')
if not .1<=nav_speed<=(2.5 if mission_profile=='fast' else .6) or not .1<=ramp_speed<=(1.1 if mission_profile=='fast' else .7):raise ValueError('mission speed outside selected profile')
options+=' autostart:=true profile:=%s ramp_speed:=%g nav_speed:=%g'%(mission_profile,ramp_speed,nav_speed)
if not .03<=crest_speed<=min(.2,ramp_speed) or not .1<=yaw_speed<=(2. if mission_profile=='fast' else 1.):raise ValueError('invalid mission crest/yaw speeds')
options+=' crest_speed:=%g yaw_speed:=%g'%(crest_speed,yaw_speed)
options+=' aligned_start:='+('true' if aligned_start else 'false')
if lio_navigation:
options += ' sensor_profile:='+sensor_profile
if not terrain and not split:
options += ' with_rviz:=false'
options += ' with_rviz:='+('true' if with_rviz else 'false')
if split:options += ' terrain:='+('true' if terrain else 'false')
elif localization:
options += ' with_lio:=true sensor_profile:='+sensor_profile
@@ -1244,13 +1256,14 @@ def sh_cmd(cmd, timeout=15):
'err': (p.stderr or '').strip()[-400:]}
def check_model_geometry(out, drive='planar'):
def check_model_geometry(out, drive='planar', dual_lidar=False):
"""从展开后的 SDF 模型计算外包络,与配置值对照(不依赖 Gazebo 运行时)。"""
src = os.path.join(WS, 'src', 'r2027_robot_description', 'sdf',
'r2027_omni_robot.sdf.xacro')
expanded = os.path.join(out, 'model_expanded.sdf')
xacro = shutil.which('xacro') or '/opt/ros/humble/bin/xacro'
p = subprocess.run([xacro, src, 'drive:='+drive, '-o', expanded],
mappings=['dual_lidar:=true','lidar:=true','sensor_model:=mid360'] if dual_lidar else []
p = subprocess.run([xacro, src, 'drive:='+drive]+mappings+['-o', expanded],
env=sim_env(), capture_output=True, text=True, timeout=60)
if p.returncode != 0:
return {'ok': False, 'error': p.stderr[-400:], 'path': expanded}
+1 -1
View File
@@ -16,7 +16,7 @@ from nav_msgs.msg import Odometry
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,phase,interpolate,rotate,json_value
IMU_OFFSET=np.array([.011,.02329,.25588])
IMU_OFFSET=np.array([.026,.02329,.28588])
def matrix(q):
+256
View File
@@ -0,0 +1,256 @@
#!/usr/bin/python3
"""Independent mission evaluation: truth only for scoring, no drive injection."""
import argparse,hashlib,json,math,os,sys,time
from pathlib import Path
import numpy as np
import rclpy
from std_msgs.msg import String
from gazebo_msgs.srv import SpawnEntity
from std_srvs.srv import Trigger
from rcl_interfaces.srv import GetParameters
from geometry_msgs.msg import Twist
from rclpy.qos import QoSProfile,DurabilityPolicy,ReliabilityPolicy
from check_omni_robot import Sim,sim_env,shutdown_probe
from check_lio_terrain import TerrainProbe
from check_mid360 import interpolate,json_value
from check_lio_navigation import graph_evidence
def critical_cloud_reliability_ok(evidence):
"""Check discovery evidence; history depth is not exposed by this local RMW."""
for topic, producer, consumers in (
('/sim/navigation/fused_planning_cloud', 'dual_lidar_fusion', ('step_blocker', 'ramp_mission')),
('/sim/navigation/terrain_planning_cloud', 'step_blocker', ('lio_navigation_adapter', 'scan_planner_node'))):
for kind, names in (('publisher', (producer,)), ('subscription', consumers)):
for name in names:
matches = [row for row in evidence.get(topic, []) if row['kind'] == kind and row['node'] == name]
if len(matches) != 1 or matches[0]['reliability'] != str(ReliabilityPolicy.RELIABLE):
return False
return True
def bounds(s):
from check_mid360 import rotate
R=rotate(np.broadcast_to(np.array(s['quaternion']),(3,4)),np.eye(3)).T
c=np.asarray(s['pos'])+R@np.array([0.,0.,.055]);e=np.abs(R)@np.array([.4,.4,.205])
return c-e,c+e
def motion_metrics(truth,events,fast=False):
entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
nav_start=next((e['stamp'] for e in events if e.get('to')=='NAVIGATE'),None)
nav=[s for s in truth if nav_start is not None and s['stamp']>=nav_start and (entry is None or s['stamp']<entry)]
straight=[s for s in nav if -3.5<s['pos'][0]<2.5]
uphill=[s for s in truth if entry is not None and s['stamp']>=entry and .5<s['pos'][0]<1.8]
crest=[s for s in truth if entry is not None and s['stamp']>=entry and ((-1.15<s['pos'][0]<-1.02) if fast else (-.85<s['pos'][0]<-.35))]
speed=lambda s:float(np.linalg.norm(s['twist_world']))
longest=0.;since=None
for s in straight:
if speed(s)<.05:
if since is None:since=s['stamp']
longest=max(longest,s['stamp']-since)
else:since=None
return dict(straight_peak_mps=max(map(speed,straight),default=0.),
straight_longest_stop_s=longest,nav_yaw_peak_radps=max((abs(s['wz']) for s in nav),default=0.),
uphill_peak_mps=max(map(speed,uphill),default=0.),crest_peak_mps=max(map(speed,crest),default=0.),
crest_median_mps=float(np.median([speed(s) for s in crest])) if crest else None)
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--profile',choices=('standard','fast'),default='standard')
ap.add_argument('--ramp-speed',type=float);ap.add_argument('--nav-speed',type=float)
ap.add_argument('--crest-speed',type=float,default=.2);ap.add_argument('--yaw-speed',type=float)
ap.add_argument('--gui',action='store_true');ap.add_argument('--sensor-profile',choices=('ideal','mild'),default='ideal')
ap.add_argument('--with-rviz',action='store_true',help='include RViz to reproduce the interactive launch load (requires --gui)')
ap.add_argument('--fault',choices=('none','lower_loss','mission_loss','mux_loss','obstacle'),default='none')
ap.add_argument('--aligned-start',action='store_true',help='fault diagnostics only, start physically at the staging pose; never count as a full-route pass')
args=ap.parse_args();out=Path(args.out).resolve();out.mkdir(parents=True,exist_ok=True)
if args.nav_speed is None:args.nav_speed=2.5 if args.profile=='fast' else .6
if args.ramp_speed is None:args.ramp_speed=1.1 if args.profile=='fast' else .7
if args.yaw_speed is None:args.yaw_speed=2.0 if args.profile=='fast' else .8
if args.aligned_start and args.fault=='none':ap.error('--aligned-start is only for explicitly scoped fault diagnostics')
if args.with_rviz and not args.gui:ap.error('--with-rviz requires --gui')
if (out/'result.json').exists():ap.error('use a fresh output directory')
os.environ.update(sim_env());os.environ['ROS_LOG_DIR']=str(out/'ros')
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
report=dict(status='INVALID',profile=args.profile,gui=args.gui,with_rviz=args.with_rviz,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,fault=args.fault,aligned_start=args.aligned_start,collector_sha256=hashlib.sha256(source).hexdigest())
root=Path(__file__).resolve().parents[2]
report['source_sha256']={str(p.relative_to(root)):hashlib.sha256(p.read_bytes()).hexdigest() for p in [
root/name for name in ('sim_ws/src/br_sim_bringup/scripts/ramp_mission.py','sim_ws/src/br_sim_bringup/scripts/mission_command_mux.py','sim_ws/src/br_sim_bringup/launch/ramp_mission.launch.py',
'sim_ws/src/r2027_robot_description/src/contact_drive.cpp','sim_ws/src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro',
'sim_ws/src/r2027_robot_description/launch/robocon_robot.launch.py','sim_ws/src/br_sim_bringup/launch/mid360_sim.launch.py',
'minco_ws/src/scan/plan_env/src/grid_map.cpp','minco_ws/src/scan/plan_env/include/plan_env/grid_map.h','minco_ws/src/scan/plan_manage/src/scan_replan_fsm.cpp',
'minco_ws/src/scan/plan_manage/src/planner_manager.cpp','minco_ws/src/scan/plan_manage/src/closed_loop_controller.cpp','sim_ws/src/br_sim_bringup/scripts/dual_lidar_fusion.py',
'minco_ws/src/perception/Point-LIO/include/common_lib.h','minco_ws/src/perception/Point-LIO/include/sensor_timestamp.h',
'sim_ws/src/br_sim_bringup/scripts/lio_navigation_adapter.py','minco_ws/src/scan/step_blocker/step_blocker/step_blocker_node.py',
'minco_ws/src/perception/Point-LIO/include/sensor_time_rate_limiter.h','minco_ws/src/perception/Point-LIO/src/laserMapping.cpp','sim_ws/src/robocon_gazebo/worlds/robocon_robot.world')]}
for name in report['source_sha256']:(out/Path(name).name).write_bytes((root/name).read_bytes())
sim=Sim(str(out/'sim'));p=None;states=[];mission=[];mux=[];fault={};actuator=[]
try:
ok,why=sim.start(lio_navigation=True,dual_lidar=True,mission=True,ramp_speed=args.ramp_speed,nav_speed=args.nav_speed,gui=args.gui,sensor_profile=args.sensor_profile,
with_rviz=args.with_rviz,mission_profile=args.profile,
crest_speed=args.crest_speed,yaw_speed=args.yaw_speed,
aligned_start=args.aligned_start,spawn=(3.7,3.5125,.15,math.pi) if args.aligned_start else None);report['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out,True)
for pub in (p.pub,p.goal_pub,p.path_pub):p.destroy_publisher(pub)
p.send=lambda *args:None
p.create_subscription(String,'/mission/status',lambda m:mission.append(json.loads(m.data)),QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
p.create_subscription(String,'/mission/mux_status',lambda m:mux.append(json.loads(m.data)),10)
p.create_subscription(Twist,'/sim/cmd_vel',lambda m:actuator.append(dict(stamp=p.now(),command=[m.linear.x,m.linear.y,m.angular.z])),100)
if not p.wait_clock():raise RuntimeError('missing clock')
deadline=time.monotonic()+700;start=p.now();last_query=-1.;graph=None
fixture=False
while time.monotonic()<deadline and p.now()-start<210:
p.pump(.03)
if p.now()-last_query>=.1:
s=p.get_state()
if s is None:raise RuntimeError('missing physical entity query')
states.append(s);last_query=p.now()
if not mission:continue
state=mission[-1]['state']
if args.fault=='obstacle' and not fixture and state in ('NAVIGATE','ENTRY'):
req=SpawnEntity.Request();req.name='mission_ramp_obstacle';req.reference_frame='world'
req.initial_pose.position.x=1.;req.initial_pose.position.y=3.5125;req.initial_pose.position.z=float((1.6119-.597)/3.5+.15);req.initial_pose.orientation.w=1.
req.xml='<sdf version="1.6"><model name="mission_ramp_obstacle"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 0.30</size></box></geometry></collision></link></model></sdf>'
res=p._call(p.spawn,req,15)
if res is None or not res.success:raise RuntimeError('fixture spawn failed')
fixture=True;fault=dict(kind='obstacle',spawn_stamp=p.now())
inject=args.fault in ('lower_loss','mission_loss','mux_loss') and not fault and state=='CLIMB' and states[-1]['pos'][0]<1.8
if inject:
fault=dict(kind=args.fault,start=p.now(),initial=states[-1])
if args.fault=='lower_loss':
raw=p.raw[1];raw_end=(int(raw.timebase)+max(point.offset_time for point in raw.points))*1e-9
fault.update(lower_last_source_end=raw_end,lower_source_age_at_injection_s=p.now()-raw_end)
fault.update(upper_before=int(p.raw[0].timebase),lower_before=int(p.raw[1].timebase))
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/disable')
response=p._call(cli,Trigger.Request(),5)
if response is None or not response.success:raise RuntimeError('lower disable failed')
else:
import signal
sim.refresh_owned()
executable=b'/ramp_mission.py' if args.fault=='mission_loss' else b'/mission_command_mux.py'
candidates=[pid for pid in sim.known if sim.owns(pid) and executable in Path('/proc/%d/cmdline'%pid).read_bytes()]
if len(candidates)!=1:raise RuntimeError('mission process ownership ambiguous')
fault['pid']=candidates[0];os.kill(fault['pid'],signal.SIGSTOP)
if state in ('FAILED','SUCCEEDED'):break
if args.fault in ('mission_loss','mux_loss') and fault and p.now()-fault['start']>1.4:break
else:raise RuntimeError('mission did not terminate in acceptance time')
if args.fault!='none' and not fault:raise RuntimeError('requested fault was not injected; the injection gate was not reached')
if args.fault=='lower_loss' and fault:
p.pump(1.1)
fault.update(upper_during_loss=int(p.raw[0].timebase),lower_during_loss=int(p.raw[1].timebase))
cli=p.create_client(Trigger,'/sim/mid360_low/lidar/profile/'+args.sensor_profile)
response=p._call(cli,Trigger.Request(),5)
if response is None or not response.success:raise RuntimeError('lower restore failed')
fault['restore_stamp']=p.now()
p.pump(1.3);final=p.get_state()
if final is None:raise RuntimeError('missing final entity query')
states.append(final)
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/dual_lidar_fusion','/ramp_mission','/mission_command_mux'))
publishers=p.get_publishers_info_by_topic('/cmd_vel')
cli=p.create_client(GetParameters,'/sim/lio/point_lio_sim/get_parameters')
req=GetParameters.Request();req.names=['odometry.publish_scan_end']
scan_end_params=p._call(cli,req,5)
report['scan_end_odometry_enabled']=bool(scan_end_params and scan_end_params.values and scan_end_params.values[0].bool_value)
report['critical_cloud_qos']={}
for topic,producer,consumers in (
('/sim/navigation/fused_planning_cloud','dual_lidar_fusion',('step_blocker','ramp_mission')),
('/sim/navigation/terrain_planning_cloud','step_blocker',('lio_navigation_adapter','scan_planner_node'))):
rows=[]
for kind,infos,wanted in (('publisher',p.get_publishers_info_by_topic(topic),(producer,)),('subscription',p.get_subscriptions_info_by_topic(topic),consumers)):
for name in wanted:
matches=[i for i in infos if i.node_name==name]
rows.extend(dict(kind=kind,node=i.node_name,reliability=str(i.qos_profile.reliability),depth=i.qos_profile.depth) for i in matches)
report['critical_cloud_qos'][topic]=rows
report['qos_depth_evidence']='Configured depth 1 in archived source; discovery returned depth 0 locally and does not establish runtime history depth.'
report['cmd_vel_publishers']=[dict(node=i.node_name,namespace=i.node_namespace) for i in publishers]
truth=p.truth_poses
if len(truth)<100:raise RuntimeError('missing dense physical truth')
queries=[s for s in states if truth[0]['stamp']<=s['stamp']<=truth[-1]['stamp']]
tpos,tq=interpolate(truth,[s['stamp'] for s in queries])
error=np.linalg.norm(tpos-np.array([s['pos'] for s in queries]),axis=1)
angles=2*np.arccos(np.clip(abs(np.sum(tq*np.array([s['quaternion'] for s in queries]),axis=1)),0,1))
# Query service and update-end truth are asynchronous within the world's
# configured 1 ms physics step. Keep raw differences and bound the
# additional positional uncertainty by the measured query speed.
phase_bound=np.array([np.linalg.norm(s['twist_world'])*.001 for s in queries]) if args.profile=='fast' else np.zeros(len(queries))
report['truth_service_phase_bound']=dict(physics_step_s=.001,scope='fast only; 2 mm spatial residual plus one physics-step travel',maximum_bound_m=float(max(phase_bound)),maximum_residual_m=float(max(error-phase_bound)))
report['truth_service_agreement']=dict(samples=len(queries),max_position_error_m=float(max(error)),max_angle_error_rad=float(max(angles)),max_dense_gap_s=float(max(np.diff([s['stamp'] for s in truth]))))
tail=[s for s in truth if s['stamp']>=final['stamp']-1.]
checks=dict(no_truth_feedback=report['graph']['ok'],scan_end_odometry_enabled=report['scan_end_odometry_enabled'],critical_cloud_qos_reliable=critical_cloud_reliability_ok(report['critical_cloud_qos']),one_drive_owner=len(publishers)==1 and publishers[0].node_name=='mission_command_mux',
truth_crosschecked=bool(np.all(error<.002+phase_bound)) and max(angles)<.005 and report['truth_service_agreement']['max_dense_gap_s']<=.12,
stopped=bool(tail) and all(np.linalg.norm(s['twist_world'])<.01 and abs(s['wz'])<.02 for s in tail),
stopped_drift=bool(tail) and max(math.dist(s['pos'],tail[0]['pos']) for s in tail)<.02)
events=mission[-1]['events'];entry=next((e['stamp'] for e in events if e.get('to')=='ENTRY'),None)
ramp=[s for s in truth if entry is not None and s['stamp']>=entry and s['pos'][0]<3.1]
clearance=[min(bounds(s)[0][1]-3.025,4.-bounds(s)[1][1]) for s in ramp]
report['ramp_clearance_m']=min(clearance,default=None)
report['maximum_ramp_lateral_error_m']=max((abs(s['pos'][1]-3.5125) for s in ramp),default=None)
pairs=sorted({(c.collision1_name,c.collision2_name) for m in p.contacts for c in m.states})
report['contacts']=dict(pairs=pairs,maximum_depth_m=max((d for m in p.contacts for c in m.states for d in c.depths),default=None))
report['final']=final;report['events']=events;report['elapsed_sim_s']=mission[-1].get('elapsed_s')
starts=[e['stamp'] for e in events if e.get('to') in ('NAVIGATE','ENTRY')]
terminal=[e['stamp'] for e in events if e.get('to') in ('SUCCEEDED','FAILED')]
report['task_duration_sim_s']=terminal[-1]-starts[0] if terminal and starts else None
report['motion_metrics']=motion_metrics(truth,events,args.profile=='fast')
if args.fault=='none':
lo,hi=bounds(final)
north=[]
for a,b in zip(truth,truth[1:]):
if entry is None or b['stamp']>entry:continue
qa=np.array(a['quaternion']);qb=np.array(b['quaternion'])
angle=2*math.acos(np.clip(abs(float(qa@qb)),0,1));pad=(math.dist(a['pos'],b['pos'])+.62*angle)/2
for s in (a,b):
blo,bhi=bounds(s)
# The inner wall ends at x=2.7; the east staging area is open.
if bhi[0]+pad>=-3. and blo[0]-pad<=2.7:north.append(min(blo[1]-4.,5.5-bhi[1])-pad)
report['north_corridor_gap_bound_m']=min(north,default=None)
mm=report['motion_metrics']
if args.profile=='fast':checks['within_20_seconds']=mission[-1]['state']=='SUCCEEDED' and report['task_duration_sim_s'] is not None and report['task_duration_sim_s']<=20.
checks.update(mission_succeeded=mission[-1]['state']=='SUCCEEDED',
straight_without_intermediate_stop=mm['straight_longest_stop_s']<=.25,
requested_straight_speed_reached=mm['straight_peak_mps']>=.85*args.nav_speed,
requested_uphill_speed_reached=mm['uphill_peak_mps']>=.85*args.ramp_speed,
requested_turn_speed_reached=mm['nav_yaw_peak_radps']>=.85*args.yaw_speed,
crest_speed_respected=mm['crest_median_mps'] is not None and mm['crest_peak_mps']<=args.crest_speed+.03,
north_corridor_clearance=bool(north) and min(north)>.03,
no_wall_contacts=all(any(name.endswith(suffix) for suffix in ('::ground','::ramp_north','::Cube.005')) for pair in pairs for name in pair if not name.startswith('r2027_omni::')),
all_phases=all(any(e.get('to')==stage for e in events) for stage in ('NAVIGATE','ENTRY','CLIMB','CREST','PLATFORM','SETTLE','SUCCEEDED')),
started_at_default=math.dist(truth[0]['pos'],[-4.5,4.5,.15])<.03,
final_whole_body_on_platform=lo[0]>=-1.76 and hi[0]<=-.84 and lo[1]>=3.065 and hi[1]<=3.96,
platform_height=abs(final['pos'][2]-.75)<.03,
full_ramp_clearance=bool(clearance) and min(clearance)>.04,
ramp_lateral_error=bool(ramp) and report['maximum_ramp_lateral_error_m']<.03,
actual_ramp_contacts=any('ramp_north' in c.collision1_name or 'ramp_north' in c.collision2_name for m in p.contacts for c in m.states),
contact_penetration=max((d for m in p.contacts for c in m.states for d in c.depths),default=1)<.005)
else:
if args.fault=='obstacle':
checks.update(obstacle_detected=mission[-1]['state']=='FAILED' and mission[-1]['reason']=='obstacle_in_braking_corridor',
obstacle_not_contacted=not any('mission_ramp_obstacle' in c.collision1_name or 'mission_ramp_obstacle' in c.collision2_name for m in p.contacts for c in m.states))
else:
stop=next((s['stamp']-fault['start'] for s in truth if s['stamp']>=fault['start'] and np.linalg.norm(s['twist_world'])<.01 and abs(s['wz'])<.02),None)
fault['stop_latency_s']=stop;checks['fault_stop_latency']=stop is not None and 0<=stop<=.5
checks['fault_exercised']=bool(fault) and (args.fault in ('mission_loss','mux_loss') or mission[-1]['state']=='FAILED')
if args.fault=='mission_loss':checks['lease_expiry_exercised']=any(m['stamp']>fault['start']+.15 and m['reason']=='lease_stale' for m in mux)
if args.fault=='mux_loss':checks['actuator_watchdog_exercised']=any(m['stamp']>fault['start']+.15 and max(abs(v) for v in m['command'])<1e-8 for m in actuator)
if args.fault=='lower_loss':
fault.update(upper_after=int(p.raw[0].timebase),lower_after=int(p.raw[1].timebase))
checks['upper_continued']=fault['upper_during_loss']-fault['upper_before']>500000000
checks['lower_stopped']=fault['lower_during_loss']-fault['lower_before']<=100000000
checks['restored_data_without_motion']=p.ready and mission[-1]['state']=='FAILED' and fault['lower_after']>fault['lower_during_loss']
report['checks']=checks;report['status']='PASS' if all(checks.values()) else 'FAIL'
print(report['status'],checks,'task_duration',report['task_duration_sim_s'],'final',final['pos'],flush=True)
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
finally:
report.update(mission=mission,mux=mux,service_samples=states,fault_event=fault,actuator_commands=actuator)
if p is not None:
report['physical_poses']=p.truth_poses
report['navigation_status']=p.navigation_status
if args.fault in ('mission_loss','mux_loss') and 'pid' in fault and sim.owns(fault['pid']):
import signal
os.kill(fault['pid'],signal.SIGKILL);fault['cleanup']='owned stopped process killed after measurement; never resumed motion'
report['ros_cleanup_errors']=shutdown_probe(p);report['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
if __name__=='__main__':sys.exit(main())
+3 -2
View File
@@ -71,7 +71,8 @@ class NavProbe(Probe):
return req.xml
def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settle_timeout=0., sample_hook=None):
def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settle_timeout=0., sample_hook=None, sample_interval=.1):
if not 0<sample_interval<=.1:raise ValueError('sample_interval must be in (0,.1]')
first = p.get_state()
old_id = p.status[-1].goal_id if p.status else 0
start_cmd = len(p.commands)
@@ -85,7 +86,7 @@ def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settl
t0, wall_end = p.now(), time.monotonic()+300
samples = []
while p.now()-t0 < timeout and time.monotonic() < wall_end:
p.pump(.1)
p.pump(sample_interval)
truth = p.get_state()
if truth is None:
raise RuntimeError('missing independent Gazebo truth')
+3 -3
View File
@@ -6,7 +6,7 @@ import numpy as np
import yaml
import rclpy
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,json_value
from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,vehicle_ranges,MOUNT,json_value
def main():
@@ -35,8 +35,8 @@ def main():
for j,f in enumerate(frames[::max(1,len(frames)//6)]):
take=np.arange(0,len(f['xyz']),max(1,len(f['xyz'])//500));xyz=f['xyz'][take];distance=np.linalg.norm(xyz,axis=1)
pos,q=interpolate(moving['states'],f['t']+f['offsets'][take]*1e-9)
origins=pos+rotate(q,np.tile([0.,0.,.3],(len(pos),1)))
directions=rotate(q,xyz/distance[:,None]);expected_range=ray_ranges(origins,directions,shapes)
origins=pos+rotate(q,np.tile(MOUNT,(len(pos),1)))
directions=rotate(q,xyz/distance[:,None]);expected_range=np.minimum(ray_ranges(origins,directions,shapes),vehicle_ranges(xyz/distance[:,None]))
valid=np.isfinite(expected_range)&(expected_range>.1)&(expected_range<40)
residuals.extend((distance-expected_range)[valid]);saved['xyz_%d'%j]=xyz;saved['expected_%d'%j]=expected_range
errors=np.array(residuals)
+2 -2
View File
@@ -69,7 +69,7 @@ def check_phase(probe, out, yaw):
pr, pw = pr[good], pw[good]
c, sn = math.cos(truth['yaw']), math.sin(truth['yaw'])
R = np.array([[c, -sn, 0], [sn, c, 0], [0, 0, 1]])
expected = (pr + [0, 0, .30]) @ R.T + truth['pos']
expected = (pr + [.015, 0, .33]) @ R.T + truth['pos']
error = float(np.max(np.linalg.norm(expected - pw, axis=1)))
floor = int(np.count_nonzero(np.abs(pw[:, 2]) < .005))
north = int(np.count_nonzero((np.abs(pw[:, 1]-5.5) < .005) & (pw[:, 2] >= -.005)
@@ -90,7 +90,7 @@ def check_phase(probe, out, yaw):
west_wall_correct=west > 2,
odom_frames=body.header.frame_id == 'world' and body.child_frame_id == 'base_link'
and sensor.header.frame_id == 'world' and sensor.child_frame_id == 'lidar',
sensor_mount=abs(shift-.30) < .001)
sensor_mount=abs(shift-.33) < .001)
np.savez_compressed(out / ('cloud_yaw_%d.npz' % round(yaw*180/math.pi)),
raw=pr, world=pw, expected=expected)
return dict(yaw=yaw, checks=checks, ok=all(checks.values()), settle=settle,
+1 -1
View File
@@ -46,7 +46,7 @@ class SlopeProbe(Probe):
if raw is None:
return
pr,pw = points(raw),points(m)
self_hit = (np.abs(pr[:,0])<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]>=-.47)&(pr[:,2]<=-.20)
self_hit = (np.abs(pr[:,0]+.015)<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]+.33>=-.17)&(pr[:,2]+.33<=.28)
roi = np.isfinite(pw).all(1)&(~self_hit)&(pw[:,0]>-.5)&(pw[:,0]<2.4)&(pw[:,1]>3.1)&(pw[:,1]<3.9)
pc=pw[roi]
if len(pc)>20:
+69
View File
@@ -0,0 +1,69 @@
#!/usr/bin/python3
"""Check the measured vehicle envelope and sensor reference points before Gazebo.
Independent acceptance targets are the user's 2026-11-10 measurements. This
checks generated geometry/configuration; runtime rays/navigation remain separate.
"""
import argparse
import json
from pathlib import Path
import xml.etree.ElementTree as ET
import numpy as np
import xacro
import yaml
from check_omni_robot import check_model_geometry
ROOT = Path(__file__).resolve().parents[2]
ROBOT = ROOT / 'sim_ws/src/r2027_robot_description'
BASE_HEIGHT = .15
OPTICAL = np.array([.015, 0., .48 - BASE_HEIGHT])
IMU = OPTICAL + [.011, .02329, -.04412]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--out', required=True)
out = Path(parser.parse_args().out).resolve()
out.mkdir(parents=True, exist_ok=True)
checks = {}
report = {'status': 'INVALID', 'checks': checks,
'scope': 'generated SDF and configuration; not runtime acceptance'}
try:
geometry = check_model_geometry(str(out), 'contact')
report['geometry'] = geometry
checks['vehicle_envelope'] = geometry['ok'] and np.allclose(
geometry['size_xyz'], [.8, .8, .41], atol=1e-9, rtol=0)
checks['base_ground_reference'] = abs(geometry['ground_below_base_link'] - BASE_HEIGHT) < 1e-9
root = ET.fromstring(xacro.process_file(str(ROBOT / 'sdf/r2027_omni_robot.sdf.xacro'),
mappings={'lidar': 'true', 'sensor_model': 'mid360', 'drive': 'contact'}).toxml())
(out / 'mid360_expanded.sdf').write_bytes(ET.tostring(root))
optical = np.fromstring(root.findtext(".//plugin[@name='mid360_sensor']/lidar_position"), sep=' ')
imu = np.fromstring(root.findtext(".//sensor[@name='mid360_imu']/pose"), sep=' ')[:3]
checks['physical_optical_mount'] = np.allclose(optical, OPTICAL, atol=1e-9, rtol=0)
checks['physical_imu_mount'] = np.allclose(imu, IMU, atol=1e-9, rtol=0)
for name in ('lio_navigation', 'lio_terrain'):
cfg = yaml.safe_load((ROOT / f'sim_ws/src/br_sim_bringup/config/{name}.yaml').read_text())
parameters = cfg['lio_navigation_adapter']['ros__parameters']
checks[name + '_optical'] = np.allclose(parameters['lidar_position_base'], OPTICAL, atol=1e-9, rtol=0)
checks[name + '_imu'] = np.allclose(parameters['imu_position_base'], IMU, atol=1e-9, rtol=0)
inertia = root.find('.//inertial')
mass = float(inertia.findtext('mass'))
com = np.fromstring(inertia.findtext('pose'), sep=' ')[:3]
diagonal = np.array([float(inertia.findtext('inertia/' + key)) for key in ('ixx', 'iyy', 'izz')])
checks['inertia_physical'] = bool(mass > 0 and np.all(diagonal > 0) and np.all(2 * diagonal < diagonal.sum()))
checks['combined_com'] = np.allclose(com, [0., 0., (5.51*.09 + 4*1.2*(-.05))/10.31], atol=1e-9, rtol=0)
report.update(optical_base_m=optical.tolist(), imu_base_m=imu.tolist(),
nominal_optical_above_ground_m=float(optical[2] + BASE_HEIGHT),
assumed_mass_kg=mass, assumed_com_m=com.tolist(),
assumed_inertia_diagonal_kg_m2=diagonal.tolist())
report['status'] = 'PASS' if all(checks.values()) else 'FAIL'
except Exception as error:
report['error'] = repr(error)
(out / 'result.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
if __name__ == '__main__':
raise SystemExit(main())
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/python3
"""Independent regression for dual-lidar self-occlusion and clearance evidence.
Analytic intersections inspect the generated collision SDF, rather than treating
missing self returns (which are filtered downstream) as proof of clear sight.
Gazebo navigation remains a separate runtime check.
"""
import math
from pathlib import Path
import unittest
import xml.etree.ElementTree as ET
import numpy as np
import xacro
from check_dual_lidar import rectangle_gap,swept_clearance
MODEL=Path(__file__).resolve().parents[1]/'src/r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro'
def rotation(rpy):
r,p,y=rpy;cr,sr=math.cos(r),math.sin(r);cp,sp=math.cos(p),math.sin(p);cy,sy=math.cos(y),math.sin(y)
return np.array([[cy*cp,cy*sp*sr-sy*cr,cy*sp*cr+sy*sr],
[sy*cp,sy*sp*sr+cy*cr,sy*sp*cr-cy*sr],[-sp,cp*sr,cp*cr]])
def collision_parts(root):
# The supported proxy is one rigid body with primitive collisions.
links=root.findall('.//model/link')
if len(links)!=1 or not np.allclose(np.fromstring(links[0].findtext('pose','0 0 0 0 0 0'),sep=' '),0.):
raise ValueError('ray acceptance must be extended for changed link transforms')
parts=[]
for collision in links[0].findall('collision'):
pose=np.fromstring(collision.findtext('pose','0 0 0 0 0 0'),sep=' ')
geometry=collision.find('geometry');shape=next(iter(geometry))
if shape.tag not in ('box','cylinder'):raise ValueError('unsupported collision shape '+shape.tag)
parts.append((pose[:3],rotation(pose[3:]),shape))
return parts
def first_hit(parts,origin,direction):
candidates=[]
for center,R,shape in parts:
p=R.T@(origin-center);v=R.T@direction
if shape.tag=='box':
half=np.fromstring(shape.findtext('size'),sep=' ')/2;lo,hi=-float('inf'),float('inf')
for j in range(3):
if abs(v[j])<1e-12:
if abs(p[j])>half[j]:hi=-float('inf');break
else:
bounds=sorted(((-half[j]-p[j])/v[j],(half[j]-p[j])/v[j]))
lo=max(lo,bounds[0]);hi=min(hi,bounds[1])
if hi>=max(lo,0.):candidates.append(max(lo,0.))
else:
radius=float(shape.findtext('radius'));half=float(shape.findtext('length'))/2
a=float(v[:2]@v[:2]);b=2*float(p[:2]@v[:2]);c=float(p[:2]@p[:2])-radius**2
discriminant=b*b-4*a*c
if a>1e-14 and discriminant>=0:
for t in ((-b-math.sqrt(discriminant))/(2*a),(-b+math.sqrt(discriminant))/(2*a)):
if t>=0 and abs(p[2]+t*v[2])<=half+1e-12:candidates.append(t)
if abs(v[2])>1e-12:
for z in (-half,half):
t=(z-p[2])/v[2]
if t>=0 and np.linalg.norm(p[:2]+t*v[:2])<=radius+1e-12:candidates.append(t)
return min(candidates,default=float('inf'))
class ModelSightTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.text=xacro.process_file(str(MODEL),mappings={'dual_lidar':'true','lidar':'true','sensor_model':'mid360','drive':'contact'}).toxml()
cls.root=ET.fromstring(cls.text);cls.parts=collision_parts(cls.root)
cls.origin=np.fromstring(cls.root.findtext(".//plugin[@name='mid360_low_sensor']/lidar_position"),sep=' ')
def test_forward_horizontal_and_downward_rays_clear_proxy(self):
# Low-obstacle returns lie below the optical plane. Test the complete
# -7..0 degree band at 0.5 degree elevation / 0.25 degree azimuth steps.
blocked=[]
for elevation in np.deg2rad(np.linspace(-7.,0.,15)):
for azimuth in np.linspace(-math.pi/2,math.pi/2,721):
v=np.array([math.cos(elevation)*math.cos(azimuth),math.cos(elevation)*math.sin(azimuth),math.sin(elevation)])
if first_hit(self.parts,self.origin,v)<2.:blocked.append((azimuth,elevation))
self.assertEqual(blocked,[])
def test_rear_stays_physically_occluded(self):
self.assertAlmostEqual(first_hit(self.parts,self.origin,np.array([-1.,0.,0.])),.705,places=9)
def test_historical_wheels_reproduce_front_occlusion(self):
root=ET.fromstring(self.text)
for collision in root.findall('.//collision'):
if 'wheel' in collision.attrib['name']:
pose=np.fromstring(collision.findtext('pose'),sep=' ');pose[0]=math.copysign(.30,pose[0])
collision.find('pose').text=' '.join(map(str,pose))
parts=collision_parts(root);blocked=[]
for azimuth in np.linspace(-math.pi/2,math.pi/2,721):
v=np.array([math.cos(azimuth),math.sin(azimuth),0.])
if first_hit(parts,self.origin,v)<2.:blocked.append(azimuth)
self.assertGreater(len(blocked),0)
class ClearanceTests(unittest.TestCase):
def test_known_axis_aligned_gaps_and_overlap(self):
self.assertAlmostEqual(rectangle_gap([.7,0.],0.,[0.,0.]),.175)
self.assertAlmostEqual(rectangle_gap([.5,0.],0.,[0.,0.]),-.025)
self.assertAlmostEqual(rectangle_gap([.525,0.],0.,[0.,0.]),0.)
def test_rotated_rectangle_does_not_use_enclosing_aabb(self):
self.assertGreater(rectangle_gap([.65,.65],math.pi/4,[0.,0.]),.17)
self.assertLess(.65-.125-.4*math.sqrt(2),0.) # AABB would falsely overlap.
def test_between_sample_collision_cannot_hide_behind_clear_endpoints(self):
states=[dict(stamp=t,pos=[x,0.,.15],yaw=0.) for t,x in ((0.,-1.),(.1,1.))]
self.assertGreater(rectangle_gap(states[0]['pos'],0.,[0.,0.]),0.)
self.assertGreater(rectangle_gap(states[1]['pos'],0.,[0.,0.]),0.)
result=swept_clearance(states,[0.,0.]);self.assertLess(result['min_gap_bound_m'],0.)
def test_clearance_covers_rotation_corners(self):
states=[dict(stamp=t,pos=[0.,0.,.15],yaw=y) for t,y in ((0.,0.),(.1,math.pi/2))]
self.assertGreater(rectangle_gap([0.,0.],0.,[.65,0.]),0.)
self.assertLess(swept_clearance(states,[.65,0.])['min_gap_bound_m'],0.)
if __name__=='__main__':unittest.main()
+187
View File
@@ -0,0 +1,187 @@
#!/usr/bin/python3
"""Reference-frame, deskew, schema and fail-closed tests for dual perception."""
from pathlib import Path
import math
import sys
import unittest
import numpy as np
import rclpy
from livox_ros_driver2.msg import CustomMsg,CustomPoint
from nav_msgs.msg import Odometry
from rclpy.qos import ReliabilityPolicy
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/br_sim_bringup/scripts'))
from dual_lidar_fusion import interpolate_poses,project_scan,cloud_message,DualLidarFusion
from lio_navigation_adapter import rotation
LOW=np.array([.325,0.,.044]);LEFT=rotation([0,0,math.sin(math.pi/4),math.cos(math.pi/4)])
def stationary():return [(float(t),np.zeros(3),np.array([0.,0.,0.,1.])) for t in np.arange(0.,.111,.01)]
class GeometryTests(unittest.TestCase):
def test_vehicle_front_half_is_lower_negative_y(self):
raw=np.array([[0,-1,0],[0,1,0],[1,0,0],[-1,0,0],[-1,.1,0]])
world,origins,t,_=project_scan(raw,np.arange(5)*1000000,0,stationary(),LOW,LEFT,True)
np.testing.assert_allclose(world,np.array([[1,0,0],[0,1,0],[0,-1,0]])+LOW,atol=1e-12)
np.testing.assert_allclose(origins,np.tile(LOW,(3,1)));np.testing.assert_array_equal(t,[0,2000000,3000000])
def test_front_sector_moves_with_vehicle_heading(self):
q=np.array([0,0,math.sin(math.pi/4),math.cos(math.pi/4)])
history=[(t,p,q) for t,p,_ in stationary()]
world,origins,_,_=project_scan([[0,-1,0]],[0],0,history,LOW,LEFT,True)
np.testing.assert_allclose(world,[[0,1.325,.044]],atol=1e-12)
np.testing.assert_allclose(origins,[[0,.325,.044]],atol=1e-12)
def test_motion_compensates_every_actual_sample_and_origin(self):
ts=np.arange(0.,.101,.01);history=[];raw=[];expected_origins=[];target=np.array([2.,.2,.08])
for t in ts:
q=np.array([0.,0.,math.sin(t*1.5),math.cos(t*1.5)]);R=rotation(q);p=np.array([t*.4,0.,0.])
history.append((float(t),p,q))
sample=np.array([0.,.025,.05,.075,.099])
for t in sample:
R=rotation([0,0,math.sin(t*1.5),math.cos(t*1.5)]);p=np.array([t*.4,0.,0.])
raw.append(LEFT.T@(R.T@(target-p)-LOW));expected_origins.append(p+R@LOW)
world,origins,t,_=project_scan(raw,np.rint(sample*1e9).astype(np.int64),0,history,LOW,LEFT,True)
np.testing.assert_allclose(world,np.tile(target,(len(sample),1)),atol=1e-10)
np.testing.assert_allclose(origins,expected_origins,atol=1e-10)
np.testing.assert_array_equal(t,np.rint(sample*1e9).astype(np.int64))
self.assertGreater(np.linalg.norm(origins[0]-origins[-1]),.05)
def test_pose_coverage_never_extrapolates(self):
for t in (-.01,.12):
with self.assertRaises(LookupError):interpolate_poses(stationary(),[t])
with self.assertRaises(ValueError):interpolate_poses([stationary()[0],stationary()[-1]],[.05])
def test_slerp_handles_equivalent_quaternion_signs(self):
history=stationary();history[1]=(history[1][0],history[1][1],-history[1][2])
_,q=interpolate_poses(history,[.005]);np.testing.assert_allclose(abs(q[0]),[0,0,0,1])
def test_invalid_offsets_rejected(self):
for offsets in ([-1],[100000000],[5000000,1000000]):
with self.assertRaises(ValueError):project_scan(np.tile([0,-1.,0],(len(offsets),1)),offsets,0,stationary(),LOW,LEFT,True)
def test_world_cloud_preserves_origin_time_identity(self):
times=np.array([1000000011,1099000011],dtype=np.int64)
m=cloud_message(np.array([[1,2,3],[4,5,6]]),np.tile(LOW,(2,1)),times,[0,1],1099000011)
self.assertEqual(m.header.frame_id,'world');self.assertEqual(m.header.stamp.nanosec,99000011)
fields={f.name:f for f in m.fields}
def read(name,dtype):return np.ndarray((m.width,),dtype=dtype,buffer=m.data,offset=fields[name].offset,strides=(m.point_step,))
np.testing.assert_array_equal(read('sensor_id','u1'),[0,1])
np.testing.assert_array_equal(read('time_sec','<i4'),[1,1]);np.testing.assert_array_equal(read('time_nanosec','<u4'),[11,99000011])
np.testing.assert_allclose(read('origin_z','<f4'),[.044,.044])
class Recorder:
def __init__(self):self.messages=[]
def publish(self,m):self.messages.append(m)
class NodeTests(unittest.TestCase):
@classmethod
def setUpClass(cls):rclpy.init()
@classmethod
def tearDownClass(cls):rclpy.shutdown()
def setUp(self):
self.node=DualLidarFusion();self.node.now_s=lambda:.11
self.node.full=Recorder();self.node.planning=Recorder();self.node.history.extend(stationary())
def tearDown(self):self.node.destroy_node()
def scan(self,i,t=0):
m=CustomMsg();m.header.frame_id='lidar' if i==0 else 'lidar_low';m.lidar_id=i
m.timebase=t;m.header.stamp.sec=t//1000000000;m.header.stamp.nanosec=t%1000000000
p=CustomPoint();p.x=2. if i==0 else 0.;p.y=0. if i==0 else -2.;p.offset_time=99000000
m.points=[p];m.point_num=1;return m
def test_pose_subscription_preserves_reliable_bursts(self):
subscription=next(s for s in self.node.subscriptions if s.topic_name=='/sim/navigation/body_odom')
self.assertEqual(subscription.qos_profile.depth,100)
self.assertEqual(subscription.qos_profile.reliability,ReliabilityPolicy.RELIABLE)
def test_clock_callback_order_does_not_drop_near_future_pose(self):
m=Odometry();m.header.frame_id='world';m.child_frame_id='lio_base_link'
m.header.stamp.nanosec=120000000;m.pose.pose.orientation.w=1.
self.node.on_pose(m)
self.assertAlmostEqual(self.node.history[-1][0],.12)
self.assertFalse(self.node.fault)
def test_pair_required_and_each_source_retained(self):
self.node.on_scan(0,self.scan(0));self.node.flush();self.assertFalse(self.node.full.messages)
self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertEqual(len(self.node.full.messages),1);self.assertEqual(self.node.full.messages[0].width,2)
# Repeated timer ticks cannot republish old data to fake freshness.
self.node.flush();self.assertEqual(len(self.node.full.messages),1)
def test_exact_scan_end_pose_does_not_wait_for_another_frame(self):
self.node.history.clear();self.node.now_s=lambda:41.4
for ns in (41260000000,41300000000,41361000000):
m=Odometry();m.header.frame_id='world';m.child_frame_id='lio_base_link'
m.header.stamp.sec=ns//1000000000;m.header.stamp.nanosec=ns%1000000000;m.pose.pose.orientation.w=1.
self.node.on_pose(m)
self.node.on_scan(0,self.scan(0,41262000000));self.node.on_scan(1,self.scan(1,41262000000))
self.node.flush();self.assertEqual(len(self.node.full.messages),1)
self.assertEqual(self.node.full.messages[0].header.stamp.nanosec,361000000)
def test_complete_pose_coverage_still_waits_for_source_clock(self):
self.node.now_s=lambda:.09
self.node.on_scan(0,self.scan(0));self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertFalse(self.node.full.messages)
self.node.now_s=lambda:.11;self.node.flush()
self.assertEqual(len(self.node.full.messages),1)
self.assertEqual(self.node.full.messages[0].header.stamp.nanosec,99000000)
def test_incomplete_pose_history_drops_pair_then_recovers(self):
self.node.history.clear();self.node.history.extend([stationary()[0],stationary()[-1]])
self.node.on_scan(0,self.scan(0));self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertFalse(self.node.fault);self.assertFalse(self.node.full.messages)
self.node.history.clear();self.node.history.extend((t+.1,p,q) for t,p,q in stationary())
self.node.now_s=lambda:.22
self.node.on_scan(0,self.scan(0,100000000));self.node.on_scan(1,self.scan(1,100000000));self.node.flush()
self.assertEqual(len(self.node.full.messages),1)
def test_wrong_frame_stops_publication(self):
m=self.scan(1);m.header.frame_id='lidar';self.node.on_scan(1,m)
self.assertTrue(self.node.fault);self.node.on_scan(0,self.scan(0));self.node.flush()
self.assertFalse(self.node.full.messages)
def test_timebase_mismatch_stops_publication(self):
m=self.scan(1);m.header.stamp.nanosec=1;self.node.on_scan(1,m);self.assertTrue(self.node.fault)
def test_stale_pair_never_published(self):
self.node.now_s=lambda:1.
self.node.on_scan(0,self.scan(0));self.node.on_scan(1,self.scan(1));self.node.flush()
self.assertFalse(self.node.full.messages)
def test_ground_uses_raw_geometry_even_with_world_height_and_tilt_error(self):
# A controlled +3 cm world offset and pitch error make a real ground
# point exceed the old 15 mm world-Z cut. The raw lower optics still
# measure the same ground and an 8 cm obstacle, separated by 80 mm.
q=np.array([0.,math.sin(-.01/2),0.,math.cos(-.01/2)])
self.node.history.clear();self.node.history.extend((t,np.array([0.,0.,.18]),q) for t,_,_ in stationary())
upper=self.scan(0);lower=self.scan(1);lower.points=[]
for height in (0.,.02,.08):
p=CustomPoint();p.x=0.;p.y=-1.;p.z=float(height-.194);p.offset_time=99000000
lower.points.append(p)
lower.point_num=len(lower.points)
self.node.on_scan(0,upper);self.node.on_scan(1,lower);self.node.flush()
full=self.node.full.messages[-1];planning=self.node.planning.messages[-1]
raw=np.stack([np.ndarray((full.width,),dtype='<f4',buffer=full.data,offset=i*4,strides=(full.point_step,)) for i in range(3)],axis=1)
filtered=np.stack([np.ndarray((planning.width,),dtype='<f4',buffer=planning.data,offset=i*4,strides=(planning.point_step,)) for i in range(3)],axis=1)
self.assertGreater(raw[1,2],.015)
self.assertTrue(np.isnan(filtered[1]).all())
self.assertTrue(np.isfinite(filtered[2:]).all()) # 2 cm and 8 cm tops kept.
for i in range(full.width):
start=i*full.point_step+12;end=(i+1)*full.point_step
self.assertEqual(bytes(full.data[start:end]),bytes(planning.data[start:end]))
self.assertEqual(full.header,planning.header)
def test_negative_world_drift_keeps_low_tops_from_both_lidars(self):
self.node.history.clear();self.node.history.extend((t,np.array([0.,0.,.11]),q) for t,_,q in stationary())
for i,optical_height in ((0,.48),(1,.194)):
m=self.scan(i);m.points=[]
for height in (0.,.02,.08):
p=CustomPoint();p.x=2. if i==0 else 0.;p.y=0. if i==0 else -2.
p.z=float(height-optical_height);p.offset_time=99000000;m.points.append(p)
m.point_num=len(m.points);self.node.on_scan(i,m)
self.node.flush();full=self.node.full.messages[-1];planning=self.node.planning.messages[-1]
def xyz(m):return np.stack([np.ndarray((m.width,),dtype='<f4',buffer=m.data,offset=i*4,strides=(m.point_step,)) for i in range(3)],axis=1)
raw=xyz(full);filtered=xyz(planning)
self.assertTrue(np.isnan(filtered[[0,3]]).all())
self.assertTrue(np.isfinite(filtered[[1,2,4,5]]).all())
self.assertTrue((raw[[1,4],2]<0.).all()) # 2 cm tops are below world zero.
if __name__=='__main__':unittest.main()
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/python3
"""Known slope filtering, pitched extrinsics and explicit planning-only priors."""
from pathlib import Path
import sys,unittest
import numpy as np
import rclpy,yaml
ROOT=Path(__file__).resolve().parents[2]
sys.path.insert(0,str(ROOT/'sim_ws/src/br_sim_bringup/scripts'))
sys.path.insert(0,str(ROOT/'minco_ws/src/scan/step_blocker/step_blocker'))
from dual_lidar_fusion import DualLidarFusion,cloud_message,project_scan
from lio_navigation_adapter import rotation
from step_blocker_node import append_ray_priors,StepBlocker
from test_dual_lidar import Recorder,stationary
class PriorTests(unittest.TestCase):
def message(self):
return cloud_message(np.array([[1.,2.,3.],[np.nan,np.nan,np.nan]]),np.array([[0.,0.,.48],[.325,0.,.194]]),np.array([1000000001,1099000000]),[0,1],1099000000)
def test_real_bytes_and_header_unchanged(self):
m=self.message();out=append_ray_priors(m,[np.array([[2.,3.,.6]])])
self.assertEqual(bytes(out.data[:len(m.data)]),bytes(m.data));self.assertEqual(out.header,m.header)
self.assertEqual(out.width,3);self.assertEqual(out.row_step,99)
data=np.frombuffer(out.data[-33:],dtype=np.dtype({'names':['xyz','origin','sec','ns','id'],'formats':[('<f4',3),('<f4',3),'<i4','<u4','u1'],'offsets':[0,12,24,28,32],'itemsize':33}))
np.testing.assert_equal(data['xyz'],data['origin']);self.assertEqual(data['id'][0],255)
self.assertEqual(data['sec'][0],0);self.assertEqual(data['ns'][0],0)
def test_empty_walls_passthrough(self):
m=self.message();self.assertEqual(append_ray_priors(m,[]),m)
def test_corrupt_schema_rejected(self):
for kind in ('field','frame','truncated','endian','identity'):
m=self.message()
if kind=='field':m.fields.pop()
elif kind=='frame':m.header.frame_id='lidar'
elif kind=='truncated':m.data.pop()
elif kind=='endian':m.is_bigendian=True
else:m.data[32]=255
with self.subTest(kind=kind),self.assertRaises(ValueError):append_ray_priors(m,[])
def test_pitched_both_optical_origins_and_lower_sector(self):
angle=.169;R=rotation([0,np.sin(angle/2),0,np.cos(angle/2)]);q=np.array([0,np.sin(angle/2),0,np.cos(angle/2)])
h=[(0.,np.array([1.,2.,.4]),q),(.1,np.array([1.,2.,.4]),q)]
low_R=rotation([0,0,np.sqrt(.5),np.sqrt(.5)])
for mount,mount_R in ((np.array([.015,0,.33]),np.eye(3)),(np.array([.325,0,.044]),low_R)):
body=np.array([1.5,0.,-.1]);raw=mount_R.T@(body-mount)
xyz,origins,t,z=project_scan([raw],[50000000],0,h,mount,mount_R,True)
np.testing.assert_allclose(xyz,[np.array([1,2,.4])+R@body]);np.testing.assert_allclose(origins,[np.array([1,2,.4])+R@mount])
self.assertAlmostEqual(z[0],-.1)
class TerrainTests(unittest.TestCase):
@classmethod
def setUpClass(cls):rclpy.init()
@classmethod
def tearDownClass(cls):rclpy.shutdown()
def test_known_slope_removes_ground_keeps_15cm_and_preserves_raw(self):
node=DualLidarFusion();node.now_s=lambda:.11;node.full=Recorder();node.planning=Recorder()
node.ground_mode='known_terrain';node.planes=[[-5,5,-5,5,-.17,0,.6]]
q=np.array([0,np.sin(.17/2),0,np.cos(.17/2)]);pos=np.array([0.,0.,.75]);R=rotation(q)
node.history.extend((t,pos,q) for t,_,_ in stationary())
from livox_ros_driver2.msg import CustomMsg,CustomPoint
for i,mount in enumerate(node.mounts):
m=CustomMsg();m.header.frame_id='lidar' if i==0 else 'lidar_low';m.lidar_id=i
for elevation in (0.,.15):
target=np.array([1.5,0.,.6-.17*1.5+elevation]);raw=node.rotations[i].T@(R.T@(target-pos)-mount)
p=CustomPoint();p.x,p.y,p.z=map(float,raw);p.offset_time=99000000;m.points.append(p)
m.point_num=2;node.on_scan(i,m)
node.flush()
full=node.full.messages[-1];filtered=node.planning.messages[-1]
def xyz(m):return np.stack([np.ndarray((m.width,),dtype='<f4',buffer=m.data,offset=4*i,strides=(m.point_step,)) for i in range(3)],axis=1)
self.assertTrue(np.isfinite(xyz(full)).all());self.assertTrue(np.isnan(xyz(filtered)[[0,2]]).all())
np.testing.assert_equal(xyz(filtered)[[1,3]],xyz(full)[[1,3]])
for i in range(4):self.assertEqual(bytes(full.data[i*33+12:(i+1)*33]),bytes(filtered.data[i*33+12:(i+1)*33]))
node.destroy_node()
def test_single_lidar_default_remains_xyz_mode(self):
node=StepBlocker();self.assertFalse(node.preserve_ray_metadata);node.destroy_node()
def test_survey_planes_match_existing_terrain_profile(self):
folder=ROOT/'sim_ws/src/br_sim_bringup/config'
a=yaml.safe_load((folder/'lio_terrain.yaml').read_text())['lio_navigation_adapter']['ros__parameters']
b=yaml.safe_load((folder/'dual_lidar_terrain.yaml').read_text())['dual_lidar_fusion']['ros__parameters']
self.assertEqual(a['traversable_planes'],b['traversable_planes']);self.assertEqual(a['surface_tolerance'],b['surface_tolerance'])
if __name__=='__main__':unittest.main()
+97 -7
View File
@@ -23,26 +23,27 @@ class Recorder:
class GeometryTests(unittest.TestCase):
def test_known_start_maps_imu_and_optical_origins(self):
imu=np.array([.011,.02329,.25588]);prior=np.array([-4.5,4.5,.15,math.pi/2])
imu=np.array([.026,.02329,.28588]);prior=np.array([-4.5,4.5,.15,math.pi/2])
p=np.array([.2,-.3,.02]);q=np.array([0.,0.,math.sin(.35),math.cos(.35)])
a=FixedAlignment(prior,imu,p,q)
base,bq=a.pose(p,q,-imu);lidar,_=a.pose(p,q,np.array([0.,0.,.3])-imu)
base,bq=a.pose(p,q,-imu);lidar,_=a.pose(p,q,np.array([.015,0.,.33])-imu)
np.testing.assert_allclose(base,prior[:3],atol=1e-12)
np.testing.assert_allclose(lidar,prior[:3]+[0,0,.3],atol=1e-12)
np.testing.assert_allclose(lidar,prior[:3]+[0,.015,.33],atol=1e-12)
self.assertAlmostEqual(math.atan2(rotation(bq)[1,0],rotation(bq)[0,0]),math.pi/2)
old_t=a.t.copy();later,_=a.pose(p+[1,0,0],q,-imu)
np.testing.assert_allclose(later-base,a.R@[1,0,0],atol=1e-12)
np.testing.assert_array_equal(a.t,old_t)
def test_rotating_imu_lever_arm_by_finite_difference(self):
offset=np.array([.011,.02329,.25588]);yaw=.8;w=.4;dt=1e-6
offset=np.array([.026,.02329,.28588]);yaw=.8;w=.4;dt=1e-6
def R(y):return np.array([[math.cos(y),-math.sin(y),0],[math.sin(y),math.cos(y),0],[0,0,1]])
imu_world_velocity=(R(yaw+w*dt)@offset-R(yaw-w*dt)@offset)/(2*dt)
imu_body_velocity=R(yaw).T@imu_world_velocity
base=shifted_twist(imu_body_velocity,[0,0,w],-offset)
np.testing.assert_allclose(base,[0,0,0],atol=1e-10)
lidar=shifted_twist(imu_body_velocity,[0,0,w],np.array([0,0,.3])-offset)
np.testing.assert_allclose(lidar,[0,0,0],atol=1e-10)
lidar=shifted_twist(imu_body_velocity,[0,0,w],np.array([.015,0,.33])-offset)
# A forward-offset optical origin has a genuine lateral velocity when yawing.
np.testing.assert_allclose(lidar,[0,.015*w,0],atol=1e-10)
def test_invalid_quaternions_are_rejected(self):
for values in ([0,0,0,0],[0,0,0,2],[float('nan'),0,0,1]):
@@ -66,6 +67,30 @@ class AdapterTests(unittest.TestCase):
for t in np.arange(1.,2.11,.05):self.node.on_odom(self.odom(float(t)))
self.assertIsNotNone(self.node.alignment)
def test_stationary_velocity_jitter_allows_fixed_start(self):
for i,t in enumerate(np.arange(1.,2.11,.01)):
m=self.odom(float(t));m.twist.twist.linear.x=.03 if i%2 else -.03
self.node.on_odom(m)
self.assertIsNotNone(self.node.alignment)
def test_moving_vehicle_cannot_lock_fixed_start(self):
for t in np.arange(1.,3.11,.01):
m=self.odom(float(t));m.pose.pose.position.x=.03*(t-1.)
m.twist.twist.linear.x=.03;self.node.on_odom(m)
self.assertIsNone(self.node.alignment)
self.assertFalse(self.node.fault)
# Small position drift must not hide a sustained speed above threshold.
for t in np.arange(3.12,4.31,.01):
m=self.odom(float(t));m.twist.twist.linear.x=.03;self.node.on_odom(m)
self.assertIsNone(self.node.alignment)
def test_position_motion_rejects_even_with_zero_mean_velocity(self):
for i,t in enumerate(np.arange(1.,3.11,.01)):
m=self.odom(float(t));m.pose.pose.position.x=.03*(t-1.)
m.twist.twist.linear.x=.03 if i%2 else -.03
self.node.on_odom(m)
self.assertIsNone(self.node.alignment)
def test_stale_and_discontinuous_odometry_never_reanchors(self):
self.anchor();t=self.node.odom_stamp;translation=self.node.alignment.t.copy()
stale=self.odom(t);self.time=t+.3;count=len(self.node.body_pub.messages)
@@ -81,6 +106,8 @@ class AdapterTests(unittest.TestCase):
self.anchor();n=111;data=np.zeros((n,6),dtype='<f4');data[:,3]=1.
data[0,3:]=[0,0,-.3] # self return, regardless of latest robot pose
data[1,2]=-self.node.alignment.t[2] # world ground
data[2,3:]=[-.43,0,-.07] # new 41 cm roof, rear edge inside 2 cm margin
data[3,3:]=[.42,0,-.07] # outside front margin after optical x=.015 shift
m=PointCloud2();m.header.frame_id='camera_init';m.header.stamp=self.odom(self.time).header.stamp
m.height=1;m.width=n;m.point_step=24;m.row_step=24*n
m.fields=[PointField(name=name,offset=i*4,datatype=PointField.FLOAT32,count=1) for i,name in enumerate(('x','y','z','lidar_x','lidar_y','lidar_z'))]
@@ -89,7 +116,7 @@ class AdapterTests(unittest.TestCase):
full=self.node.world_pub.messages[-1];filtered=self.node.planning_pub.messages[-1]
self.assertEqual(filtered.header.stamp,m.header.stamp)
xyz=np.stack(float_fields(filtered,('x','y','z')),axis=-1).reshape(n,3)
self.assertTrue(np.isnan(xyz[:2]).all());self.assertTrue(np.isfinite(xyz[2:]).all())
self.assertTrue(np.isnan(xyz[:3]).all());self.assertTrue(np.isfinite(xyz[3:]).all())
for a,b in zip(float_fields(full,('lidar_x','lidar_y','lidar_z')),float_fields(filtered,('lidar_x','lidar_y','lidar_z'))):np.testing.assert_array_equal(a,b)
def test_wrong_source_frame_latches_stop(self):
@@ -125,6 +152,69 @@ class AdapterTests(unittest.TestCase):
self.node.health();self.assertTrue(self.node.ready_pub.messages[-1].data)
self.time+=.02;self.node.odom_stamp=self.time;self.node.cloud_stamp=self.time
self.node.health();self.assertFalse(self.node.ready_pub.messages[-1].data)
def test_selected_fused_cloud_not_display_cloud_controls_readiness(self):
self.anchor();self.node.planning_topic='/sim/navigation/terrain_planning_cloud'
self.node.cloud_stamp=self.time-1.;self.node.downstream_stamp=self.time
self.node.health();self.assertTrue(self.node.ready_pub.messages[-1].data)
self.time+=.31;self.node.odom_stamp=self.time;self.node.cloud_stamp=self.time
self.node.health();self.assertFalse(self.node.ready_pub.messages[-1].data)
def test_future_downstream_cloud_waits_for_clock(self):
self.anchor();previous=self.time;self.node.downstream_stamp=previous
m=PointCloud2();m.header.frame_id='world';m.width=1;m.height=1
m.header.stamp.sec=int(previous+.08);m.header.stamp.nanosec=round(((previous+.08)%1)*1e9)
self.node.on_planning_cloud(m);self.assertEqual(self.node.downstream_stamp,previous)
self.time=previous+.08;self.node.health();self.assertAlmostEqual(self.node.downstream_stamp,self.time)
def test_odom_before_clock_waits_then_keeps_original_stamp(self):
self.anchor();previous=self.time;m=self.odom(previous+.08);self.time=previous
count=len(self.node.body_pub.messages);self.node.on_odom(m)
self.assertEqual(len(self.node.body_pub.messages),count)
self.node.health();self.assertEqual(len(self.node.body_pub.messages),count)
self.time=previous+.08;self.node.health()
self.assertEqual(len(self.node.body_pub.messages),count+1)
self.assertEqual(self.node.body_pub.messages[-1].header.stamp,m.header.stamp)
self.assertFalse(self.node.pending_odom)
def test_cloud_before_clock_is_deferred_without_timestamp_rewrite(self):
self.anchor();previous=self.time;odom=self.odom(previous+.08);self.time=previous
self.node.on_odom(odom)
data=np.ones((111,6),dtype='<f4');m=PointCloud2();m.header=copy.deepcopy(odom.header)
m.height=1;m.width=len(data);m.point_step=24;m.row_step=24*len(data)
m.fields=[PointField(name=n,offset=i*4,datatype=PointField.FLOAT32,count=1) for i,n in enumerate(('x','y','z','lidar_x','lidar_y','lidar_z'))]
m.data=array('B',data.tobytes());self.node.on_cloud(m)
self.assertFalse(self.node.world_pub.messages)
self.time=previous+.08;self.node.health()
self.assertEqual(self.node.world_pub.messages[-1].header.stamp,m.header.stamp)
self.assertFalse(self.node.pending_cloud)
def test_expired_pending_data_does_not_become_fresh_after_clock_jump(self):
self.anchor();previous=self.time;m=self.odom(previous+.08);self.time=previous
count=len(self.node.body_pub.messages);self.node.on_odom(m)
self.time=previous+.4;self.node.health()
self.assertEqual(len(self.node.body_pub.messages),count)
self.assertFalse(self.node.ready_pub.messages[-1].data)
def test_pending_source_order_cannot_hide_backwards_time(self):
self.anchor();previous=self.time
a=self.odom(previous+.08);b=self.odom(previous+.04);self.time=previous
self.node.on_odom(a);self.node.on_odom(b)
self.time=previous+.08;self.node.health()
self.assertIn('backwards',self.node.fault)
def test_far_future_samples_do_not_publish_or_fill_pending_queue(self):
self.anchor();previous=self.time;m=self.odom(previous+1.);self.time=previous
count=len(self.node.body_pub.messages);self.node.on_odom(m)
self.assertFalse(self.node.pending_odom);self.assertEqual(self.node.future_dropped,1)
self.assertEqual(len(self.node.body_pub.messages),count)
def test_stopped_clock_pending_queue_is_bounded_and_fails_closed(self):
self.anchor();previous=self.time;m=self.odom(previous+.08);self.time=previous
count=len(self.node.body_pub.messages)
for _ in range(65):self.node.on_odom(copy.deepcopy(m))
self.assertEqual(len(self.node.pending_odom),64)
self.assertIn('queue overflow',self.node.fault)
self.assertEqual(len(self.node.body_pub.messages),count)
if __name__=='__main__':unittest.main()
+30
View File
@@ -0,0 +1,30 @@
// Standalone numerical regression: no robot, ROS graph or filter execution.
#include <sensor_timestamp.h>
#include <sensor_time_rate_limiter.h>
#include <cassert>
#include <iostream>
int main()
{
int previously_truncated = 0;
for (std::int64_t frame = 0; frame < 6000; ++frame) {
const std::int64_t expected = frame * 100000000 + 99000000;
const double stamp = frame * .1 + .099;
const auto old = static_cast<std::int64_t>(std::floor(stamp)) * 1000000000 +
static_cast<std::uint32_t>((stamp - std::floor(stamp)) * 1e9);
previously_truncated += old != expected;
assert(point_lio::rounded_sensor_time_ns(stamp) == expected);
}
assert(previously_truncated > 0);
assert(point_lio::rounded_sensor_time_ns(38.319) == INT64_C(38319000000));
assert(point_lio::rounded_sensor_time_ns(.9999999996) == INT64_C(1000000000));
assert(point_lio::rounded_sensor_time_ns(1.0000000004) == INT64_C(1000000000));
point_lio::SensorTimeRateLimiter limiter;
assert(limiter.should_publish(.090,100));
assert(!limiter.should_publish(.099,100));
assert(limiter.should_publish(.099,100,true));
assert(!limiter.should_publish(.099,100,true));
assert(limiter.should_publish(.109,100));
std::cout << "6000 scan endpoint roundtrips and 3 boundary cases passed; old truncation mismatches: "
<< previously_truncated << '\n';
}
+216
View File
@@ -0,0 +1,216 @@
#!/usr/bin/python3
"""Safety leases, geometry, phase history and terminal-stop tests (no Gazebo)."""
from pathlib import Path
import sys,math,unittest
import numpy as np
import rclpy
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/br_sim_bringup/scripts'))
from mission_command_mux import select_command
from ramp_mission import RampMission,body_command,envelope,obstacle_count,ground_height,speed_target
from lio_navigation_adapter import multiply,rotation
from scan_planner_msgs.msg import TrajectoryStatus
from std_srvs.srv import Trigger
from livox_ros_driver2.msg import CustomMsg,CustomPoint
from sensor_msgs_py.point_cloud2 import create_cloud_xyz32
from std_msgs.msg import Header
def qpose(pitch=0.,yaw=math.pi):
return multiply(np.array([0.,0.,math.sin(yaw/2),math.cos(yaw/2)]),np.array([0.,math.sin(pitch/2),0.,math.cos(pitch/2)]))
class Recorder:
def __init__(self):self.messages=[]
def publish(self,m):self.messages.append(m)
class MuxTests(unittest.TestCase):
def test_no_lease_health_or_expired_lease_is_zero(self):
nav=(1.,(.3,0.,0.));lease=dict(stamp=1.,since=.9,mode='NAV')
for now,l,health in ((1.,None,True),(1.,lease,False),(1.16,lease,True),(.99,lease,True)):
self.assertEqual(select_command(now,l,nav,None,health)[0],(0.,0.,0.))
def test_only_selected_source_can_drive(self):
for mode,expected in (('NAV',(.2,.1,0.)),('RAMP',(.3,0.,.1)),('STOP',(0.,0.,0.))):
self.assertEqual(select_command(1.,dict(stamp=1.,since=.9,mode=mode),(1.,(.2,.1,0.)),(1.,(.3,0.,.1)),True)[0],expected)
def test_commands_before_grant_or_stale_cannot_reappear(self):
for t in (.8,.89,1.01):
self.assertEqual(select_command(1.,dict(stamp=1.,since=.9,mode='RAMP'),None,(t,(.3,0.,0.)),True)[0],(0.,0.,0.))
def test_nonfinite_or_missing_source_is_zero(self):
lease=dict(stamp=1.,since=.9,mode='NAV')
self.assertEqual(select_command(1.,lease,None,None,True)[0],(0.,0.,0.))
self.assertEqual(select_command(1.,lease,(1.,(float('nan'),0.,0.)),None,True)[0],(0.,0.,0.))
def test_linear_norm_not_just_individual_axes_is_limited(self):
cmd,_=select_command(1.,dict(stamp=1.,since=.9,mode='NAV'),(1.,(.5,.5,1.)),None,True)
self.assertAlmostEqual(math.hypot(*cmd[:2]),.5);self.assertEqual(cmd[2],.5)
def test_opt_in_limits_and_expiry_at_fast_speed(self):
lease=dict(stamp=1.,since=.9,mode='NAV');nav=(1.,(.7,.7,1.))
cmd,_=select_command(1.,lease,nav,None,True,.7,.8)
self.assertAlmostEqual(math.hypot(*cmd[:2]),.7);self.assertEqual(cmd[2],.8)
self.assertEqual(select_command(1.16,lease,nav,None,True,.7,.8)[0],(0.,0.,0.))
cmd,_=select_command(1.,lease,(1.,(2.,2.,1.)),None,True,2.,1.)
self.assertAlmostEqual(math.hypot(*cmd[:2]),2.)
self.assertEqual(select_command(1.16,lease,(1.,cmd),None,True,2.,1.)[0],(0.,0.,0.))
class GeometryTests(unittest.TestCase):
def test_fast_profile_brakes_before_low_speed_zone_and_still_limits_final_approach(self):
self.assertEqual(speed_target(1.,1.2,.2,True),1.2)
self.assertLess(speed_target(-.7,1.2,.2,True),1.2)
self.assertLessEqual(speed_target(-1.,1.2,.2,True),.2)
self.assertLess(speed_target(-1.292,1.2,.2,True),.05)
# Full-speed braking corridor must grow when speed rises, rather than
# using only a small fixed lookahead after the experimental speed lift.
obstacle=np.array([[.4,3.5125,float(ground_height(.4))+.2]])
self.assertEqual(obstacle_count(obstacle,[1.6,3.5125,.5],qpose(-.169),.3,1.2),0)
self.assertEqual(obstacle_count(obstacle,[1.6,3.5125,.5],qpose(-.169),1.2,1.2),1)
def test_crest_braking_begins_before_crest_zone(self):
self.assertEqual(speed_target(1.,.7,.2),.7)
self.assertLess(speed_target(.2,.7,.2),.7)
self.assertEqual(speed_target(-.25,.7,.2),.2)
self.assertEqual(speed_target(-.8,.7,.2),.2)
self.assertLess(speed_target(-1.2,.7,.2),.1)
def test_pitch_correct_body_forward_and_cross_track(self):
for pitch in (0.,-.169):
q=qpose(pitch);cmd=body_command(q,.3,.01);world=rotation(q)@np.array([cmd[0],cmd[1],0.])
self.assertLess(world[0],0.);self.assertGreater(world[1],0.);self.assertAlmostEqual(cmd[0],.3,places=10)
def test_whole_body_on_platform_requires_more_than_flat_pitch(self):
for x,clear in ((-1.,False),(-1.3,True),(-1.5,False)):
lo,hi=envelope([x,3.5125,.75],qpose())
self.assertEqual(lo[0]>=-1.76 and hi[0]<=-.84,clear)
def test_obstacle_guard_keeps_floor_and_outside_rail_separate(self):
cloud=np.array([[1.1,3.5125,float(ground_height(1.1))],[1.1,3.025,.9],[1.1,3.5125,float(ground_height(1.1))+.2]])
self.assertEqual(obstacle_count(cloud,[1.6,3.5125,.5],qpose(-.169),.3),1)
class StateTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Never let service tests address a live mission on simulation domain 77.
import os
os.environ['ROS_LOCALHOST_ONLY']='1'
rclpy.init(domain_id=189)
@classmethod
def tearDownClass(cls):rclpy.shutdown()
def setUp(self):
self.n=RampMission();self.t=10.;self.n.now=lambda:self.t
for name in ('lease_pub','direct_pub','report_pub','goal_pub'):setattr(self.n,name,Recorder())
self.n.state='ENTRY';self.n.start_time=10.;self.n.cloud=np.empty((0,3));self.n.gyro=np.zeros(3)
def tearDown(self):self.n.destroy_node()
def tick(self,x=3.7,y=3.5125,pitch=0.,speed=0.,dt=.1):
self.t+=dt;self.n.pose=dict(stamp=self.t,p=np.array([x,y,.15+float(ground_height(x))]),q=qpose(pitch),velocity=np.array([speed,0.,0.]),speed=speed,wz=0.)
self.n.pose_window.append(self.n.pose)
while self.n.pose_window and self.n.pose_window[0]['stamp']<self.t-(.35 if self.n.fast else .5):self.n.pose_window.popleft()
self.n.ready=True;self.n.ready_stamp=self.t;self.n.imu_stamp=self.t;self.n.cloud_stamp=self.t;self.n.lower_stamp=self.t;self.n.tick()
def test_initial_flat_never_means_arrival(self):
for _ in range(8):self.tick()
self.assertEqual(self.n.state,'ENTRY');self.assertFalse(self.n.seen_slope)
def test_missing_incline_is_latched_failure(self):
self.tick(x=1.7);self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
self.tick();self.assertEqual(self.n.state,'FAILED')
def test_sustained_incline_then_flat_still_needs_full_vehicle_clear(self):
for _ in range(4):self.tick(x=2.1,pitch=-.169)
self.assertEqual(self.n.state,'CLIMB');self.assertTrue(self.n.seen_slope)
self.tick(x=-.3,pitch=-.169);self.assertEqual(self.n.state,'CREST')
for _ in range(4):self.tick(x=-1.)
self.assertEqual(self.n.state,'PLATFORM')
self.tick(x=-1.3);self.assertEqual(self.n.state,'SETTLE')
for _ in range(10):self.tick(x=-1.3,speed=.08)
self.assertEqual(self.n.state,'SETTLE')
for _ in range(100):self.tick(x=-1.3,dt=.02)
self.assertEqual(self.n.state,'SUCCEEDED');self.assertEqual(self.n.mode,'STOP')
def test_lateral_drift_stops_before_leaving_lane(self):
self.tick(x=1.5,y=3.56,pitch=-.169);self.assertEqual(self.n.reason,'estimated_lateral_clearance');self.assertEqual(self.n.mode,'STOP')
def test_new_obstacle_revokes_ramp_drive(self):
self.n.seen_slope=True;self.n.state='CLIMB'
self.n.cloud=np.array([[1.1,3.5125,float(ground_height(1.1))+.2]])
self.tick(x=1.6,pitch=-.169,speed=.3);self.assertEqual(self.n.reason,'obstacle_in_braking_corridor');self.assertEqual(self.n.mode,'STOP')
def test_stale_state_is_not_replaced_by_open_loop_motion(self):
self.tick();self.n.ready=False;self.t+=.02;self.n.tick()
self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
self.tick();self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
def test_raw_lower_loss_stops_before_fused_cloud_timeout(self):
self.tick();self.t+=.24
self.n.ready_stamp=self.t;self.n.pose['stamp']=self.t;self.n.imu_stamp=self.t;self.n.cloud_stamp=self.t
self.n.tick()
self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
self.assertEqual(self.n.health_failure['failed_checks'],['lower_scan'])
self.assertAlmostEqual(self.n.health_failure['sources']['lower_scan']['age_s'],.24)
captured=self.n.health_failure
self.tick();self.assertIs(self.n.health_failure,captured)
def test_fast_late_scan_holds_then_resumes_but_expiry_still_latches(self):
self.n.fast=True;self.n.ramp_speed=1.1;self.n.ramp_acceleration=2.
self.tick();self.t+=.16
for name in ('ready_stamp','imu_stamp','cloud_stamp'):setattr(self.n,name,self.t)
self.n.pose['stamp']=self.t;self.n.tick()
self.assertEqual(self.n.state,'ENTRY');self.assertEqual(self.n.mode,'STOP')
self.assertTrue(self.n.lower_hold);self.assertIsNone(self.n.health_failure)
self.tick();self.assertFalse(self.n.lower_hold);self.assertEqual(self.n.mode,'RAMP')
self.t+=.24
for name in ('ready_stamp','imu_stamp','cloud_stamp'):setattr(self.n,name,self.t)
self.n.pose['stamp']=self.t;self.n.tick()
self.assertEqual(self.n.state,'FAILED')
self.tick();self.assertEqual(self.n.state,'FAILED');self.assertEqual(self.n.mode,'STOP')
def test_single_delayed_lower_frame_does_not_latch_failure(self):
self.tick();self.t+=.199
self.n.ready_stamp=self.t;self.n.pose['stamp']=self.t;self.n.imu_stamp=self.t;self.n.cloud_stamp=self.t
self.n.tick();self.assertEqual(self.n.state,'ENTRY');self.assertIsNone(self.n.health_failure)
def test_future_cloud_waits_for_clock_without_replacing_fresh_input(self):
self.tick();previous=self.n.cloud_stamp
h=Header(frame_id='world');h.stamp.sec=10;h.stamp.nanosec=150000000
self.n.on_cloud(create_cloud_xyz32(h,[[10.,10.,0.]]))
self.n.tick();self.assertEqual(self.n.cloud_stamp,previous);self.assertEqual(self.n.state,'ENTRY')
self.t=10.16;self.n.tick();self.assertAlmostEqual(self.n.cloud_stamp,10.15);self.assertEqual(self.n.state,'ENTRY')
def test_queued_future_cloud_cannot_refresh_expired_data(self):
self.tick();self.t+=.31
h=Header(frame_id='world');h.stamp.sec=11
self.n.on_cloud(create_cloud_xyz32(h,[[10.,10.,0.]]))
self.n.ready_stamp=self.t;self.n.pose['stamp']=self.t;self.n.imu_stamp=self.t;self.n.lower_stamp=self.t
self.n.tick();self.assertEqual(self.n.health_failure['failed_checks'],['fused_cloud'])
def test_lower_watchdog_preserves_actual_source_time_and_clock_order(self):
self.n.state='IDLE';self.n.requested=False
m=CustomMsg();m.header.frame_id='lidar_low';m.header.stamp.sec=10;m.header.stamp.nanosec=100000000
m.timebase=10100000000;m.lidar_id=1;m.point_num=1
point=CustomPoint();point.offset_time=23000000;m.points=[point]
self.n.on_lower(m);self.t=10.12;self.n.tick();self.assertIsNone(self.n.lower_stamp)
self.t=10.13;self.n.tick();self.assertAlmostEqual(self.n.lower_stamp,10.123)
self.n.on_lower(m);self.n.tick();self.assertEqual(self.n.reason,'lower_time_backwards')
def test_wrong_lidar_cannot_refresh_lower_watchdog(self):
m=CustomMsg();m.header.frame_id='lidar';m.lidar_id=0
self.n.on_lower(m);self.assertEqual(self.n.reason,'invalid_lower_scan')
def test_terminal_navigation_result_survives_lease_age(self):
# Terminal status is an event, unlike ACTIVE's short-lived motion grant.
self.n.state='NAVIGATE';self.n.goal_sent=8.;self.n.wait_goal_id=0
status=TrajectoryStatus();status.goal_id=1;status.state=status.SUCCEEDED
status.header.stamp.sec=9;status.goal.x=3.7;status.goal.y=4.8
self.n.status=status
for _ in range(60):self.tick(x=3.7,y=4.8,dt=.02)
self.assertEqual(self.n.nav_index,1)
self.assertEqual(len(self.n.goal_pub.messages),1)
def test_stale_active_grant_cannot_move(self):
self.n.state='NAVIGATE';self.n.goal_sent=8.;self.n.wait_goal_id=0
status=TrajectoryStatus();status.goal_id=1;status.state=status.ACTIVE
status.header.stamp.sec=9;status.goal.x=3.7;status.goal.y=4.8;self.n.status=status
self.tick(x=3.7,y=4.8);self.assertEqual(self.n.mode,'STOP')
def test_fast_pass_through_requires_fresh_grant_and_revokes_it_for_new_goal(self):
self.n.fast=True;self.n.goals=[self.n.goals[0],self.n.goals[-1]]
self.n.state='NAVIGATE';self.n.goal_sent=8.;self.n.wait_goal_id=0
status=TrajectoryStatus();status.goal_id=1;status.state=status.ACTIVE
status.goal.x=3.7;status.goal.y=4.8;status.header.stamp.sec=9
self.n.status=status
self.tick(x=3.05,y=4.8)
self.assertEqual(self.n.nav_index,0) # Stale grant cannot advance.
status.header.stamp.sec=10;status.header.stamp.nanosec=200000000
self.tick(x=3.05,y=4.8)
self.assertEqual(self.n.nav_index,1)
self.assertEqual(self.n.wait_goal_id,1)
self.assertEqual(self.n.mode,'STOP')
self.assertEqual(len(self.n.goal_pub.messages),1)
self.assertAlmostEqual(self.n.goal_pub.messages[0].pose.position.y,3.5125)
def test_actual_start_and_cancel_services(self):
self.n.state='IDLE';self.n.requested=False
start=self.n.create_client(Trigger,'/ramp_mission/start')
cancel=self.n.create_client(Trigger,'/ramp_mission/cancel')
self.assertTrue(start.wait_for_service(timeout_sec=2.))
future=start.call_async(Trigger.Request());rclpy.spin_until_future_complete(self.n,future,timeout_sec=2.)
self.assertTrue(future.result().success);self.assertTrue(self.n.requested)
duplicate=start.call_async(Trigger.Request());rclpy.spin_until_future_complete(self.n,duplicate,timeout_sec=2.)
self.assertFalse(duplicate.result().success)
future=cancel.call_async(Trigger.Request());rclpy.spin_until_future_complete(self.n,future,timeout_sec=2.)
self.assertTrue(future.result().success);self.assertEqual(self.n.state,'FAILED')
if __name__=='__main__':unittest.main()
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/python3
"""Lost read-only responses may retry; a spawn must never be blindly repeated."""
from pathlib import Path
import sys
import unittest
from unittest.mock import patch
from types import SimpleNamespace
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/r2027_robot_description/scripts'))
from spawn_existing_world import call,query_existing_entity
class Future:
def __init__(self,complete):self.complete=complete;self.cancelled=False
def done(self):return self.complete
def exception(self):return None
def result(self):return SimpleNamespace(success=False)
def cancel(self):self.cancelled=True
class Client:
srv_name='/test_service'
def __init__(self,outcomes):self.outcomes=iter(outcomes);self.requests=[];self.removed=[];self.futures=[]
def call_async(self,request):
self.requests.append(request);future=Future(next(self.outcomes));self.futures.append(future);return future
def remove_pending_request(self,future):self.removed.append(future)
class SpawnQueryTests(unittest.TestCase):
def setUp(self):
self.now=0.;self.warnings=[]
self.node=SimpleNamespace(get_logger=lambda:SimpleNamespace(warning=self.warnings.append))
self.patches=[patch('spawn_existing_world.time.monotonic',lambda:self.now),
patch('spawn_existing_world.rclpy.spin_until_future_complete',self.spin)]
for p in self.patches:p.start()
def tearDown(self):
for p in reversed(self.patches):p.stop()
def spin(self,node,future,timeout_sec):
if not future.complete:self.now+=timeout_sec
def test_lost_first_query_response_retries_and_preserves_negative_result(self):
client=Client([False,True]);request=object()
self.assertFalse(query_existing_entity(self.node,client,request).success)
self.assertEqual(client.requests,[request,request]);self.assertEqual(self.now,3.)
self.assertTrue(client.futures[0].cancelled);self.assertEqual(len(client.removed),1)
def test_repeated_read_timeouts_keep_original_total_deadline(self):
client=Client([False]*5)
with self.assertRaises(TimeoutError):query_existing_entity(self.node,client,object())
self.assertEqual(self.now,15.);self.assertEqual(len(client.requests),5)
self.assertTrue(all(f.cancelled for f in client.futures))
def test_spawn_timeout_never_repeats_side_effect(self):
client=Client([False,True])
with self.assertRaises(TimeoutError):call(self.node,client,object(),120.)
self.assertEqual(len(client.requests),1);self.assertEqual(self.now,120.)
if __name__=='__main__':unittest.main()