Files
RC2027_BR_code/sim_ws/tools/check_lio_terrain.py
T
Kevin ca61aa63b5 fix(sim): clean up interrupted runs and document usage and migration
Prevent ROS cleanup errors from skipping owned Gazebo process teardown.
Reject occupied master ports before launching nodes and stop the stack when
its GUI closes. Add --gui to the automatic LIO navigation checks.

Expand the root README and add a beginner guide covering manual goals,
automatic tests, restart troubleshooting, MID360 assumptions and staged
migration to real hardware. Preserve lifecycle and GUI validation evidence.

Validation: three navigation restart cycles, two busy-port rejection cases,
SIGINT/SIGHUP cleanup and a GUI straight-route check. Current source hashes,
Python syntax, documentation shell syntax and local links verified. Hardware
migration remains unverified; no push performed.
2026-11-08 22:44:02 +08:00

194 lines
14 KiB
Python

#!/usr/bin/python3
"""Independent physical acceptance of LIO reference-path navigation on known ramps."""
import argparse,hashlib,json,math,os,signal,sys,time
from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.msg import ContactsState
from gazebo_msgs.srv import SpawnEntity
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Path as NavPath
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
from sensor_msgs.msg import PointCloud2
from check_omni_robot import Sim,sim_env, shutdown_probe
from check_lio_navigation import LioNavProbe,graph_evidence
from check_mid360 import interpolate,rotate,json_value
from check_sim_lidar import points
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):
super().__init__();self.out=out;self.contacts=[];self.snapshots=[];self.next_snapshot=0.
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 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')
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))
def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
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')
msg=NavPath();msg.header.frame_id='world';msg.header.stamp=p.get_clock().now().to_msg()
for x in xs:
pose=PoseStamped();pose.header=msg.header;pose.pose.position.x=float(x);pose.pose.position.y=y
pose.pose.position.z=.15 if blocked and x<-1.8 else height(x);pose.pose.orientation.w=1.;msg.poses.append(pose)
if goal_y is not None:msg.poses[-1].pose.position.y=goal_y
target_y=msg.poses[-1].pose.position.y
p.path_pub.publish(msg);start=p.now();deadline=time.monotonic()+500;states=[first];readiness=[];fault={}
while p.now()-start<85 and time.monotonic()<deadline:
p.pump(.04);s=p.get_state()
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=[])
try:
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)
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
status=p.status[-1];terminal=status.header.stamp.sec+status.header.stamp.nanosec*1e-9
braking=[];latency=None
while p.now()-terminal<.2:
p.pump(.005);s=p.get_state()
if s is None:raise RuntimeError('missing braking state')
braking.append(s)
if math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02:latency=s['stamp']-terminal;break
rest=[];t=p.now()
while p.now()-t<1.1:
p.pump(.04);s=p.get_state()
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
# 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])
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),
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,
estimated_lateral_error=max(abs(errors[:,1]))<.03,estimated_vertical_error=max(abs(errors[:,2]))<.05)
if fault_sim is not None:
stopped=next((s['stamp']-fault['start'] for s in fault.get('samples',[]) if math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02),None)
late=[s for s in fault.get('samples',[]) if s['stamp']-fault['start']>.6]
fault['stop_latency_sim_s']=stopped
checks.update(downstream_hold_exercised=bool(fault.get('samples')),
downstream_readiness_revoked=any(not r['ready'] for r in fault.get('readiness',[])),
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 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_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,
real_ramp_contacts=any(('ramp_north' if y>0 else 'ramp_south') in pair for m in contacts for c in m.states for pair in (c.collision1_name,c.collision2_name)),
penetration=bool(contacts) and max((d for m in contacts for c in m.states for d in c.depths),default=1)<.005)
return dict(checks=checks,ok=all(checks.values()),goal=[xs[-1],target_y,msg.poses[-1].pose.position.z+.15],
position_error_m=xy_error,stop_drift_m=drift,braking_latency_sim_s=latency,
estimated_max_abs_xyz_error_m=np.max(np.abs(errors),axis=0).tolist(),min_full_body_clearance_m=float(min(clearance)),
contact_evidence=dict(messages=len(contacts),
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,
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,
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])
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('--sensor-profile',choices=('ideal','mild','stress'),default='ideal')
args=ap.parse_args()
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())
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
if not ok:raise RuntimeError(why)
rclpy.init();p=TerrainProbe(out)
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',))
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.orientation.w=1.
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>'
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()
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'])
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)
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')
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
(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['cloud_snapshots']=p.snapshots;report['navigation_status']=p.navigation_status
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
finally:
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())