2026-11-08 19:04:32 +08:00
#!/usr/bin/python3
"""Independent physical acceptance of LIO reference-path navigation on known ramps."""
import argparse , hashlib , json , math , os , signal , sys , time
2026-11-12 16:42:07 +08:00
from collections import deque
2026-11-08 19:04:32 +08:00
from pathlib import Path
import numpy as np
import rclpy
from gazebo_msgs.msg import ContactsState
from gazebo_msgs.srv import SpawnEntity
2026-11-12 16:42:07 +08:00
from std_srvs.srv import Trigger
from std_msgs.msg import String
from livox_ros_driver2.msg import CustomMsg
2026-11-08 19:04:32 +08:00
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
2026-11-08 22:44:02 +08:00
from check_omni_robot import Sim , sim_env , shutdown_probe
2026-11-08 19:04:32 +08:00
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 ):
2026-11-12 16:42:07 +08:00
def __init__ ( self , out , dual = False ):
2026-11-08 19:04:32 +08:00
super () . __init__ (); self . out = out ; self . contacts = []; self . snapshots = []; self . next_snapshot = 0.
2026-11-12 16:42:07 +08:00
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 )
2026-11-08 19:04:32 +08:00
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 )
2026-11-12 16:42:07 +08:00
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 ))
2026-11-08 19:04:32 +08:00
def capture ( self ):
if self . now () < self . next_snapshot : return
2026-11-12 16:42:07 +08:00
full = self . clouds . get ( '/sim/navigation/fused_cloud' if self . dual else '/sim/navigation/cloud_registered' )
filtered = self . clouds . get ( '/sim/navigation/fused_planning_cloud' if self . dual else '/sim/navigation/planning_cloud' )
2026-11-08 19:04:32 +08:00
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 ))
2026-11-12 16:42:07 +08:00
if self . dual :
final = self . clouds . get ( '/sim/navigation/terrain_planning_cloud' )
if final is not None and final . header . stamp == filtered . header . stamp :
def read ( m , offset , dtype ): return np . ndarray (( m . width ,), dtype = dtype , buffer = m . data , offset = offset , strides = ( m . point_step ,))
real_ids = read ( full , 32 , 'u1' ); ids = read ( final , 32 , 'u1' ); prior = ids == 255
same = bytes ( final . data [: len ( filtered . data )]) == bytes ( filtered . data )
metadata = all ( bytes ( full . data [ i * 33 + 12 :( i + 1 ) * 33 ]) == bytes ( filtered . data [ i * 33 + 12 :( i + 1 ) * 33 ]) for i in range ( full . width ))
zero_rays = all ( np . array_equal ( read ( final , i * 4 , '<f4' )[ prior ], read ( final ,( i + 3 ) * 4 , '<f4' )[ prior ]) for i in range ( 3 ))
zero_time = all (( read ( final , offset , dtype )[ prior ] == 0 ) . all () for offset , dtype in (( 24 , '<i4' ),( 28 , '<u4' )))
self . metadata_checks . append ( dict ( stamp = self . now (), both_sources = bool (( real_ids == 0 ) . any () and ( real_ids == 1 ) . any ()),
real_bytes_preserved = same , filter_metadata_preserved = metadata , explicit_prior_ids = bool ( prior . any ()), zero_length_priors = zero_rays , prior_has_no_acquisition_time = zero_time ))
2026-11-08 19:04:32 +08:00
2026-11-12 16:42:07 +08:00
def run_path ( p , xs , y , blocked = False , fault_sim = None , goal_y = None , lower_loss = False ):
2026-11-08 19:04:32 +08:00
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 :
2026-11-12 16:42:07 +08:00
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' )
2026-11-08 19:04:32 +08:00
try :
2026-11-12 16:42:07 +08:00
if pid is not None : os . kill ( pid , signal . SIGSTOP )
2026-11-08 19:04:32 +08:00
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 :
2026-11-12 16:42:07 +08:00
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 )
2026-11-08 19:04:32 +08:00
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
2026-11-12 16:42:07 +08:00
# 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 ]))
2026-11-08 19:04:32 +08:00
# 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 ])
2026-11-12 16:42:07 +08:00
# 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 ]
2026-11-08 19:04:32 +08:00
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 ),
2026-11-12 16:42:07 +08:00
truth_crosschecked = max ( position_error ) < .002 and max ( angle_error ) < .005 and truth_gap <= .12 ,
2026-11-08 19:04:32 +08:00
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 ))
2026-11-12 16:42:07 +08:00
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 )
2026-11-08 19:04:32 +08:00
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 ,
2026-11-12 16:42:07 +08:00
ramp_pitch = bool ( mid ) and max ( abs ( s [ 'rpy' ][ 1 ] - math . cos ( first [ 'yaw' ]) * math . atan2 ( .597 , 3.5 )) for s in mid ) < .05 ,
2026-11-08 19:04:32 +08:00
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 ,
2026-11-12 16:42:07 +08:00
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 )),
2026-11-08 19:04:32 +08:00
estimation_pairs = [ dict ( stamp = float ( t ), estimate = e . tolist (), truth_interpolated = g . tolist ()) for t , e , g in zip ( times , estimated , pos )],
2026-11-12 16:42:07 +08:00
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 ,
2026-11-08 19:04:32 +08:00
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' )
2026-11-12 16:42:07 +08:00
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' )
2026-11-08 19:04:32 +08:00
ap . add_argument ( '--sensor-profile' , choices = ( 'ideal' , 'mild' , 'stress' ), default = 'ideal' )
args = ap . parse_args ()
2026-11-12 16:42:07 +08:00
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' )
2026-11-08 19:04:32 +08:00
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 ())
2026-11-12 16:42:07 +08:00
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 ())
2026-11-08 19:04:32 +08:00
sim = Sim ( str ( out / 'sim' )); p = None ; y = 3.5125 if args . side == 'red' else - 3.5125
try :
2026-11-12 16:42:07 +08:00
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
2026-11-08 19:04:32 +08:00
if not ok : raise RuntimeError ( why )
2026-11-12 16:42:07 +08:00
rclpy . init (); p = TerrainProbe ( out , args . dual_lidar ); p . sensor_profile = args . sensor_profile
2026-11-08 19:04:32 +08:00
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' )
2026-11-12 16:42:07 +08:00
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' ,))
2026-11-08 19:04:32 +08:00
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'
2026-11-12 16:42:07 +08:00
req . initial_pose . position . x = 1. ; req . initial_pose . position . y = y ; req . initial_pose . position . z = height ( 1. ) + args . obstacle_height / 2
2026-11-08 19:04:32 +08:00
req . initial_pose . orientation . w = 1.
2026-11-12 16:42:07 +08:00
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 ])
2026-11-08 19:04:32 +08:00
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>'
2026-11-12 16:42:07 +08:00
req . xml = req . xml . replace ( '0.25 0.25 0.6' , '0.25 0.25 ' + str ( args . obstacle_height ))
2026-11-08 19:04:32 +08:00
response = p . _call ( p . spawn , req , timeout = 15 )
if not response or not response . success : raise RuntimeError ( 'obstacle fixture not spawned' )
2026-11-12 16:42:07 +08:00
( 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'
2026-11-08 19:04:32 +08:00
deadline = time . monotonic () + 5
2026-11-12 16:42:07 +08:00
while p . clouds [ ft ] . header . stamp != p . clouds [ pt ] . header . stamp and time . monotonic () < deadline : p . pump ( .02 )
if p . clouds [ ft ] . header . stamp != p . clouds [ pt ] . header . stamp : raise RuntimeError ( 'no matched obstacle cloud stamps' )
full = points ( p . clouds [ ft ]); filtered = points ( p . clouds [ pt ])
2026-11-08 19:04:32 +08:00
np . savez_compressed ( out / 'obstacle_points.npz' , world = full , filtered = filtered )
if len ( full ) != len ( filtered ): raise RuntimeError ( 'unpaired obstacle point clouds' )
2026-11-12 16:42:07 +08:00
selected = ( np . abs ( full [:, 0 ] - 1. ) < .18 ) & ( np . abs ( full [:, 1 ] - y ) < .18 ) & ( full [:, 2 ] > height ( 1. ) + min ( .12 , args . obstacle_height - .015 )) & ( full [:, 2 ] < height ( 1. ) + args . obstacle_height + .08 )
2026-11-08 19:04:32 +08:00
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 )
2026-11-12 16:42:07 +08:00
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 ] < height ( 1. ) + args . obstacle_height + .08 )
records . append ( dict ( stamp_ns = ns , count = int ( mask . sum ()), retained = int ( np . isfinite ( plan [ mask ]) . all ( axis = 1 ) . sum ()), by_sensor = [ int ( np . count_nonzero ( mask & ( ids == i ))) for i in ( 0 , 1 )]))
worlds . append ( world ); filtered_frames . append ( plan ); identities . append ( ids )
count = sum ( r [ 'count' ] for r in records ); retained = sum ( r [ 'retained' ] for r in records )
by_sensor = [ sum ( r [ 'by_sensor' ][ i ] for r in records ) for i in ( 0 , 1 )]
report [ 'obstacle_returns' ] = dict ( count = count , retained = retained , by_sensor = by_sensor , frames = records ,
criteria = 'all matched scans in fixed 2 s window; >=10 frames, >=15 selected returns, >=5 lower returns; all selected returns preserved' ,
ok = len ( records ) >= 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 )
2026-11-08 19:04:32 +08:00
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 :
2026-11-12 16:42:07 +08:00
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
2026-11-08 19:04:32 +08:00
( 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
2026-11-12 16:42:07 +08:00
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'
2026-11-08 19:04:32 +08:00
report [ 'cloud_snapshots' ] = p . snapshots ; report [ 'navigation_status' ] = p . navigation_status
2026-11-12 16:42:07 +08:00
except Exception as exc : report [ 'status' ] = 'INVALID' ; report [ 'error' ] = repr ( exc ); print ( report [ 'error' ], flush = True )
2026-11-08 19:04:32 +08:00
finally :
2026-11-12 16:42:07 +08:00
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 )
2026-11-08 22:44:02 +08:00
report [ 'ros_cleanup_errors' ] = shutdown_probe ( p )
2026-11-08 19:04:32 +08:00
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 ())