#!/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 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,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().08: 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: 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 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 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 # 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]) # 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 -.35old_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, 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 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.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, 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, 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,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]) 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()) 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,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,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()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','/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.)+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='true0.25 0.25 0.60.25 0.25 0.6' 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);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[ft].header.stamp!=p.clouds[pt].header.stamp and time.monotonic()height(1.)+min(.12,args.obstacle_height-.015))&(full[:,2]=15 and retained==count) 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]=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 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()) 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['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']] if __name__=='__main__':sys.exit(main())