Files
RC2027_BR_code/sim_ws/tools/check_point_lio.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

132 lines
7.8 KiB
Python

#!/usr/bin/python3
"""Evaluate existing Point-LIO with one fixed initial SE3 alignment; no truth feedback."""
import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import subprocess
import sys
import time
import numpy as np
import rclpy
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])
def matrix(q):
return rotate(np.broadcast_to(q,(3,4)),np.eye(3)).T
class LioProbe(SensorProbe):
def __init__(self):
super().__init__();self.estimates=[]
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',self.on_estimate,100)
def on_estimate(self,m):
p=m.pose.pose.position;q=m.pose.pose.orientation;v=m.twist.twist.linear
self.estimates.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
frame=m.header.frame_id,child=m.child_frame_id,pos=[p.x,p.y,p.z],
q=[q.x,q.y,q.z,q.w],body_velocity=[v.x,v.y,v.z],received_sim=self.now()))
def main():
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
ap.add_argument('--case',choices=('flat','slope'),default='flat');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)
result=dict(status='INVALID',case=args.case,checks={},collector_sha256=hashlib.sha256(source).hexdigest())
sim,p=Sim(str(out/'sim')),None
try:
spawn=(3.5,3.5125,.15,0.) if args.case=='slope' else (-4.5,4.5,.15,0.)
ok,why=sim.start(localization=True,spawn=spawn);result['startup']=why
if not ok:raise RuntimeError(why)
rclpy.init();p=LioProbe()
if not p.wait_clock():raise RuntimeError('missing clock')
deadline=time.monotonic()+60
while time.monotonic()<deadline:
rclpy.spin_once(p,timeout_sec=.02)
if len(p.frames)>=10 and len(p.imus)>=100 and p.get_state() is not None:break
else:raise RuntimeError('model/sensors not ready')
# CLI discovery may take wall time; perform it before the measured truth
# interval, so it cannot create an unobserved hole in the trajectory.
for name,cmd in [('node_info',['ros2','node','info','/sim/lio/point_lio_sim']),
('parameters',['ros2','param','dump','/sim/lio/point_lio_sim'])]:
r=subprocess.run(cmd,capture_output=True,text=True,timeout=30)
(out/(name+'.txt')).write_text(r.stdout+r.stderr)
if r.returncode:raise RuntimeError(name+' unavailable')
initial=phase(p,(0.,0.,0.),4.)
if len(p.estimates)<100:raise RuntimeError('Point-LIO output missing or startup incomplete')
init_est=p.estimates[-1]
pos,q=interpolate(initial['states'],np.array([init_est['t']]))
R=matrix(q[0])@matrix(np.array(init_est['q'])).T
truth_imu=pos[0]+rotate(q,IMU_OFFSET[None,:])[0]
translation=truth_imu-R@np.array(init_est['pos'])
result['alignment']=dict(stamp=init_est['t'],rotation=R.tolist(),translation=translation.tolist(),
method='one initial stationary IMU pose; fixed for entire route; evaluator only')
records={}
motions=([('up_first',(-.25,0.,0.),10.),('hill_stop',(0.,0.,0.),2.),
('up_second',(-.25,0.,0.),8.8),('top_stop',(0.,0.,0.),1.5),
('down',(.25,0.,0.),18.8),('final_stop',(0.,0.,0.),1.5)] if args.case=='slope' else
[('forward',(.2,0.,0.),2.5),('lateral',(0.,-.2,0.),2.),
('turn',(0.,0.,.3),2.),
('return_x',(-.2*math.cos(.6),.2*math.sin(.6),0.),2.5),
('return_y',(.2*math.sin(.6),.2*math.cos(.6),0.),2.),
('turn_back',(0.,0.,-.3),2.),('final_stop',(0.,0.,0.),1.5)])
for name,cmd,duration in motions:
records[name]=phase(p,cmd,duration)
(out/(name+'_truth.json')).write_text(json.dumps(records[name],indent=2)+'\n')
print(name,records[name]['states'][-1]['pos'],'estimates',len(p.estimates),flush=True)
truth=initial['states']+[s for record in records.values() for s in record['states']]
estimates=[e for e in p.estimates if init_est['t']<=e['t']<=truth[-1]['stamp']]
if len(estimates)<100:raise RuntimeError('insufficient estimates in truth interval')
pos,q=interpolate(truth,np.array([e['t'] for e in estimates]))
expected=pos+rotate(q,np.broadcast_to(IMU_OFFSET,pos.shape))
predicted=np.array([R@np.array(e['pos'])+translation for e in estimates])
position_error=np.linalg.norm(predicted-expected,axis=1)
angle_error=np.array([math.acos(np.clip((np.trace(matrix(tq).T@R@matrix(np.array(e['q'])))-1)/2,-1,1)) for tq,e in zip(q,estimates)])
estimates_t=np.array([e['t'] for e in estimates]);lags=np.array([e['received_sim']-e['t'] for e in estimates])
graph=(out/'node_info.txt').read_text();subscribers=graph.split('Subscribers:')[1].split('Publishers:')[0]
# A namespaced node's inputs must be sensors and clock, never truth odom/TF.
checks=result['checks']
checks.update(input_isolation='/sim/mid360/lidar:' in subscribers and '/sim/mid360/imu:' in subscribers and
all(topic not in subscribers for topic in ('/odom:','/body_odom:','/tf:','/tf_static:')),
estimated_tf_disabled=bool(p.tf_pairs) and set(p.tf_pairs)=={'odom->base_link'},
frames=all(e['frame']=='camera_init' and e['child']=='body' for e in estimates),
finite=bool(np.isfinite(predicted).all() and np.isfinite(angle_error).all()),
position=bool(np.max(position_error)<.10),orientation=bool(np.max(angle_error)<.10),
timestamps=bool(np.all(np.diff(estimates_t)>0) and np.max(np.diff(estimates_t))<.2),
latency=bool(np.quantile(lags,.95)<.3 and np.max(lags)<1.0))
if args.case=='slope':
checks['physical_top_landing']=abs(records['top_stop']['states'][-1]['pos'][2]-.749)<.03
checks['physical_return']=abs(records['final_stop']['states'][-1]['pos'][2]-.149)<.02
else:
checks['physical_excitation']=max(s['yaw'] for s in truth)-min(s['yaw'] for s in truth)>.5 and max(s['pos'][0] for s in truth)-min(s['pos'][0] for s in truth)>.4
result.update(checks=checks,estimates=estimates,truth=truth,
observed_tf_edges=p.tf_pairs,observed_static_tf_edges=p.tf_static_pairs,
max_position_error_m=float(np.max(position_error)),p95_position_error_m=float(np.quantile(position_error,.95)),
max_angle_error_rad=float(np.max(angle_error)),p95_lag_s=float(np.quantile(lags,.95)),
max_lag_s=float(np.max(lags)),median_rate_hz=float(1/np.median(np.diff(estimates_t))),
last_position_error_m=float(position_error[-1]))
np.savez_compressed(out/'comparison.npz',times=estimates_t,expected=expected,predicted=predicted,
position_error=position_error,angle_error=angle_error,lags=lags)
result['status']='PASS' if all(checks.values()) else 'FAIL'
print(json.dumps({k:v for k,v in result.items() if k not in ('truth','estimates')},indent=2,default=json_value),flush=True)
except Exception as exc:
result['status']='INVALID';result['error']=repr(exc);print(result['error'],flush=True)
if p is not None:result['estimates']=p.estimates
finally:
result['ros_cleanup_errors'] = shutdown_probe(p)
result['teardown']=sim.stop()
(out/'result.json').write_text(json.dumps(result,indent=2,default=json_value)+'\n')
return {'PASS':0,'FAIL':30,'INVALID':40}[result['status']]
if __name__=='__main__':sys.exit(main())