#!/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 corridor_bounds(s,side): """Score symmetric corridors in +Y coordinates; retain raw truth in report.""" lo,hi=bounds(s) if side=='blue':lo[1],hi[1]=-hi[1],-lo[1] return lo,hi 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 and .5=entry and ((-1.15=.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=side_sign*3.5125;req.initial_pose.position.z=float((1.6119-.597)/3.5+.15);req.initial_pose.orientation.w=1. req.xml='true0.25 0.25 0.30' 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(corridor_bounds(s,args.side)[0][1]-3.025,4.-corridor_bounds(s,args.side)[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]-side_sign*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=corridor_bounds(final,args.side) 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=corridor_bounds(s,args.side) # 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_name,'::'+platform_name)) 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,side_sign*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_name in c.collision1_name or ramp_name 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())