#!/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','.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()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().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()=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']))&(times100 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())