feat(sim): integrate Gazebo Classic with Point-LIO and SCAN navigation
Import the complete field and a simplified omnidirectional robot in sim_ws. Reuse original Point-LIO, SCAN and controller implementations with isolated simulation profiles, timed MID360/IMU data, readiness and command guards. Support known-corridor terrain paths, optional sensor stress profiles and separate physics/algorithm launch processes. Remove retired Fortress resources and operating instructions; add build, usage, scope and durable validation documentation. Validation: full build script; 8 adapter tests and 4 SCAN CTest targets; 8 continuous mild-noise routes; red/blue terrain 4 cases each; noise 9/9; visibility characterization 9/9; default sensors 16/16; loss-stop and post-build straight navigation. Real wheels/network remain unverified.
This commit is contained in:
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build original algorithms in isolated prefixes. Never installs a device SDK.
|
||||
set -eo pipefail
|
||||
BR_SIM_REPO=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)
|
||||
cd "$BR_SIM_REPO"
|
||||
BR_SIM_JOBS=${BR_SIM_BUILD_JOBS:-2}
|
||||
[[ "$BR_SIM_JOBS" =~ ^[1-9][0-9]*$ ]] || { echo 'BR_SIM_BUILD_JOBS must be a positive integer' >&2; exit 2; }
|
||||
source /opt/ros/humble/setup.bash
|
||||
export PATH="/usr/bin:$PATH" MAKEFLAGS="-j$BR_SIM_JOBS" CMAKE_BUILD_PARALLEL_LEVEL="$BR_SIM_JOBS"
|
||||
BR_SIM_CMAKE=(-DPython3_EXECUTABLE=/usr/bin/python3 -DCMAKE_BUILD_TYPE=Release)
|
||||
colcon --log-base sim_ws/log/build_interfaces build --base-paths minco_ws/src/perception/livox_ros_driver2 \
|
||||
--packages-select livox_ros_driver2 --build-base sim_ws/build/localization --install-base sim_ws/install/localization \
|
||||
--executor sequential --cmake-args "${BR_SIM_CMAKE[@]}" -DLIVOX_INTERFACES_ONLY=ON -DBUILD_TESTING=OFF
|
||||
source sim_ws/install/localization/setup.bash
|
||||
colcon --log-base sim_ws/log/build_localization build --base-paths minco_ws/src/perception/Point-LIO \
|
||||
--packages-select point_lio --build-base sim_ws/build/localization --install-base sim_ws/install/localization \
|
||||
--executor sequential --cmake-args "${BR_SIM_CMAKE[@]}" -DBUILD_TESTING=OFF
|
||||
source sim_ws/install/localization/setup.bash
|
||||
colcon --log-base sim_ws/log/build_navigation build --base-paths minco_ws/src/scan \
|
||||
--packages-up-to scan_planner step_blocker --build-base sim_ws/build/navigation --install-base sim_ws/install/navigation \
|
||||
--executor sequential --cmake-args "${BR_SIM_CMAKE[@]}" -DBUILD_TESTING=ON
|
||||
source sim_ws/install/navigation/setup.bash
|
||||
colcon --log-base sim_ws/log/build_classic build --base-paths sim_ws/src \
|
||||
--packages-select robocon_gazebo r2027_robot_description br_sim_bringup \
|
||||
--build-base sim_ws/build/classic --install-base sim_ws/install/classic --symlink-install \
|
||||
--executor sequential --cmake-args "${BR_SIM_CMAKE[@]}" -DBUILD_TESTING=OFF
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/python3
|
||||
"""SCAN navigation using LIO only; independent physical arrival and fault-stop checks."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
import rclpy
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from std_msgs.msg import String
|
||||
from rclpy.qos import QoSProfile,DurabilityPolicy,qos_profile_sensor_data
|
||||
|
||||
from check_omni_robot import Sim,sim_env
|
||||
from check_scan_navigation import NavProbe,run_goal
|
||||
from check_slope_drive import SlopeProbe
|
||||
|
||||
|
||||
class LioNavProbe(NavProbe):
|
||||
get_state=SlopeProbe.get_state
|
||||
def __init__(self):
|
||||
super().__init__(map_diagnostics=False);self.navigation_status=[];self.nav_odom=[];self.lio_odom=[]
|
||||
# The route/fault checks do not need the full dense 3D visualization maps.
|
||||
# Avoid requesting tens of MB/s merely to save diagnostic point counts.
|
||||
self.create_subscription(String,'/sim/navigation/status',lambda m:self.navigation_status.append(json.loads(m.data)),
|
||||
QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
|
||||
self.create_subscription(Odometry,'/sim/navigation/body_odom',lambda m:self.nav_odom.append(m),100)
|
||||
self.create_subscription(Odometry,'/sim/lio/aft_mapped_to_init',lambda m:self.lio_odom.append(m),100)
|
||||
for topic in ('/sim/navigation/planning_cloud','/sim/navigation/cloud_registered'):
|
||||
self.create_subscription(PointCloud2,topic,lambda m,topic=topic:self.clouds.update({topic:m}),qos_profile_sensor_data)
|
||||
|
||||
|
||||
def graph_evidence(out,probe,planning_topic='/sim/navigation/planning_cloud',extra_nodes=()):
|
||||
info={}
|
||||
for node in ('/lio_navigation_adapter','/sim/lio/point_lio_sim','/scan_planner_node','/closed_loop_controller')+tuple(extra_nodes):
|
||||
name=node.rsplit('/',1)[1];namespace=node.rsplit('/',1)[0] or '/'
|
||||
deadline=time.monotonic()+15
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
subscribers=probe.get_subscriber_names_and_types_by_node(name,namespace)
|
||||
clients=probe.get_client_names_and_types_by_node(name,namespace)
|
||||
if len(subscribers)>=(2 if node in extra_nodes else 3):break
|
||||
except RuntimeError:pass
|
||||
rclpy.spin_once(probe,timeout_sec=.05)
|
||||
else:raise RuntimeError('graph discovery incomplete: '+node)
|
||||
topics=[topic for topic,_ in subscribers]
|
||||
info[node]=dict(subscribers='\n'.join(topic+': '+','.join(types) for topic,types in subscribers),
|
||||
topics=topics,clients='\n'.join(topic for topic,_ in clients))
|
||||
(out/(node.strip('/').replace('/','_')+'_node.json')).write_text(json.dumps(info[node],indent=2)+'\n')
|
||||
checks=dict(no_truth_input=all(all(t not in d['topics'] for t in (
|
||||
'/odom','/body_odom','/aft_mapped_to_init','/tf','/tf_static','/gazebo/model_states','/gazebo/link_states')) and
|
||||
all(t not in d['clients'] for t in ('get_entity_state','get_model_state')) for d in info.values()),
|
||||
estimator_sensors_only=all(t in info['/sim/lio/point_lio_sim']['topics'] for t in ('/sim/mid360/lidar','/sim/mid360/imu')),
|
||||
adapter_lio_only=all(t in info['/lio_navigation_adapter']['topics'] for t in ('/sim/lio/aft_mapped_to_init','/sim/lio/cloud_registered_full_lidar')),
|
||||
controller_uses_estimate='/sim/navigation/body_odom' in info['/closed_loop_controller']['topics'],
|
||||
planner_uses_estimate=all(t in info['/scan_planner_node']['topics'] for t in ('/sim/navigation/body_odom','/sim/navigation/sensor_odom',planning_topic)))
|
||||
return dict(checks=checks,ok=all(checks.values()),nodes=info)
|
||||
|
||||
|
||||
def fault_stop(p,sim):
|
||||
goal=PoseStamped();goal.header.frame_id='world';goal.header.stamp=p.get_clock().now().to_msg()
|
||||
goal.pose.position.x=-3.6;goal.pose.position.y=4.5;goal.pose.position.z=.15;goal.pose.orientation.w=1.
|
||||
p.goal_pub.publish(goal);deadline=time.monotonic()+60
|
||||
while time.monotonic()<deadline:
|
||||
p.pump(.05);truth=p.get_state()
|
||||
if truth and math.hypot(*truth['twist_world'][:2])>.1:break
|
||||
else:raise RuntimeError('fault case never moved')
|
||||
candidates=[]
|
||||
for pid in sim.known:
|
||||
try:
|
||||
if b'/pointlio_mapping' in Path('/proc/%d/cmdline'%pid).read_bytes():candidates.append(pid)
|
||||
except FileNotFoundError:pass
|
||||
if len(candidates)!=1:raise RuntimeError('no single owned Point-LIO process: '+repr(candidates))
|
||||
pid=candidates[0];samples=[];readiness=[];start_cmd=len(p.commands);t0=p.now()
|
||||
if not sim.owns(pid):raise RuntimeError('Point-LIO ownership marker changed')
|
||||
try:
|
||||
os.kill(pid,signal.SIGSTOP)
|
||||
while p.now()-t0<1.3:
|
||||
p.pump(.05);s=p.get_state()
|
||||
if s is None:raise RuntimeError('missing independent physical state')
|
||||
samples.append(s);readiness.append(dict(t=p.now(),ready=p.ready))
|
||||
finally:
|
||||
last_nav_stamp=(p.nav_odom[-1].header.stamp.sec+p.nav_odom[-1].header.stamp.nanosec*1e-9) if p.nav_odom else None
|
||||
os.kill(pid,signal.SIGCONT)
|
||||
stop=next((s['stamp']-t0 for s in samples if math.hypot(*s['twist_world'][:2])<.01 and abs(s['wz'])<.02),None)
|
||||
late=[s for s in samples if s['stamp']-t0>.7]
|
||||
drift=max(math.dist(s['pos'],late[0]['pos']) for s in late) if late else None
|
||||
checks=dict(started_moving=True,readiness_revoked=any(not s['ready'] for s in readiness),
|
||||
stopped_in_time=stop is not None and 0<=stop<=.5,
|
||||
remained_stopped=bool(late) and drift<.02 and all(math.hypot(*s['twist_world'][:2])<.01 for s in late),
|
||||
no_truth_fallback=last_nav_stamp is not None and last_nav_stamp<t0+.1)
|
||||
resumed=[]
|
||||
for _ in range(8):
|
||||
p.pump(.1);s=p.get_state()
|
||||
if s is None:raise RuntimeError('missing resumed truth')
|
||||
resumed.append(s)
|
||||
checks['restart_latched_stopped']=not p.ready and any(s['phase']=='fault' and s['stamp']>t0 for s in p.navigation_status)
|
||||
checks['no_motion_after_resume']=all(math.hypot(*s['twist_world'][:2])<.01 for s in resumed)
|
||||
return dict(name='lio_loss_stop',checks=checks,ok=all(checks.values()),owned_lio_pid=pid,
|
||||
stop_latency_sim_s=stop,drift_m=drift,samples=samples,resumed_samples=resumed,
|
||||
last_nav_stamp_during_loss=last_nav_stamp,loss_start_stamp=t0,readiness=readiness,commands=p.commands[start_cmd:])
|
||||
|
||||
|
||||
def near_goal_recovery(p,sim):
|
||||
candidates=[]
|
||||
for pid in sim.known:
|
||||
try:
|
||||
if b'/lio_navigation_adapter.py' in Path('/proc/%d/cmdline'%pid).read_bytes() and sim.owns(pid):candidates.append(pid)
|
||||
except FileNotFoundError:pass
|
||||
if len(candidates)!=1:raise RuntimeError('cannot identify one owned navigation adapter')
|
||||
event={};pid=candidates[0]
|
||||
def pause_near_goal(state):
|
||||
distance=math.hypot(state['pos'][0]+3.8,state['pos'][1]-4.5)
|
||||
if event or not (.12<distance<.19) or math.hypot(*state['twist_world'][:2])<.02:return
|
||||
estimated=p.nav_odom[-1].pose.pose.position
|
||||
event.update(start=p.now(),physical_remaining_m=distance,
|
||||
estimated_remaining_m=math.hypot(estimated.x+3.8,estimated.y-4.5),owned_adapter_pid=pid)
|
||||
try:
|
||||
os.kill(pid,signal.SIGSTOP);p.pump(.4)
|
||||
event['paused_final_truth']=p.get_state()
|
||||
finally:
|
||||
os.kill(pid,signal.SIGCONT);event['resumed']=p.now()
|
||||
result=run_goal(p,'near_goal_recovery',-3.8,4.5,0.,goal_z=.15,settle_timeout=.2,sample_hook=pause_near_goal)
|
||||
checks=result['checks']
|
||||
checks['short_distance_hold_exercised']=bool(event) and .08<event['estimated_remaining_m']<.2
|
||||
held=[s for s in result['statuses'] if event and event['start']<=s['t']<=event['resumed'] and
|
||||
s['state']==0 and ('perception' in s['reason'] or 'odometry_stale' in s['reason'])]
|
||||
before=[s['traj_id'] for s in result['statuses'] if event and s['t']<=event['start'] and s['state']==1]
|
||||
stopped=event.get('paused_final_truth')
|
||||
checks['held_before_recovery']=bool(held) and stopped is not None and math.hypot(*stopped['twist_world'][:2])<.01 and abs(stopped['wz'])<.02
|
||||
checks['new_grant_after_recovery']=bool(event and before) and any(
|
||||
s['t']>event['resumed'] and s['state']==1 and s['traj_id']>max(before) for s in result['statuses'])
|
||||
result['event']=event;result['ok']=all(checks.values());return result
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
|
||||
group=ap.add_mutually_exclusive_group();group.add_argument('--straight-only',action='store_true');group.add_argument('--fault-only',action='store_true');group.add_argument('--recovery-only',action='store_true')
|
||||
ap.add_argument('--laps',type=int,default=1)
|
||||
ap.add_argument('--sensor-profile',choices=('ideal','mild','stress'),default='ideal')
|
||||
ap.add_argument('--split',action='store_true')
|
||||
args=ap.parse_args()
|
||||
if not 1<=args.laps<=5 or (args.laps>1 and (args.straight_only or args.fault_only or args.recovery_only)):
|
||||
ap.error('laps must be 1..5 and multi-lap mode requires complete navigation')
|
||||
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',cases=[],sensor_profile=args.sensor_profile,laps=args.laps,split=args.split,collector_sha256=hashlib.sha256(source).hexdigest())
|
||||
sim,p=Sim(str(out/'sim')),None
|
||||
try:
|
||||
ok,why=sim.start(lio_navigation=True,sensor_profile=args.sensor_profile,split=args.split);report['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=LioNavProbe()
|
||||
if not p.wait_clock():raise RuntimeError('missing clock')
|
||||
deadline=time.monotonic()+90
|
||||
while time.monotonic()<deadline:
|
||||
rclpy.spin_once(p,timeout_sec=.02)
|
||||
if p.ready and p.status and p.goal_pub.get_subscription_count()>=2 and len(p.nav_odom)>20:break
|
||||
else:raise RuntimeError('LIO navigation never became ready')
|
||||
report['graph']=graph_evidence(out,p)
|
||||
if not report['graph']['ok']:
|
||||
report['status']='FAIL';return 30
|
||||
p.pump(1.)
|
||||
if args.fault_only:report['cases'].append(fault_stop(p,sim))
|
||||
elif args.recovery_only:report['cases'].append(near_goal_recovery(p,sim))
|
||||
else:
|
||||
# Keep the whole 8 cm arrival-tolerance region and terminal-turn
|
||||
# envelope clear of the now-observed L1 corner. No margin is reduced.
|
||||
goals=[('straight',-3.8,4.5,0.),('lateral',-3.8,3.5,0.),('return_and_turn',-4.5,4.5,math.pi/2)]
|
||||
if args.straight_only:goals=goals[:1]
|
||||
fixture=False
|
||||
for lap in range(args.laps):
|
||||
lapdir=out if args.laps==1 else out/('lap_%d'%(lap+1));lapdir.mkdir(exist_ok=True)
|
||||
for name,x,y,yaw in goals:
|
||||
result=run_goal(p,name,x,y,yaw,goal_z=.15,settle_timeout=.2)
|
||||
result['lap']=lap+1;report['cases'].append(result)
|
||||
(lapdir/(name+'.json')).write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('lap',lap+1,name,result['checks'],'error',result['position_error_m'],flush=True)
|
||||
if not result['ok']:break
|
||||
if not all(c['ok'] for c in report['cases']):break
|
||||
if not args.straight_only:
|
||||
if not fixture:
|
||||
(out/'test_obstacle.sdf').write_text(p.add_obstacle());fixture=True;p.pump(2.)
|
||||
result=run_goal(p,'detour',-4.5,1.5,math.pi/2,obstacle=True,goal_z=.15,settle_timeout=.2)
|
||||
result['lap']=lap+1;report['cases'].append(result)
|
||||
(lapdir/'detour.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('lap',lap+1,'detour',result['checks'],'error',result['position_error_m'],flush=True)
|
||||
if not result['ok']:break
|
||||
expected=1 if args.straight_only or args.fault_only or args.recovery_only else 4*args.laps
|
||||
report['status']='PASS' if len(report['cases'])==expected and all(c['ok'] for c in report['cases']) else 'FAIL'
|
||||
report['navigation_status']=p.navigation_status
|
||||
report['observed_tf_edges']=p.tf_pairs
|
||||
report['input_reference_frames']=sorted({(m.header.frame_id,m.child_frame_id) for m in p.nav_odom})
|
||||
except Exception as exc:
|
||||
report['error']=repr(exc);print(report['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
|
||||
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/python3
|
||||
"""Independent physical acceptance of LIO reference-path navigation on known ramps."""
|
||||
import argparse,hashlib,json,math,os,signal,sys,time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from gazebo_msgs.msg import ContactsState
|
||||
from gazebo_msgs.srv import SpawnEntity
|
||||
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
|
||||
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):
|
||||
super().__init__();self.out=out;self.contacts=[];self.snapshots=[];self.next_snapshot=0.
|
||||
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 capture(self):
|
||||
if self.now()<self.next_snapshot:return
|
||||
full=self.clouds.get('/sim/navigation/cloud_registered');filtered=self.clouds.get('/sim/navigation/planning_cloud')
|
||||
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))
|
||||
|
||||
|
||||
def run_path(p,xs,y,blocked=False,fault_sim=None,goal_y=None):
|
||||
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:
|
||||
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,samples=[],readiness=[])
|
||||
try:
|
||||
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 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
|
||||
# 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])
|
||||
extent=np.abs(matrices[:,1,:])@np.array([.4,.4,.15])
|
||||
physical_y=np.array([s['pos'][1] for s in states])
|
||||
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),
|
||||
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 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.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,
|
||||
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,
|
||||
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('--sensor-profile',choices=('ideal','mild','stress'),default='ideal')
|
||||
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)
|
||||
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())
|
||||
report=dict(status='INVALID',cases={},side=args.side,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,sensor_profile=args.sensor_profile,spawn=(3.5,y,.15,0.));report['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=TerrainProbe(out)
|
||||
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')
|
||||
report['graph']=graph_evidence(out,p,'/sim/navigation/terrain_planning_cloud',extra_nodes=('/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.)+.3
|
||||
req.initial_pose.orientation.w=1.
|
||||
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>'
|
||||
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);p.pump(2.);p.capture()
|
||||
deadline=time.monotonic()+5
|
||||
while p.clouds['/sim/navigation/cloud_registered'].header.stamp!=p.clouds['/sim/navigation/planning_cloud'].header.stamp and time.monotonic()<deadline:p.pump(.02)
|
||||
if p.clouds['/sim/navigation/cloud_registered'].header.stamp!=p.clouds['/sim/navigation/planning_cloud'].header.stamp:raise RuntimeError('no matched obstacle cloud stamps')
|
||||
full=points(p.clouds['/sim/navigation/cloud_registered']);filtered=points(p.clouds['/sim/navigation/planning_cloud'])
|
||||
np.savez_compressed(out/'obstacle_points.npz',world=full,filtered=filtered)
|
||||
if len(full)!=len(filtered):raise RuntimeError('unpaired obstacle point clouds')
|
||||
selected=(np.abs(full[:,0]-1.)<.18)&(np.abs(full[:,1]-y)<.18)&(full[:,2]>height(1.)+.12)&(full[:,2]<height(1.)+.68)
|
||||
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)
|
||||
if not report['obstacle_returns']['ok']:raise RuntimeError('obstacle was not observed and preserved')
|
||||
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 and name=='uphill' else None,
|
||||
goal_y=(3.9 if y>0 else -3.9) if name=='edge_rejected' else None);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()) else 'FAIL'
|
||||
report['cloud_snapshots']=p.snapshots;report['navigation_status']=p.navigation_status
|
||||
except Exception as exc:report['error']=repr(exc);print(report['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
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())
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/python3
|
||||
"""Measure physical MID360 lower-FOV limits. PASS characterizes a limitation, not safe navigation."""
|
||||
import argparse,json,os,sys
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from gazebo_msgs.srv import SpawnEntity,DeleteEntity,GetEntityState
|
||||
from check_omni_robot import Sim,sim_env
|
||||
from check_mid360 import SensorProbe,rotate,json_value
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);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')
|
||||
report=dict(status='INVALID',scope='stationary ideal sensor visibility only; not navigation acceptance',cases=[]);sim=Sim(str(out/'sim'));p=None
|
||||
(out/'collector_snapshot.py').write_bytes(Path(__file__).read_bytes())
|
||||
try:
|
||||
ok,why=sim.start(lidar=True,drive='contact',sensor_model='mid360',spawn=(-4.5,4.5,.15,0.));report['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=SensorProbe()
|
||||
if not p.wait_clock():raise RuntimeError('no clock')
|
||||
spawn=p.create_client(SpawnEntity,'/spawn_entity');delete=p.create_client(DeleteEntity,'/delete_entity');p.pump(2.)
|
||||
for distance,height in [(1.5,.03),(3.,.03),(1.5,.08),(3.,.08),(1.5,.15),(3.,.15),(.6,.3),(1.5,.3),(1.5,.6)]:
|
||||
state=p.get_state()
|
||||
if state is None:raise RuntimeError('no physical observer pose')
|
||||
center=np.array([state['pos'][0]+distance,state['pos'][1],height/2])
|
||||
# The far TOP face can be visible even if the front face is below
|
||||
# the lower FOV. Include box depth; a point-target approximation
|
||||
# wrongly predicts that the 8 cm / 3 m fixture is invisible.
|
||||
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([0.,0.,.3]))
|
||||
inverse=q.copy();inverse[:3]*=-1
|
||||
corners=np.array([[center[0]+dx,center[1]+dy,height] for dx in (-.125,.125) for dy in (-.125,.125)])
|
||||
local=rotate(inverse,corners-origin)
|
||||
maximum_elevation=float(np.arctan2(local[:,2],np.linalg.norm(local[:,:2],axis=1)).max())
|
||||
visible=maximum_elevation>=np.deg2rad(-7)
|
||||
req=SpawnEntity.Request();req.name='visibility_box_%02d'%len(report['cases']);req.reference_frame='world';req.initial_pose.position.x=float(center[0]);req.initial_pose.position.y=float(center[1]);req.initial_pose.position.z=float(center[2]);req.initial_pose.orientation.w=1.
|
||||
req.xml=f'<sdf version="1.6"><model name="visibility_box"><static>true</static><link name="box"><collision name="box"><geometry><box><size>0.25 0.25 {height}</size></box></geometry></collision><visual name="box"><geometry><box><size>0.25 0.25 {height}</size></box></geometry></visual></link></model></sdf>'
|
||||
response=p._call(spawn,req,timeout=10)
|
||||
if not response or not response.success:raise RuntimeError('box not spawned')
|
||||
query=GetEntityState.Request();query.name=req.name;query.reference_frame='world'
|
||||
p.pump(.2);exists=p._call(p.cli_get,query,timeout=10)
|
||||
if not exists or not exists.success:raise RuntimeError('spawned fixture not independently queryable')
|
||||
p.pump(.2);t=p.now();p.pump(1.5)
|
||||
frames=[f for f in p.frames if t<f['t'] and f['t']+.1<p.now()]
|
||||
if len(frames)<8:raise RuntimeError('insufficient actual scans')
|
||||
q=np.array(state['quaternion']);origin=np.array(state['pos'])+rotate(q,np.array([0.,0.,.3]));all_world=[]
|
||||
for f in frames:all_world.append(rotate(q,f['xyz'])+origin)
|
||||
world=np.concatenate(all_world)
|
||||
in_box=(abs(world[:,0]-center[0])<.126)&(abs(world[:,1]-center[1])<.126)&(world[:,2]>.005)&(world[:,2]<=height+.002)
|
||||
count=int(in_box.sum());ok=count>=5 if visible else count==0
|
||||
case=dict(distance_m=distance,height_m=height,expected_visible=visible,observed_returns=count,frames=len(frames),ok=ok,
|
||||
navigation_capability='visible points only; motion untested' if count else 'UNSUPPORTED: no returns, cannot promise avoidance')
|
||||
report['cases'].append(case);np.savez_compressed(out/('fixture_%02d.npz'%len(report['cases'])),returns=world[in_box],fixture_center=center,observer_position=state['pos'],observer_quaternion=q)
|
||||
print(case,flush=True)
|
||||
remove=DeleteEntity.Request();remove.name=req.name;response=p._call(delete,remove,timeout=10)
|
||||
if response is None:raise RuntimeError('missing delete response')
|
||||
case['fixture_name']=req.name;case['delete_response_success']=response.success;case['delete_response']=response.status_message
|
||||
# Gazebo deletion is asynchronous. Confirm actual absence, using a
|
||||
# unique name so an old deletion cannot affect a subsequent fixture.
|
||||
for _ in range(30):
|
||||
p.pump(.05);exists=p._call(p.cli_get,query,timeout=10)
|
||||
if exists is not None and not exists.success:break
|
||||
else:raise RuntimeError('owned fixture still exists after deletion')
|
||||
p.pump(.2)
|
||||
report['status']='PASS' if all(c['ok'] for c in report['cases']) else 'FAIL'
|
||||
except Exception as e:report['error']=repr(e);print(report['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
|
||||
return dict(PASS=0,FAIL=30,INVALID=40)[report['status']]
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -0,0 +1,256 @@
|
||||
#!/usr/bin/python3
|
||||
"""Independent geometry, acquisition-time and specific-force acceptance, no truth into LIO."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from livox_ros_driver2.msg import CustomMsg
|
||||
from sensor_msgs.msg import Imu
|
||||
from std_msgs.msg import String
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from check_omni_robot import Sim,sim_env
|
||||
from check_slope_drive import SlopeProbe
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[2]
|
||||
MOUNT=np.array([0.,0.,.30])
|
||||
|
||||
|
||||
def json_value(value):
|
||||
if isinstance(value,np.generic):return value.item()
|
||||
raise TypeError('unsupported evidence value: '+type(value).__name__)
|
||||
|
||||
|
||||
def rotate(q,v):
|
||||
"""Quaternion xyzw, row vectors, broadcasting allowed."""
|
||||
return v+2*np.cross(q[..., :3],np.cross(q[..., :3],v)+q[...,3,None]*v)
|
||||
|
||||
|
||||
def interpolate(states,times):
|
||||
times=np.asarray(times)
|
||||
ts=np.array([s['stamp'] for s in states])
|
||||
# Duplicate state samples are legal; select distinct independent query times.
|
||||
ts,idx=np.unique(ts,return_index=True);states=[states[i] for i in idx]
|
||||
if np.min(times)<ts[0] or np.max(times)>ts[-1]:raise ValueError('no bracketing independent truth')
|
||||
hi=np.clip(np.searchsorted(ts,times,side='right'),1,len(ts)-1);lo=hi-1
|
||||
if np.max(ts[hi]-ts[lo])>.12:raise ValueError('truth gap exceeds 120 ms')
|
||||
w=(times-ts[lo])/(ts[hi]-ts[lo])
|
||||
pos=np.array([s['pos'] for s in states]);q=np.array([s['quaternion'] for s in states])
|
||||
qa,qb=q[lo],q[hi];qb=np.where(np.sum(qa*qb,axis=-1,keepdims=True)<0,-qb,qb)
|
||||
qq=qa+(qb-qa)*w[:,None];qq/=np.linalg.norm(qq,axis=-1,keepdims=True)
|
||||
return pos[lo]+(pos[hi]-pos[lo])*w[:,None],qq
|
||||
|
||||
|
||||
def scene_shapes():
|
||||
"""Read authoritative static primitives and triangles; independent of ODE ray code."""
|
||||
base=ROOT/'sim_ws/src/robocon_gazebo/models/robocon_ground_full'
|
||||
result=[]
|
||||
for c in ET.parse(base/'model.sdf').findall('.//collision'):
|
||||
p=np.fromstring(c.findtext('pose','0 0 0 0 0 0'),sep=' ')
|
||||
r,pitch,y=p[3:];cx,sx=np.cos(r),np.sin(r);cy,sy=np.cos(pitch),np.sin(pitch);cz,sz=np.cos(y),np.sin(y)
|
||||
R=np.array([[cz*cy,cz*sy*sx-sz*cx,cz*sy*cx+sz*sx],
|
||||
[sz*cy,sz*sy*sx+cz*cx,sz*sy*cx-cz*sx],[-sy,cy*sx,cy*cx]])
|
||||
geom=c.find('geometry');box=geom.find('box');cylinder=geom.find('cylinder');mesh=geom.find('mesh')
|
||||
if box is not None:shape=('box',np.fromstring(box.findtext('size'),sep=' ')/2)
|
||||
elif cylinder is not None:shape=('cylinder',(float(cylinder.findtext('radius')),float(cylinder.findtext('length'))/2))
|
||||
elif mesh is not None:
|
||||
path=base/'meshes'/Path(mesh.findtext('uri')).name
|
||||
vertices=[];faces=[]
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith('v '):vertices.append(list(map(float,line.split()[1:])))
|
||||
if line.startswith('f '):faces.append([int(s.split('/')[0])-1 for s in line.split()[1:]])
|
||||
vertices=np.array(vertices)*np.fromstring(mesh.findtext('scale','1 1 1'),sep=' ')
|
||||
shape=('mesh',vertices[np.array(faces)])
|
||||
else:raise ValueError('unhandled scene geometry')
|
||||
result.append((p[:3],R,*shape))
|
||||
return result
|
||||
|
||||
|
||||
def ray_ranges(origins,directions,shapes):
|
||||
best=np.full(len(origins),np.inf)
|
||||
for center,R,kind,value in shapes:
|
||||
o=(origins-center)@R;d=directions@R
|
||||
if kind=='box':
|
||||
safe=np.where(np.abs(d)>1e-12,d,1e-12)
|
||||
a=(-value-o)/safe;b=(value-o)/safe
|
||||
enter=np.max(np.minimum(a,b),axis=1);leave=np.min(np.maximum(a,b),axis=1)
|
||||
hit=np.where((leave>=np.maximum(enter,0))&(enter>0),enter,np.inf)
|
||||
elif kind=='cylinder':
|
||||
radius,height=value
|
||||
A=np.sum(d[:,:2]**2,axis=1);B=2*np.sum(o[:,:2]*d[:,:2],axis=1)
|
||||
C=np.sum(o[:,:2]**2,axis=1)-radius**2;disc=B*B-4*A*C
|
||||
hit=np.full(len(o),np.inf)
|
||||
for sign in (-1,1):
|
||||
t=(-B+sign*np.sqrt(np.maximum(disc,0)))/np.maximum(2*A,1e-20)
|
||||
good=(disc>=0)&(t>0)&(np.abs(o[:,2]+t*d[:,2])<=height)
|
||||
hit=np.minimum(hit,np.where(good,t,np.inf))
|
||||
for z in (-height,height):
|
||||
t=(z-o[:,2])/np.where(np.abs(d[:,2])>1e-12,d[:,2],1e-12)
|
||||
xy=o[:,:2]+t[:,None]*d[:,:2]
|
||||
hit=np.minimum(hit,np.where((t>0)&(np.sum(xy**2,axis=1)<=radius**2),t,np.inf))
|
||||
else:
|
||||
hit=np.full(len(o),np.inf)
|
||||
for a,b,c in value:
|
||||
e1,e2=b-a,c-a;h=np.cross(d,e2);det=h@e1
|
||||
safe=np.where(np.abs(det)>1e-12,det,1e-12);s=o-a
|
||||
u=np.sum(s*h,axis=1)/safe;q=np.cross(s,e1);v=np.sum(d*q,axis=1)/safe
|
||||
t=q@e2/safe
|
||||
good=(np.abs(det)>1e-12)&(u>=0)&(v>=0)&(u+v<=1)&(t>0)
|
||||
hit=np.minimum(hit,np.where(good,t,np.inf))
|
||||
best=np.minimum(best,hit)
|
||||
return best
|
||||
|
||||
|
||||
class SensorProbe(SlopeProbe):
|
||||
def __init__(self):
|
||||
super().__init__();self.frames=[];self.imus=[];self.sensor_status=[]
|
||||
self.create_subscription(CustomMsg,'/sim/mid360/lidar',self.on_frame,qos_profile_sensor_data)
|
||||
self.create_subscription(Imu,'/sim/mid360/imu',self.on_imu,qos_profile_sensor_data)
|
||||
self.create_subscription(String,'/sim/mid360/status',lambda m:self.sensor_status.append(json.loads(m.data)),10)
|
||||
|
||||
def on_frame(self,m):
|
||||
self.frames.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
|
||||
timebase=int(m.timebase),frame=m.header.frame_id,point_num=m.point_num,
|
||||
xyz=np.array([[p.x,p.y,p.z] for p in m.points]),
|
||||
offsets=np.array([p.offset_time for p in m.points],dtype=np.uint32),
|
||||
line=np.array([p.line for p in m.points],dtype=np.uint8),
|
||||
tag=np.array([p.tag for p in m.points],dtype=np.uint8)))
|
||||
|
||||
def on_imu(self,m):
|
||||
a=m.linear_acceleration;w=m.angular_velocity
|
||||
self.imus.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,frame=m.header.frame_id,
|
||||
acc=[a.x,a.y,a.z],gyro=[w.x,w.y,w.z],orientation_covariance_0=m.orientation_covariance[0]))
|
||||
|
||||
|
||||
def phase(p,cmd,duration):
|
||||
t0=p.now();states=[p.get_state()];nxt=t0
|
||||
def sample():
|
||||
nonlocal nxt
|
||||
if p.now()<nxt:return
|
||||
s=p.get_state()
|
||||
if s is None:raise RuntimeError('missing independent Gazebo state')
|
||||
states.append(s);nxt=p.now()+.025
|
||||
p.hold(*cmd,duration,sampler=sample)
|
||||
states.append(p.get_state())
|
||||
if any(s is None for s in states):raise RuntimeError('invalid truth sample')
|
||||
return dict(t0=t0,t1=p.now(),states=states)
|
||||
|
||||
|
||||
def geometry_check(p,record,shapes,out,name):
|
||||
states=record['states'];frames=[f for f in p.frames if f['t']>states[0]['stamp']+.15 and f['t']+.1<states[-1]['stamp']-.05]
|
||||
if len(frames)<4:raise RuntimeError('insufficient complete sensor frames')
|
||||
errors=[];instant_errors=[];saved={}
|
||||
for i,f in enumerate(frames[::max(1,len(frames)//6)]):
|
||||
idx=np.arange(0,len(f['xyz']),max(1,len(f['xyz'])//600))
|
||||
xyz=f['xyz'][idx];ranges=np.linalg.norm(xyz,axis=1);direction=xyz/ranges[:,None]
|
||||
times=f['t']+f['offsets'][idx]*1e-9
|
||||
pos,q=interpolate(states,times)
|
||||
origins=pos+rotate(q,np.broadcast_to(MOUNT,pos.shape));directions=rotate(q,direction)
|
||||
expected=ray_ranges(origins,directions,shapes)
|
||||
errors.extend(np.abs(expected-ranges).tolist())
|
||||
end_pos,end_q=interpolate(states,np.full(len(xyz),f['t']+.099))
|
||||
wrong=ray_ranges(end_pos+rotate(end_q,np.broadcast_to(MOUNT,end_pos.shape)),rotate(end_q,direction),shapes)
|
||||
instant_errors.extend(np.abs(wrong-ranges).tolist())
|
||||
saved[str(i)+'_xyz']=f['xyz'];saved[str(i)+'_offset_ns']=f['offsets']
|
||||
saved[str(i)+'_query_t']=times;saved[str(i)+'_expected_range']=expected
|
||||
np.savez_compressed(out/(name+'_clouds.npz'),**saved)
|
||||
finite=np.isfinite(errors)
|
||||
# At object silhouettes a tiny interpolation error may change occlusion.
|
||||
# Check the distribution and retain all errors instead of removing them.
|
||||
e=np.asarray(errors);wrong=np.asarray(instant_errors)
|
||||
return dict(samples=len(e),finite_fraction=float(np.mean(finite)),
|
||||
p95_range_error_m=float(np.quantile(e,.95)),p99_range_error_m=float(np.quantile(e,.99)),
|
||||
instantaneous_p95_error_m=float(np.quantile(wrong,.95)),
|
||||
ok=bool(np.mean(finite)>.98 and np.quantile(e,.95)<.005 and np.quantile(e,.99)<.02))
|
||||
|
||||
|
||||
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')
|
||||
sim,p=Sim(str(out/'sim')),None
|
||||
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())
|
||||
wall=time.monotonic()
|
||||
try:
|
||||
spawn=(1.4,3.5125,.6,0.) if args.case=='slope' else (-4.5,4.5,.17,0.)
|
||||
ok,why=sim.start(lidar=True,drive='contact',sensor_model='mid360',spawn=spawn)
|
||||
result['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=SensorProbe()
|
||||
if not p.wait_clock():raise RuntimeError('no clock')
|
||||
p.pump(1.5)
|
||||
if len(p.frames)<5 or len(p.imus)<100:raise RuntimeError('missing lidar or IMU stream')
|
||||
records={};shapes=scene_shapes()
|
||||
records['stationary']=phase(p,(0.,0.,0.),2.)
|
||||
for name,cmd,duration in ([] if args.case=='slope' else [
|
||||
('forward',(.3,0.,0.),2.5),('lateral',(0.,-.2,0.),1.5),('turn',(0.,0.,.3),2.)]):
|
||||
records[name]=phase(p,cmd,duration)
|
||||
records['stop']=phase(p,(0.,0.,0.),.5)
|
||||
# Finish live collection before CPU-heavy offline ray intersections.
|
||||
# Otherwise the probe's own analysis can overflow its IMU receive queue.
|
||||
if args.case=='flat':
|
||||
if not p.set_state(-4.5,4.5,1.2,0.):raise RuntimeError('drop set failed')
|
||||
drop=phase(p,(.3,0.,0.),.23)
|
||||
free=[m for m in p.imus if drop['t0']+.04<m['t']<drop['t1']-.02]
|
||||
result['free_fall']=dict(samples=free,truth=drop)
|
||||
geometry={}
|
||||
for name in records:
|
||||
if name!='stop':geometry[name]=geometry_check(p,records[name],shapes,out,name)
|
||||
frames=[f for f in p.frames if records['stationary']['t0']<=f['t']<records['stop']['t1']-.1]
|
||||
checks=result['checks']
|
||||
checks['geometry']=all(g['ok'] for g in geometry.values())
|
||||
checks['frame_and_count']=all(f['frame']=='lidar' and f['point_num']==len(f['xyz']) and len(f['xyz'])>500 for f in frames)
|
||||
checks['finite_fov']=all(np.isfinite(f['xyz']).all() and np.min(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))>=math.radians(-7)-1e-6 and np.max(np.arctan2(f['xyz'][:,2],np.linalg.norm(f['xyz'][:,:2],axis=1)))<=math.radians(52)+1e-6 for f in frames)
|
||||
checks['timebase']=all(abs(f['t']*1e9-f['timebase'])<1 for f in frames)
|
||||
checks['actual_batch_times']=all(np.min(f['offsets'])>=0 and np.max(f['offsets'])<100000000 and len(np.unique(f['offsets']))>50 and np.all(f['offsets']%1000000==0) and np.all(np.diff(f['offsets'].astype(np.int64))>=0) for f in frames)
|
||||
checks['frame_rate']=len(frames)>5 and np.max(np.abs(np.diff([f['t'] for f in frames])-.1))<1e-6
|
||||
checks['livox_flags']=all(np.max(f['line'])<4 and np.all(f['tag']==0x10) for f in frames)
|
||||
checks['ray_budget']=len(p.sensor_status)>5 and all(s['rays']==20000 and s['last_sample_ns']-s['first_sample_ns']==99000000 for s in p.sensor_status)
|
||||
checks['pattern_continues']=not np.allclose(frames[0]['xyz'][:100],frames[1]['xyz'][:100])
|
||||
st=records['stationary'];imu=[m for m in p.imus if st['t0']+.2<m['t']<st['t1']]
|
||||
if len(imu)<100:raise RuntimeError('too few stationary IMUs')
|
||||
pos,q=interpolate(st['states'],np.array([m['t'] for m in imu]));inverse=q.copy();inverse[:,:3]*=-1
|
||||
expected=rotate(inverse,np.broadcast_to([0,0,9.8],pos.shape))
|
||||
acc=np.array([m['acc'] for m in imu]);gyro=np.array([m['gyro'] for m in imu])
|
||||
stationary_error=np.linalg.norm(acc-expected,axis=1)
|
||||
checks['imu_specific_force']=bool(np.quantile(stationary_error,.95)<.05 and np.max(np.linalg.norm(gyro,axis=1))<.01)
|
||||
checks['imu_frame_rate']=all(m['frame']=='mid360_imu' for m in imu) and abs(1/np.median(np.diff([m['t'] for m in imu]))-200)<2
|
||||
checks['no_attitude_oracle']=all(m['orientation_covariance_0']==-1. for m in p.imus)
|
||||
measured_imu=[m for m in p.imus if st['t0']<=m['t']<=records['stop']['t1']]
|
||||
imu_times=np.array([m['t'] for m in measured_imu]);imu_intervals=np.diff(imu_times)
|
||||
imu_rate=(len(imu_times)-1)/(imu_times[-1]-imu_times[0])
|
||||
checks['imu_continuity']=bool(abs(imu_rate-200)<2 and np.min(imu_intervals)>0 and np.max(imu_intervals)<.02)
|
||||
if args.case=='flat':
|
||||
tr=records['turn'];moving=[m for m in p.imus if tr['t0']+.3<m['t']<tr['t1']-.1]
|
||||
checks['gyro_motion']=len(moving)>100 and abs(np.median([m['gyro'][2] for m in moving])-.3)<.02
|
||||
checks['real_scan_distortion']=max(geometry[n]['instantaneous_p95_error_m'] for n in ('forward','turn'))>.015
|
||||
checks['free_fall_imu']=len(free)>20 and np.quantile([np.linalg.norm(m['acc']) for m in free],.95)<.05
|
||||
else:
|
||||
checks['slope_physically_tilted']=abs(np.median([s['rpy'][1] for s in st['states']])-math.atan2(.597,3.5))<.02
|
||||
result.update(geometry=geometry,records=records,imus=p.imus,sensor_status=p.sensor_status,
|
||||
stationary_imu_p95_error_m_s2=float(np.quantile(stationary_error,.95)),
|
||||
stationary_imu_mean=np.mean(acc,axis=0).tolist(),frame_returns=[len(f['xyz']) for f in frames],
|
||||
measured_imu_rate_hz=float(imu_rate),maximum_imu_interval_s=float(np.max(imu_intervals)),
|
||||
sim_duration_s=p.now()-records['stationary']['t0'],wall_duration_s=time.monotonic()-wall)
|
||||
result['status']='PASS' if all(checks.values()) else 'FAIL'
|
||||
print(json.dumps(dict(status=result['status'],checks=checks,geometry=geometry),indent=2,default=json_value),flush=True)
|
||||
except Exception as exc:
|
||||
result['status']='INVALID';result['error']=repr(exc);print(result['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
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())
|
||||
@@ -0,0 +1,188 @@
|
||||
#!/usr/bin/python3
|
||||
"""P5 flat-ground corridor acceptance and unsupported-terrain rejection.
|
||||
|
||||
Each case owns a fresh simulator. Temporary corridor geometry is independent of
|
||||
the production field. No drive or stop command is injected during measurements.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from gazebo_msgs.srv import GetEntityState, SpawnEntity
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
|
||||
from check_omni_robot import Sim, sim_env
|
||||
from check_scan_navigation import NavProbe, run_goal
|
||||
from check_sim_lidar import points
|
||||
|
||||
|
||||
def spawn_corridor(p, width, out):
|
||||
poses = []
|
||||
for side, sign in (('left', -1), ('right', 1)):
|
||||
name = 'p5_wall_'+side
|
||||
req = SpawnEntity.Request()
|
||||
req.name, req.reference_frame = name, 'world'
|
||||
req.initial_pose.position.x = -4.5 + sign*(width/2+.05)
|
||||
req.initial_pose.position.y = 3.25
|
||||
req.initial_pose.position.z = .3
|
||||
req.initial_pose.orientation.w = 1.
|
||||
req.xml = '''<sdf version="1.6"><model name="%s"><static>true</static><link name="wall">
|
||||
<collision name="wall"><geometry><box><size>0.1 1.5 0.6</size></box></geometry></collision>
|
||||
<visual name="wall"><geometry><box><size>0.1 1.5 0.6</size></box></geometry></visual>
|
||||
</link></model></sdf>''' % name
|
||||
(out/(name+'.sdf')).write_text(req.xml)
|
||||
res = p._call(p.spawn, req, timeout=15)
|
||||
if not res or not res.success:
|
||||
raise RuntimeError('wall spawn failed: %r' % res)
|
||||
query = GetEntityState.Request()
|
||||
query.name, query.reference_frame = name, 'world'
|
||||
actual = p._call(p.cli_get, query)
|
||||
if not actual or not actual.success:
|
||||
raise RuntimeError('wall truth unavailable')
|
||||
pose = actual.state.pose.position
|
||||
poses.append([pose.x, pose.y, pose.z])
|
||||
measured = poses[1][0]-poses[0][0]-.1
|
||||
if abs(measured-width) > 1e-6:
|
||||
raise RuntimeError('corridor width differs from specification')
|
||||
return dict(nominal_width_m=width, measured_width_m=measured, wall_centers=poses,
|
||||
wall_size_m=[.1, 1.5, .6], y_extent_m=[2.5, 4.])
|
||||
|
||||
|
||||
def run_rejection(p, goal):
|
||||
first = p.get_state()
|
||||
if first is None:
|
||||
raise RuntimeError('no initial independent truth')
|
||||
old_id = p.status[-1].goal_id if p.status else 0
|
||||
first_cmd, first_status = len(p.commands), len(p.status)
|
||||
m = PoseStamped()
|
||||
m.header.frame_id = 'world'
|
||||
m.header.stamp = p.get_clock().now().to_msg()
|
||||
m.pose.position.x, m.pose.position.y, m.pose.position.z = goal[0], goal[1], .15
|
||||
m.pose.orientation.w = 1.
|
||||
p.goal_pub.publish(m)
|
||||
t0, end = p.now(), time.monotonic()+120
|
||||
samples = []
|
||||
while p.now()-t0 < 13. and time.monotonic() < end:
|
||||
p.pump(.1)
|
||||
s = p.get_state()
|
||||
if s is None:
|
||||
raise RuntimeError('missing truth during rejection')
|
||||
samples.append(s)
|
||||
status = p.status[-1]
|
||||
if status.goal_id > old_id and status.state in (status.SUCCEEDED, status.FAILED):
|
||||
break
|
||||
p.pump(1.1)
|
||||
final = p.get_state()
|
||||
if final is None or not samples:
|
||||
raise RuntimeError('missing final truth')
|
||||
samples.append(final)
|
||||
statuses, cmds = p.status[first_status:], p.commands[first_cmd:]
|
||||
drift = max(math.hypot(s['pos'][0]-first['pos'][0], s['pos'][1]-first['pos'][1]) for s in samples)
|
||||
status = p.status[-1]
|
||||
checks = dict(acknowledged=any(s.goal_id > old_id for s in statuses),
|
||||
failed_as_expected=status.goal_id > old_id and status.state == status.FAILED,
|
||||
never_active=not any(s.state == s.ACTIVE for s in statuses),
|
||||
fresh_perception=p.ready,
|
||||
stopped=drift < .02 and max(math.hypot(*s['twist_world'][:2]) for s in samples) < .01,
|
||||
zero_commands=len(cmds) > 10 and all(max(abs(c[k]) for k in ('vx','vy','wz')) < 1e-6 for c in cmds),
|
||||
original_goal_preserved=abs(status.goal.x-goal[0]) < 1e-6 and abs(status.goal.y-goal[1]) < 1e-6)
|
||||
return dict(goal=goal, checks=checks, ok=all(checks.values()), drift_m=drift,
|
||||
samples=samples, commands=cmds,
|
||||
statuses=[dict(state=s.state, goal_id=s.goal_id, reason=s.reason) for s in statuses])
|
||||
|
||||
|
||||
def run_case(name, out):
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
os.environ.update(sim_env())
|
||||
os.environ['ROS_LOG_DIR'] = str(out/'ros')
|
||||
sim, p = Sim(str(out/'sim')), None
|
||||
report = dict(case=name, status='INVALID')
|
||||
try:
|
||||
spawn = (2.2, 4.65, .15, 0.) if name == 'ramp_entry_rejected' else (
|
||||
(-4.5, 4.5, .15, math.pi/2) if name == 'corridor_120_yaw90' else None)
|
||||
ok, why = sim.start(navigation=True, spawn=spawn)
|
||||
report['startup'] = why
|
||||
if not ok:
|
||||
raise RuntimeError(why)
|
||||
rclpy.init()
|
||||
p = NavProbe()
|
||||
if not p.wait_clock():
|
||||
raise RuntimeError('no clock')
|
||||
deadline = time.monotonic()+90
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(p, timeout_sec=.02)
|
||||
if p.ready and p.status and p.goal_pub.get_subscription_count() >= 2:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError('SCAN not ready')
|
||||
if name.startswith('corridor'):
|
||||
width = 1.2 if name.startswith('corridor_120') else .95
|
||||
report['geometry'] = spawn_corridor(p, width, out)
|
||||
p.pump(2.)
|
||||
if name.startswith('corridor_120'):
|
||||
yaw = math.pi/2 if name.endswith('yaw90') else 0.
|
||||
result = run_goal(p, name, -4.5, 1.8, yaw, timeout=25.)
|
||||
inside = [s for s in result['samples'] if
|
||||
2.5 <= s['pos'][1]+.4 and s['pos'][1]-.4 <= 4.]
|
||||
clearance = min(.6 - abs(s['pos'][0]+4.5) -
|
||||
.4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw']))) for s in inside) if inside else None
|
||||
result['min_wall_clearance_m'] = clearance
|
||||
result['checks']['crossed_channel'] = bool(inside) and min(s['pos'][1] for s in inside) < 2.5
|
||||
result['checks']['physical_clearance'] = clearance is not None and clearance >= .03
|
||||
result['checks']['heading_held'] = max(abs(math.atan2(math.sin(s['yaw']-yaw),
|
||||
math.cos(s['yaw']-yaw))) for s in result['samples']) <= .01
|
||||
axis = 'vx' if name.endswith('yaw90') else 'vy'
|
||||
result['checks']['expected_body_axis'] = any(abs(c[axis]) > .05 for c in result['commands'])
|
||||
else:
|
||||
goal = {'corridor_095': (-4.5, 3.25), 'stairs_rejected': (-2.5, 3.5),
|
||||
'ramp_entry_rejected': (2., 3.5)}[name]
|
||||
result = run_rejection(p, goal)
|
||||
result['ok'] = all(result['checks'].values())
|
||||
report['result'] = result
|
||||
report['status'] = 'PASS' if result['ok'] else 'FAIL'
|
||||
# Preserve input geometry evidence for auditing rejection vs data loss.
|
||||
clouds = {topic: points(msg) for topic, msg in p.clouds.items()}
|
||||
np.savez_compressed(out/'map_evidence.npz', **clouds)
|
||||
print(name, report['status'], result['checks'], flush=True)
|
||||
except Exception as exc:
|
||||
report['error'] = repr(exc)
|
||||
print(name, report['error'], flush=True)
|
||||
finally:
|
||||
if p is not None:
|
||||
p.send(0., 0., 0.)
|
||||
p.destroy_node()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
report['teardown'] = sim.stop()
|
||||
(out/'result.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--out', required=True)
|
||||
names = ('corridor_120', 'corridor_120_yaw90', 'corridor_095', 'stairs_rejected', 'ramp_entry_rejected')
|
||||
ap.add_argument('--case', choices=names)
|
||||
args = ap.parse_args()
|
||||
out = Path(args.out).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
source = Path(__file__).read_bytes()
|
||||
(out/'collector_snapshot.py').write_bytes(source)
|
||||
reports = [run_case(name, out/name) for name in (names if args.case is None else [args.case])]
|
||||
status = 'INVALID' if any(r['status'] == 'INVALID' for r in reports) else (
|
||||
'FAIL' if any(r['status'] == 'FAIL' for r in reports) else 'PASS')
|
||||
summary = dict(status=status, collector_sha256=hashlib.sha256(source).hexdigest(),
|
||||
cases=[dict(case=r['case'], status=r['status']) for r in reports])
|
||||
(out/'result.json').write_text(json.dumps(summary, indent=2)+'\n')
|
||||
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[status]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,132 @@
|
||||
#!/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
|
||||
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:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
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())
|
||||
@@ -0,0 +1,306 @@
|
||||
#!/usr/bin/python3
|
||||
"""Run existing SCAN/controller against Gazebo truth, never publish drive commands.
|
||||
|
||||
PASS requires a new goal to be acknowledged, ACTIVE and SUCCEEDED, physical
|
||||
arrival, and a full second stopped at the goal. Save every independent truth
|
||||
sample and observed command. A static test obstacle does not modify the map.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from gazebo_msgs.srv import SpawnEntity
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
from rclpy.qos import QoSProfile, DurabilityPolicy, qos_profile_sensor_data
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from scan_planner_msgs.msg import TrajectoryStatus
|
||||
from std_msgs.msg import Bool
|
||||
|
||||
from check_omni_robot import Probe, Sim, sim_env
|
||||
from check_sim_lidar import points
|
||||
|
||||
|
||||
class NavProbe(Probe):
|
||||
def __init__(self, map_diagnostics=True):
|
||||
super().__init__()
|
||||
self.goal_pub = self.create_publisher(PoseStamped, '/move_base_simple/goal', 10)
|
||||
self.status = []
|
||||
self.commands = []
|
||||
self.ready = False
|
||||
self.clouds = {}
|
||||
topics = ['/cloud_registered_for_scan']
|
||||
if map_diagnostics:
|
||||
topics.extend(('/grid_map/occupancy', '/grid_map/occupancy_inflate'))
|
||||
for topic in topics:
|
||||
self.create_subscription(PointCloud2, topic,
|
||||
lambda m, topic=topic: self.clouds.update({topic: m}), qos_profile_sensor_data)
|
||||
self.create_subscription(TrajectoryStatus, '/planning/trajectory_status',
|
||||
self.status.append,
|
||||
QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL))
|
||||
self.create_subscription(Twist, '/cmd_vel', self.on_cmd, 100)
|
||||
self.create_subscription(Bool, '/planning/perception_ready',
|
||||
lambda m: setattr(self, 'ready', m.data),
|
||||
QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL))
|
||||
self.spawn = self.create_client(SpawnEntity, '/spawn_entity')
|
||||
|
||||
def on_cmd(self, m):
|
||||
self.commands.append(dict(t=self.now(), vx=m.linear.x, vy=m.linear.y, wz=m.angular.z))
|
||||
|
||||
def add_obstacle(self):
|
||||
req = SpawnEntity.Request()
|
||||
req.name = 'p4_test_box'
|
||||
req.reference_frame = 'world'
|
||||
req.initial_pose.position.x = -4.6
|
||||
req.initial_pose.position.y = 3.0
|
||||
req.initial_pose.position.z = .3
|
||||
req.initial_pose.orientation.w = 1.
|
||||
req.xml = '''<sdf version="1.6"><model name="p4_test_box"><static>true</static>
|
||||
<link name="box"><collision name="collision"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></collision>
|
||||
<visual name="visual"><geometry><box><size>0.25 0.25 0.6</size></box></geometry></visual></link></model></sdf>'''
|
||||
res = self._call(self.spawn, req, timeout=15)
|
||||
if not res or not res.success:
|
||||
raise RuntimeError('test obstacle spawn failed: %s' % res)
|
||||
return req.xml
|
||||
|
||||
|
||||
def run_goal(p, name, x, y, yaw, timeout=55., obstacle=False, goal_z=None, settle_timeout=0., sample_hook=None):
|
||||
first = p.get_state()
|
||||
old_id = p.status[-1].goal_id if p.status else 0
|
||||
start_cmd = len(p.commands)
|
||||
start_status = len(p.status)
|
||||
m = PoseStamped()
|
||||
m.header.frame_id = 'world'
|
||||
m.header.stamp = p.get_clock().now().to_msg()
|
||||
m.pose.position.x, m.pose.position.y, m.pose.position.z = x, y, first['pos'][2] if goal_z is None else goal_z
|
||||
m.pose.orientation.z, m.pose.orientation.w = math.sin(yaw/2), math.cos(yaw/2)
|
||||
p.goal_pub.publish(m)
|
||||
t0, wall_end = p.now(), time.monotonic()+300
|
||||
samples = []
|
||||
while p.now()-t0 < timeout and time.monotonic() < wall_end:
|
||||
p.pump(.1)
|
||||
truth = p.get_state()
|
||||
if truth is None:
|
||||
raise RuntimeError('missing independent Gazebo truth')
|
||||
samples.append(truth)
|
||||
if sample_hook is not None:
|
||||
sample_hook(truth)
|
||||
s = p.status[-1] if p.status else None
|
||||
if s is not None and s.goal_id > old_id and s.state in (s.SUCCEEDED, s.FAILED):
|
||||
break
|
||||
# The optional force-drive protocol measures braking explicitly, then starts
|
||||
# the full stopped window. Legacy instantaneous-drive protocol is unchanged.
|
||||
braking=[];settle_latency=None;terminal_observed_time=p.now()
|
||||
terminal_status=p.status[-1] if p.status else None
|
||||
terminal_time=terminal_observed_time
|
||||
if terminal_status is not None and terminal_status.goal_id>old_id and terminal_status.state in (terminal_status.SUCCEEDED,terminal_status.FAILED):
|
||||
terminal_time=terminal_status.header.stamp.sec+terminal_status.header.stamp.nanosec*1e-9
|
||||
if settle_timeout>0:
|
||||
while p.now()-terminal_time<settle_timeout:
|
||||
p.pump(.005);state=p.get_state()
|
||||
if state is None:raise RuntimeError('truth missing during braking')
|
||||
braking.append(state)
|
||||
if math.hypot(*state['twist_world'][:2])<.01 and abs(state['wz'])<.02:
|
||||
settle_latency=state['stamp']-terminal_time;break
|
||||
# Observe the post-arrival behavior; do not inject a stop to make this pass.
|
||||
stop_start = p.now()
|
||||
stopped_samples = []
|
||||
while p.now()-stop_start < 1.1:
|
||||
p.pump(.1)
|
||||
stopped_samples.append(p.get_state())
|
||||
final = stopped_samples[-1]
|
||||
statuses = p.status[start_status:]
|
||||
cmds = p.commands[start_cmd:]
|
||||
err = math.hypot(final['pos'][0]-x, final['pos'][1]-y)
|
||||
yaw_err = abs(math.atan2(math.sin(final['yaw']-yaw), math.cos(final['yaw']-yaw)))
|
||||
speed = max(math.hypot(*s['twist_world'][:2]) for s in stopped_samples)
|
||||
drift = max(math.hypot(s['pos'][0]-final['pos'][0], s['pos'][1]-final['pos'][1])
|
||||
for s in stopped_samples)
|
||||
checks = dict(acknowledged=any(s.goal_id > old_id for s in statuses),
|
||||
active=any(s.goal_id > old_id and s.state == s.ACTIVE for s in statuses),
|
||||
succeeded=bool(statuses and statuses[-1].goal_id > old_id and
|
||||
statuses[-1].state == statuses[-1].SUCCEEDED),
|
||||
arrival=err < .10, yaw=yaw_err < .10,
|
||||
stopped=speed < .01 and drift < .02,
|
||||
commands_observed=len(cmds) > 10,
|
||||
moved=math.hypot(final['pos'][0]-first['pos'][0],
|
||||
final['pos'][1]-first['pos'][1]) > .3)
|
||||
if name == 'lateral':
|
||||
checks['lateral_command'] = any(abs(c['vy']) > .05 for c in cmds)
|
||||
if settle_timeout>0:
|
||||
checks['bounded_braking']=settle_latency is not None and 0<=settle_latency<=settle_timeout
|
||||
checks['stopped_rotation']=all(abs(s['wz'])<.02 for s in stopped_samples)
|
||||
if obstacle:
|
||||
# Square footprint at heading pi/2; use its enclosing AABB, including yaw drift.
|
||||
clearances = []
|
||||
for s in samples:
|
||||
extent = .4*(abs(math.cos(s['yaw']))+abs(math.sin(s['yaw'])))
|
||||
clearances.append(max(abs(s['pos'][0]+4.6)-.125-extent,
|
||||
abs(s['pos'][1]-3.)-.125-extent))
|
||||
checks['physical_clearance'] = min(clearances) > .015
|
||||
checks['detoured'] = max(s['pos'][0] for s in samples) > -3.95
|
||||
else:
|
||||
clearances = []
|
||||
cloud_diagnostics = {}
|
||||
for topic, msg in p.clouds.items():
|
||||
pc = points(msg)
|
||||
pc = pc[np.isfinite(pc).all(axis=1)]
|
||||
near = pc[(np.abs(pc[:, 0]-x) < .6) & (np.abs(pc[:, 1]-y) < .6) & (pc[:, 2] < .4)]
|
||||
cloud_diagnostics[topic] = dict(total=len(pc), near_goal=near.tolist())
|
||||
return dict(name=name, goal=[x, y, yaw], checks=checks, ok=all(checks.values()),
|
||||
cloud_diagnostics=cloud_diagnostics,
|
||||
position_error_m=err, yaw_error_rad=yaw_err, stopped_max_speed_m_s=speed,
|
||||
stopped_drift_m=drift, duration_sim_s=p.now()-t0,
|
||||
settle_latency_sim_s=settle_latency,braking_samples=braking,
|
||||
terminal_source_stamp=terminal_time,terminal_observed_stamp=terminal_observed_time,
|
||||
min_obstacle_clearance_m=min(clearances) if clearances else None,
|
||||
samples=samples, stop_samples=stopped_samples, commands=cmds,
|
||||
statuses=[dict(t=s.header.stamp.sec+s.header.stamp.nanosec*1e-9,
|
||||
goal_id=s.goal_id, state=s.state, reason=s.reason,
|
||||
traj_id=s.traj_id, is_final=s.is_final,
|
||||
goal=[s.goal.x, s.goal.y, s.goal.z]) for s in statuses])
|
||||
|
||||
|
||||
def run_data_loss(p, sim):
|
||||
"""Suspend only our adapter while the real controller is moving; no injected stop."""
|
||||
m = PoseStamped()
|
||||
m.header.frame_id = 'world'
|
||||
m.header.stamp = p.get_clock().now().to_msg()
|
||||
m.pose.position.x, m.pose.position.y = -3.6, 4.5
|
||||
m.pose.orientation.w = 1.
|
||||
p.goal_pub.publish(m)
|
||||
deadline = time.monotonic()+60
|
||||
while time.monotonic() < deadline:
|
||||
p.pump(.05)
|
||||
truth = p.get_state()
|
||||
if truth and math.hypot(*truth['twist_world'][:2]) > .1:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError('data-loss test never reached moving state')
|
||||
owned = []
|
||||
for pid in sim.known:
|
||||
try:
|
||||
if b'/sim_data_adapter.py' in Path('/proc/%d/cmdline' % pid).read_bytes():
|
||||
owned.append(pid)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
if len(owned) != 1:
|
||||
raise RuntimeError('cannot identify exactly one owned adapter: %r' % owned)
|
||||
pid = owned[0]
|
||||
samples, ready = [], []
|
||||
t0 = p.now()
|
||||
try:
|
||||
os.kill(pid, signal.SIGSTOP)
|
||||
while p.now()-t0 < 1.3:
|
||||
p.pump(.05)
|
||||
state = p.get_state()
|
||||
if state is None:
|
||||
raise RuntimeError('independent truth missing during data loss')
|
||||
samples.append(state)
|
||||
ready.append(dict(t=p.now(), ready=p.ready))
|
||||
finally:
|
||||
os.kill(pid, signal.SIGCONT)
|
||||
stop = next((s['stamp']-t0 for s in samples
|
||||
if math.hypot(*s['twist_world'][:2]) < .01 and abs(s['wz']) < .02), None)
|
||||
late = [s for s in samples if s['stamp']-t0 >= .7]
|
||||
drift = max(math.hypot(s['pos'][0]-late[0]['pos'][0], s['pos'][1]-late[0]['pos'][1])
|
||||
for s in late) if late else None
|
||||
checks = dict(initially_moving=True, readiness_revoked=any(not s['ready'] for s in ready),
|
||||
stopped_in_time=stop is not None and 0 <= stop <= .5,
|
||||
stayed_stopped=bool(late) and all(math.hypot(*s['twist_world'][:2]) < .01
|
||||
for s in late) and drift < .02)
|
||||
return dict(name='data_loss_stop', checks=checks, ok=all(checks.values()),
|
||||
owned_adapter_pid=pid, stop_latency_sim_s=stop, drift_m=drift,
|
||||
samples=samples, readiness=ready)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--out', required=True)
|
||||
ap.add_argument('--no-map-diagnostics', action='store_true',
|
||||
help='Skip dense visualization maps; keep physical arrival/stop criteria unchanged')
|
||||
ap.add_argument('--settle-timeout', type=float, default=0.,
|
||||
help='Explicit bounded braking window before the full stopped interval (0 preserves legacy protocol)')
|
||||
group = ap.add_mutually_exclusive_group()
|
||||
group.add_argument('--straight-only', action='store_true')
|
||||
group.add_argument('--fault-only', action='store_true')
|
||||
args = ap.parse_args()
|
||||
if not math.isfinite(args.settle_timeout) or not 0<=args.settle_timeout<=.2:
|
||||
ap.error('--settle-timeout must be between 0 and 0.20 simulation seconds')
|
||||
out = Path(args.out).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
os.environ.update(sim_env())
|
||||
sim, p = Sim(str(out/'sim')), None
|
||||
source = Path(__file__).read_bytes()
|
||||
(out/'collector_snapshot.py').write_bytes(source)
|
||||
report = dict(status='INVALID', cases=[],
|
||||
collector_sha256_at_start=hashlib.sha256(source).hexdigest(),
|
||||
braking_window_sim_s=args.settle_timeout, map_diagnostics=not args.no_map_diagnostics)
|
||||
try:
|
||||
ok, why = sim.start(navigation=True)
|
||||
report['sim_start'] = why
|
||||
if not ok:
|
||||
raise RuntimeError(why)
|
||||
rclpy.init()
|
||||
p = NavProbe(map_diagnostics=not args.no_map_diagnostics)
|
||||
if not p.wait_clock():
|
||||
raise RuntimeError('no simulation clock')
|
||||
end = time.monotonic()+90
|
||||
while time.monotonic() < end:
|
||||
rclpy.spin_once(p, timeout_sec=.02)
|
||||
if p.ready and p.status and p.goal_pub.get_subscription_count() >= 2:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError('navigation not ready')
|
||||
p.pump(1.)
|
||||
if args.fault_only:
|
||||
result = run_data_loss(p, sim)
|
||||
report['cases'].append(result)
|
||||
print(result['name'], result['checks'], flush=True)
|
||||
# Keep the 0.8 m footprint plus margin away from the stair edge at y=4.
|
||||
goals = [('straight', -3.6, 4.5, 0.), ('lateral', -3.6, 3.5, 0.),
|
||||
('return_and_turn', -4.5, 4.5, math.pi/2)]
|
||||
if args.straight_only:
|
||||
goals = goals[:1]
|
||||
if args.fault_only:
|
||||
goals = []
|
||||
for name, x, y, yaw in goals:
|
||||
result = run_goal(p, name, x, y, yaw, settle_timeout=args.settle_timeout)
|
||||
report['cases'].append(result)
|
||||
(out/(name+'.json')).write_text(json.dumps(result, indent=2)+'\n')
|
||||
print(name, result['checks'], 'error', result['position_error_m'], flush=True)
|
||||
if not result['ok']:
|
||||
break
|
||||
if not args.straight_only and not args.fault_only and all(c['ok'] for c in report['cases']) and len(report['cases']) == 3:
|
||||
(out/'test_obstacle.sdf').write_text(p.add_obstacle())
|
||||
p.pump(2.)
|
||||
result = run_goal(p, 'detour', -4.5, 1.5, math.pi/2, obstacle=True, settle_timeout=args.settle_timeout)
|
||||
report['cases'].append(result)
|
||||
(out/'detour.json').write_text(json.dumps(result, indent=2)+'\n')
|
||||
print('detour', result['checks'], 'error', result['position_error_m'], flush=True)
|
||||
expected = 1 if args.straight_only or args.fault_only else 4
|
||||
report['status'] = 'PASS' if len(report['cases']) == expected and all(
|
||||
c['ok'] for c in report['cases']) else 'FAIL'
|
||||
except Exception as exc:
|
||||
report['error'] = repr(exc)
|
||||
print(report['error'], flush=True)
|
||||
finally:
|
||||
if p is not None:
|
||||
p.send(0., 0., 0.) # Teardown only, after all measurements have been saved.
|
||||
p.destroy_node()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
report['teardown'] = sim.stop()
|
||||
(out/'result.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/python3
|
||||
"""Validate noise against independently interpolated physics; no fabricated time or IMU truth input."""
|
||||
import argparse,json,os,sys,time,hashlib
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import yaml
|
||||
import rclpy
|
||||
from check_omni_robot import Sim,sim_env
|
||||
from check_mid360 import SensorProbe,phase,interpolate,rotate,scene_shapes,ray_ranges,json_value
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True);ap.add_argument('--profile',choices=('mild','stress'),default='stress');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')
|
||||
config=Path(__file__).resolve().parents[1]/'src/r2027_robot_description/config/sensor_profiles.yaml'
|
||||
profile=yaml.safe_load(config.read_text())[args.profile]
|
||||
(out/'sensor_profiles.yaml').write_bytes(config.read_bytes());(out/'collector_snapshot.py').write_bytes(Path(__file__).read_bytes())
|
||||
report=dict(status='INVALID',profile=args.profile,parameters=profile);sim=Sim(str(out/'sim'));p=None
|
||||
try:
|
||||
ok,why=sim.start(lidar=True,drive='contact',sensor_model='mid360',sensor_profile=args.profile,spawn=(-4.5,4.5,.15,0.));report['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=SensorProbe()
|
||||
if not p.wait_clock():raise RuntimeError('no clock')
|
||||
p.pump(2.);stationary=phase(p,(0.,0.,0.),3.);moving=phase(p,(.2,0.,0.),2.);final=phase(p,(0.,0.,0.),1.)
|
||||
records=dict(stationary=stationary,moving=moving,final=final)
|
||||
(out/'physics.json').write_text(json.dumps(records,indent=2)+'\n')
|
||||
imus=[m for m in p.imus if stationary['t0']+.2<m['t']<stationary['t1']-.1]
|
||||
if len(imus)<400:raise RuntimeError('insufficient IMU samples')
|
||||
_,q=interpolate(stationary['states'],[m['t'] for m in imus]);q[:,:3]*=-1
|
||||
expected=rotate(q,np.tile([0.,0.,9.8],(len(q),1)))
|
||||
accel=np.array([m['acc'] for m in imus])-expected;gyro=np.array([m['gyro'] for m in imus])
|
||||
frames=[f for f in p.frames if moving['t0']+.15<f['t'] and f['t']+.1<moving['t1']-.1]
|
||||
if len(frames)<6:raise RuntimeError('insufficient complete moving lidar frames')
|
||||
residuals=[];shapes=scene_shapes();saved={}
|
||||
for j,f in enumerate(frames[::max(1,len(frames)//6)]):
|
||||
take=np.arange(0,len(f['xyz']),max(1,len(f['xyz'])//500));xyz=f['xyz'][take];distance=np.linalg.norm(xyz,axis=1)
|
||||
pos,q=interpolate(moving['states'],f['t']+f['offsets'][take]*1e-9)
|
||||
origins=pos+rotate(q,np.tile([0.,0.,.3],(len(pos),1)))
|
||||
directions=rotate(q,xyz/distance[:,None]);expected_range=ray_ranges(origins,directions,shapes)
|
||||
valid=np.isfinite(expected_range)&(expected_range>.1)&(expected_range<40)
|
||||
residuals.extend((distance-expected_range)[valid]);saved['xyz_%d'%j]=xyz;saved['expected_%d'%j]=expected_range
|
||||
errors=np.array(residuals)
|
||||
statuses=[s for s in p.sensor_status if 'candidate_hits' in s];candidates=sum(s['candidate_hits'] for s in statuses);dropped=sum(s['dropped'] for s in statuses)
|
||||
times=np.array([m['t'] for m in imus]);std=profile['range_stddev'];checks=dict(
|
||||
physical_excitation=moving['states'][-1]['pos'][0]-moving['states'][0]['pos'][0]>.3,
|
||||
imu_bias=np.all(abs(accel.mean(axis=0)-profile['accel_bias'])<5*profile['accel_stddev']/np.sqrt(len(accel))+.002) and np.all(abs(gyro.mean(axis=0)-profile['gyro_bias'])<5*profile['gyro_stddev']/np.sqrt(len(gyro))+.00005),
|
||||
imu_stddev=np.all(abs(accel.std(axis=0)/profile['accel_stddev']-1)<.2) and np.all(abs(gyro.std(axis=0)/profile['gyro_stddev']-1)<.2),
|
||||
range_noise=len(errors)>2000 and abs(errors.mean())<.1*std and .8<errors.std()/std<1.2,
|
||||
dropout=candidates>5000 and abs(dropped/candidates-profile['dropout'])<5*np.sqrt(profile['dropout']*(1-profile['dropout'])/candidates),
|
||||
packet_accounting=bool(statuses) and all(s['candidate_hits']==s['returns']+s['dropped']+s['range_rejected'] and s['rays']==20000 for s in statuses),
|
||||
acquisition_times=all(np.all(f['offsets']%1000000==0) and max(f['offsets'])<=99000000 and f['timebase']==round(f['t']*1e9) for f in frames),
|
||||
imu_times=np.min(np.diff(times))>0 and np.max(np.diff(times))<.02 and abs((len(times)-1)/(times[-1]-times[0])-200)<2,
|
||||
no_attitude_oracle=all(m['orientation_covariance_0']==-1 for m in imus))
|
||||
report.update(checks=checks,accel_mean=accel.mean(axis=0).tolist(),accel_stddev=accel.std(axis=0).tolist(),gyro_mean=gyro.mean(axis=0).tolist(),gyro_stddev=gyro.std(axis=0).tolist(),
|
||||
range_residual_mean_m=float(errors.mean()),range_residual_stddev_m=float(errors.std()),sampled_range_returns=len(errors),dropped=dropped,candidates=candidates,dropout_fraction=dropped/candidates,sensor_status=statuses)
|
||||
report.update(imu_mean_rate_hz=float((len(times)-1)/(times[-1]-times[0])),imu_interval_range_s=[float(np.diff(times).min()),float(np.diff(times).max())])
|
||||
np.savez_compressed(out/'observations.npz',imu_times=times,accel_residual=accel,gyro=gyro,range_residual=errors,**saved)
|
||||
report['status']='PASS' if all(checks.values()) else 'FAIL';print(report['status'],checks,flush=True)
|
||||
except Exception as e:report['error']=repr(e);print(report['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
report['teardown']=sim.stop();(out/'result.json').write_text(json.dumps(report,indent=2,default=json_value)+'\n')
|
||||
return dict(PASS=0,FAIL=30,INVALID=40)[report['status']]
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/python3
|
||||
"""P3: compare raw/world 3D clouds against independent Gazebo truth at two yaws."""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
from nav_msgs.msg import Odometry
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
|
||||
from check_omni_robot import Probe, Sim, reset_and_settle, sim_env
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] /
|
||||
'src/r2027_robot_description/scripts'))
|
||||
from sim_data_adapter import xyz_views
|
||||
|
||||
|
||||
def stamp(m):
|
||||
return m.header.stamp.sec * 1_000_000_000 + m.header.stamp.nanosec
|
||||
|
||||
|
||||
def points(m):
|
||||
return np.stack(xyz_views(m), axis=-1).reshape(-1, 3)
|
||||
|
||||
|
||||
class LidarProbe(Probe):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.raw = {}
|
||||
self.world = {}
|
||||
self.body = []
|
||||
self.sensor = []
|
||||
self.create_subscription(PointCloud2, '/lidar/points',
|
||||
lambda m: self.raw.update({stamp(m): m}), qos_profile_sensor_data)
|
||||
self.create_subscription(PointCloud2, '/cloud_registered',
|
||||
lambda m: self.world.update({stamp(m): m}), 10)
|
||||
self.create_subscription(Odometry, '/body_odom', self.body.append, 10)
|
||||
self.create_subscription(Odometry, '/aft_mapped_to_init', self.sensor.append, 10)
|
||||
|
||||
|
||||
def check_phase(probe, out, yaw):
|
||||
ok, settle = reset_and_settle(probe, -4.5, 4.5, .17, yaw, str(out))
|
||||
if not ok:
|
||||
raise RuntimeError('robot did not settle')
|
||||
cutoff = int(probe.now() * 1e9)
|
||||
deadline = time.monotonic() + 60
|
||||
pairs = []
|
||||
while time.monotonic() < deadline:
|
||||
rclpy.spin_once(probe, timeout_sec=.02)
|
||||
pairs = sorted(s for s in probe.world if s >= cutoff and s in probe.raw)
|
||||
if len(pairs) >= 8 and probe.body and probe.sensor:
|
||||
break
|
||||
if len(pairs) < 8:
|
||||
raise RuntimeError('not enough paired raw/world clouds: %d' % len(pairs))
|
||||
truth = probe.get_state()
|
||||
if truth is None:
|
||||
raise RuntimeError('independent truth unavailable')
|
||||
s = pairs[-1]
|
||||
raw, world = probe.raw[s], probe.world[s]
|
||||
pr, pw = points(raw), points(world)
|
||||
good = np.isfinite(pr).all(axis=1) & np.isfinite(pw).all(axis=1)
|
||||
pr, pw = pr[good], pw[good]
|
||||
c, sn = math.cos(truth['yaw']), math.sin(truth['yaw'])
|
||||
R = np.array([[c, -sn, 0], [sn, c, 0], [0, 0, 1]])
|
||||
expected = (pr + [0, 0, .30]) @ R.T + truth['pos']
|
||||
error = float(np.max(np.linalg.norm(expected - pw, axis=1)))
|
||||
floor = int(np.count_nonzero(np.abs(pw[:, 2]) < .005))
|
||||
north = int(np.count_nonzero((np.abs(pw[:, 1]-5.5) < .005) & (pw[:, 2] >= -.005)
|
||||
& (pw[:, 2] <= .045)))
|
||||
west = int(np.count_nonzero((np.abs(pw[:, 0]+5.5) < .005) & (pw[:, 2] >= -.005)
|
||||
& (pw[:, 2] <= .045)))
|
||||
dt = np.diff(pairs) / 1e9
|
||||
body, sensor = probe.body[-1], probe.sensor[-1]
|
||||
shift = sensor.pose.pose.position.z - body.pose.pose.position.z
|
||||
checks = dict(raw_frame=raw.header.frame_id == 'lidar',
|
||||
world_frame=world.header.frame_id == 'world',
|
||||
cloud_3d=len(np.unique(np.round(pr[:, 2], 3))) > 10,
|
||||
finite_points=len(pw) > 1000, exact_stamp=stamp(raw) == stamp(world),
|
||||
stamp_monotonic=bool(np.all(dt > 0)),
|
||||
scan_rate=bool(np.max(dt) < .3),
|
||||
transform_matches_truth=error < .005,
|
||||
floor_correct=floor > 100, north_wall_correct=north > 2,
|
||||
west_wall_correct=west > 2,
|
||||
odom_frames=body.header.frame_id == 'world' and body.child_frame_id == 'base_link'
|
||||
and sensor.header.frame_id == 'world' and sensor.child_frame_id == 'lidar',
|
||||
sensor_mount=abs(shift-.30) < .001)
|
||||
np.savez_compressed(out / ('cloud_yaw_%d.npz' % round(yaw*180/math.pi)),
|
||||
raw=pr, world=pw, expected=expected)
|
||||
return dict(yaw=yaw, checks=checks, ok=all(checks.values()), settle=settle,
|
||||
truth=truth, stamp_ns=s, paired_clouds=len(pairs), finite_points=len(pw),
|
||||
fields=[f.name for f in raw.fields], rate_sim_hz=float(1/np.mean(dt)),
|
||||
transform_error_m=error, floor_points=floor, north_wall_points=north,
|
||||
west_wall_points=west, mount_shift_z=shift)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--out', required=True)
|
||||
args = ap.parse_args()
|
||||
out = Path(args.out).resolve()
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
os.environ.update(sim_env())
|
||||
sim = Sim(str(out/'sim'))
|
||||
report = {'phases': [], 'status': 'INVALID'}
|
||||
probe = None
|
||||
try:
|
||||
ok, why = sim.start(lidar=True)
|
||||
report['sim_start'] = why
|
||||
if not ok:
|
||||
raise RuntimeError(why)
|
||||
rclpy.init()
|
||||
probe = LidarProbe()
|
||||
if not probe.wait_clock():
|
||||
raise RuntimeError('no clock')
|
||||
for yaw in (0., math.pi/2):
|
||||
phase = check_phase(probe, out, yaw)
|
||||
report['phases'].append(phase)
|
||||
print('yaw %.3f: %s' % (yaw, phase['checks']), flush=True)
|
||||
report['status'] = 'PASS' if all(p['ok'] for p in report['phases']) else 'FAIL'
|
||||
except Exception as exc:
|
||||
report['error'] = repr(exc)
|
||||
print(report['error'], flush=True)
|
||||
finally:
|
||||
if probe is not None:
|
||||
probe.send(0., 0., 0.)
|
||||
probe.destroy_node()
|
||||
if rclpy.ok():
|
||||
rclpy.shutdown()
|
||||
report['teardown'] = sim.stop()
|
||||
(out/'result.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n')
|
||||
return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,166 @@
|
||||
#!/usr/bin/python3
|
||||
"""Validate force drive using independent Gazebo state, real contacts and lidar geometry."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from gazebo_msgs.msg import ContactsState
|
||||
from gazebo_msgs.srv import GetEntityState
|
||||
from geometry_msgs.msg import WrenchStamped
|
||||
from rclpy.qos import qos_profile_sensor_data
|
||||
from sensor_msgs.msg import PointCloud2
|
||||
|
||||
from check_omni_robot import BASE, Probe, Sim, reset_and_settle, sim_env
|
||||
from check_sim_lidar import points, stamp
|
||||
|
||||
|
||||
class SlopeProbe(Probe):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.contacts, self.wrenches, self.cloud_checks = [], [], []
|
||||
self.raw = {}
|
||||
self.create_subscription(ContactsState, '/sim/drive_contacts', self.on_contacts, 100)
|
||||
self.create_subscription(WrenchStamped, '/sim/drive_wrench', self.on_force, 100)
|
||||
self.create_subscription(PointCloud2, '/lidar/points', lambda m: self.raw.update({stamp(m):m}), qos_profile_sensor_data)
|
||||
self.create_subscription(PointCloud2, '/cloud_registered', self.on_cloud, 5)
|
||||
|
||||
def on_contacts(self, m):
|
||||
self.contacts.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
|
||||
pairs=[(s.collision1_name,s.collision2_name) for s in m.states],
|
||||
max_depth=max((d for s in m.states for d in s.depths),default=0.)))
|
||||
|
||||
def on_force(self, m):
|
||||
self.wrenches.append(dict(t=m.header.stamp.sec+m.header.stamp.nanosec*1e-9,
|
||||
force=[m.wrench.force.x,m.wrench.force.y,m.wrench.force.z],
|
||||
torque=[m.wrench.torque.x,m.wrench.torque.y,m.wrench.torque.z]))
|
||||
|
||||
def on_cloud(self, m):
|
||||
raw = self.raw.pop(stamp(m), None)
|
||||
if raw is None:
|
||||
return
|
||||
pr,pw = points(raw),points(m)
|
||||
self_hit = (np.abs(pr[:,0])<=.42)&(np.abs(pr[:,1])<=.42)&(pr[:,2]>=-.47)&(pr[:,2]<=-.20)
|
||||
roi = np.isfinite(pw).all(1)&(~self_hit)&(pw[:,0]>-.5)&(pw[:,0]<2.4)&(pw[:,1]>3.1)&(pw[:,1]<3.9)
|
||||
pc=pw[roi]
|
||||
if len(pc)>20:
|
||||
errors=np.abs(.597*pc[:,0]+3.5*pc[:,2]-1.6119)/math.hypot(.597,3.5)
|
||||
self.cloud_checks.append(dict(t=stamp(m)*1e-9,points=len(pc),max_plane_error_m=float(np.max(errors))))
|
||||
for key in sorted(self.raw)[:-20]:self.raw.pop(key)
|
||||
|
||||
def get_state(self):
|
||||
req=GetEntityState.Request(); req.name=BASE; req.reference_frame='world'
|
||||
res=self._call(self.cli_get,req)
|
||||
if res is None or not res.success:return None
|
||||
st=res.state;q=st.pose.orientation
|
||||
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(max(-1.,min(1.,2*(q.w*q.y-q.z*q.x))))
|
||||
yaw=math.atan2(2*(q.w*q.z+q.x*q.y),1-2*(q.y*q.y+q.z*q.z))
|
||||
return dict(stamp=res.header.stamp.sec+res.header.stamp.nanosec*1e-9,
|
||||
pos=[st.pose.position.x,st.pose.position.y,st.pose.position.z],yaw=yaw,
|
||||
rpy=[roll,pitch,yaw],quaternion=[q.x,q.y,q.z,q.w],
|
||||
twist_world=[st.twist.linear.x,st.twist.linear.y,st.twist.linear.z],
|
||||
wz=st.twist.angular.z)
|
||||
|
||||
|
||||
def hold(p, cmd, duration):
|
||||
samples=[];nxt=p.now()
|
||||
def sample():
|
||||
nonlocal nxt
|
||||
if p.now()<nxt:return
|
||||
state=p.get_state()
|
||||
if state is None:raise RuntimeError('independent truth unavailable')
|
||||
samples.append(state);nxt=p.now()+.04
|
||||
p.hold(*cmd,duration,sampler=sample)
|
||||
return samples
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
|
||||
ap.add_argument('--world');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')
|
||||
sim,p=Sim(str(out/'sim')),None
|
||||
report=dict(status='INVALID',phases={})
|
||||
source=Path(__file__).read_bytes();(out/'collector_snapshot.py').write_bytes(source)
|
||||
report['collector_sha256']=hashlib.sha256(source).hexdigest()
|
||||
try:
|
||||
ok,why=sim.start(lidar=True,drive='contact',world=args.world);report['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=SlopeProbe()
|
||||
if not p.wait_clock():raise RuntimeError('no clock')
|
||||
p.pump(.5)
|
||||
if not p.set_state(3.5,3.5,1.15,0.):raise RuntimeError('drop set failed')
|
||||
t0=p.now()
|
||||
drop=hold(p,(.2,0.,0.),.28)
|
||||
t=np.array([s['stamp'] for s in drop]); z=np.array([s['pos'][2] for s in drop])
|
||||
if len(np.unique(t))<5:raise RuntimeError('insufficient free-fall samples')
|
||||
acc=float(2*np.polyfit(t-t[0],z,2)[0])
|
||||
forces=[s for s in p.wrenches if t0+.04<s['t']<p.now()]
|
||||
checks=dict(gravity=abs(acc+9.81)<.5,
|
||||
no_air_drive=len(forces)>3 and max(np.linalg.norm(s['force']) for s in forces)<1e-6,
|
||||
horizontal_drift=abs(drop[-1]['pos'][0]-drop[0]['pos'][0])<.01)
|
||||
report['phases']['free_fall']=dict(checks=checks,acceleration_z_m_s2=acc,samples=drop)
|
||||
ok,rec=reset_and_settle(p,3.5,3.5,.17,0.,str(out))
|
||||
if not ok:raise RuntimeError('ramp start did not settle')
|
||||
t0=p.now()
|
||||
motions={}
|
||||
for name,cmd,duration in (
|
||||
('up_first',(-.25,0.,0.),10.),('stop',(0.,0.,0.),2.),
|
||||
('up_second',(-.25,0.,0.),8.8),('upper_landing',(0.,0.,0.),1.5),
|
||||
('down',(.25,0.,0.),18.8),('bottom',(0.,0.,0.),1.5)):
|
||||
motions[name]=hold(p,cmd,duration)
|
||||
(out/(name+'.json')).write_text(json.dumps(dict(samples=motions[name],
|
||||
contacts=p.contacts,wrenches=p.wrenches),indent=2)+'\n')
|
||||
print(name,motions[name][-1]['pos'],motions[name][-1]['rpy'],flush=True)
|
||||
if name=='up_first' and motions[name][-1]['pos'][0]>2.:
|
||||
report['phases']['ascent_entry']=dict(checks=dict(entered_ramp=False),samples=motions[name])
|
||||
report['status']='FAIL'
|
||||
return 30
|
||||
up1,stop,up2,top,down,bottom=[motions[n] for n in (
|
||||
'up_first','stop','up_second','upper_landing','down','bottom')]
|
||||
states=up1+up2+down
|
||||
mid=[s for s in states if -.35<s['pos'][0]<2.2]
|
||||
if len(mid)<20:raise RuntimeError('insufficient ramp samples')
|
||||
err=max(abs(s['pos'][2]-((1.6119-.597*s['pos'][0])/3.5+.15)) for s in mid)
|
||||
theta=math.atan2(.597,3.5)
|
||||
tilt=max(abs(s['rpy'][1]-theta) for s in mid)
|
||||
late=stop[len(stop)//2:]
|
||||
stop_speed=max(np.linalg.norm(s['twist_world']) for s in late)
|
||||
stop_drift=max(np.linalg.norm(np.array(s['pos'])-late[0]['pos']) for s in late)
|
||||
contacts=[s for s in p.contacts if s['t']>t0]
|
||||
force=[s for s in p.wrenches if s['t']>t0]
|
||||
clouds=[s for s in p.cloud_checks if s['t']>t0]
|
||||
checks=dict(reached_upper_landing=top[-1]['pos'][0]<-.9 and abs(top[-1]['pos'][2]-.749)<.03,
|
||||
returned_to_ground=bottom[-1]['pos'][0]>3. and abs(bottom[-1]['pos'][2]-.149)<.02,
|
||||
followed_ramp=err<.03,physical_pitch=tilt<.05,
|
||||
stayed_in_lane=max(abs(s['pos'][1]-3.5) for s in states)<.03,
|
||||
hill_stop=stop_speed<.01 and stop_drift<.02,
|
||||
ramp_contact=any('ramp_north' in n for s in contacts for pair in s['pairs'] for n in pair),
|
||||
no_excess_penetration=bool(contacts) and max(s['max_depth'] for s in contacts)<.005,
|
||||
no_vertical_or_tilt_actuator=bool(force) and all(s['force'][2]==0 and s['torque'][:2]==[0,0] for s in force),
|
||||
tilted_cloud_geometry=len(clouds)>10 and max(s['max_plane_error_m'] for s in clouds)<.01)
|
||||
report['phases']['round_trip']=dict(checks=checks,up_first=up1,stop=stop,up_second=up2,
|
||||
upper_landing=top,down=down,bottom=bottom,max_height_error_m=err,max_pitch_error_rad=tilt,
|
||||
hill_stop_speed_m_s=float(stop_speed),hill_stop_drift_m=float(stop_drift),
|
||||
contacts=contacts,applied_wrenches=force,cloud_geometry=clouds)
|
||||
for name,phase in report['phases'].items():print(name,phase['checks'],flush=True)
|
||||
report['status']='PASS' if all(all(v['checks'].values()) for v in report['phases'].values()) else 'FAIL'
|
||||
except Exception as exc:
|
||||
report['error']=repr(exc);print(report['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
report['teardown']=sim.stop()
|
||||
(out/'result.json').write_text(json.dumps(report,indent=2,
|
||||
default=lambda v:v.item() if isinstance(v,np.generic) else str(v))+'\n')
|
||||
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
|
||||
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -0,0 +1,141 @@
|
||||
#!/usr/bin/python3
|
||||
"""Existing SCAN reference-path controller + force physics: uphill, downhill, stair rejection."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from gazebo_msgs.msg import ContactsState
|
||||
from nav_msgs.msg import Path as NavPath
|
||||
from geometry_msgs.msg import PoseStamped
|
||||
from rclpy.qos import QoSProfile,DurabilityPolicy
|
||||
|
||||
from check_omni_robot import Sim,sim_env
|
||||
from check_scan_navigation import NavProbe
|
||||
from check_slope_drive import SlopeProbe
|
||||
from check_sim_lidar import points
|
||||
|
||||
LANE_Y=3.5125 # Midpoint of the rail's outer face y=3.025 and ramp edge y=4.
|
||||
|
||||
|
||||
class TerrainProbe(NavProbe):
|
||||
get_state=SlopeProbe.get_state
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.path_pub=self.create_publisher(NavPath,'/initial_path',
|
||||
QoSProfile(depth=1,durability=DurabilityPolicy.TRANSIENT_LOCAL))
|
||||
self.contacts=[]
|
||||
self.create_subscription(ContactsState,'/sim/drive_contacts',self.contacts.append,100)
|
||||
|
||||
|
||||
def run_path(p, xs, blocked=False):
|
||||
old_id=p.status[-1].goal_id if p.status else 0
|
||||
first_status,first_cmd,first_contacts=len(p.status),len(p.commands),len(p.contacts)
|
||||
first=p.get_state()
|
||||
if first is None:raise RuntimeError('missing starting truth')
|
||||
msg=NavPath();msg.header.frame_id='world';msg.header.stamp=p.get_clock().now().to_msg()
|
||||
for x in xs:
|
||||
z=0.15 if blocked and x<-1.8 else (0. if x>=2.7 else (.6 if x<=-.8 else (1.6119-.597*x)/3.5))
|
||||
pose=PoseStamped();pose.header=msg.header;pose.pose.position.x=float(x)
|
||||
pose.pose.position.y=LANE_Y;pose.pose.position.z=z;pose.pose.orientation.w=1.
|
||||
msg.poses.append(pose)
|
||||
p.path_pub.publish(msg)
|
||||
t0,end=p.now(),time.monotonic()+360
|
||||
states=[]
|
||||
while p.now()-t0<65 and time.monotonic()<end:
|
||||
p.pump(.1);state=p.get_state()
|
||||
if state is None:raise RuntimeError('missing independent state')
|
||||
states.append(state)
|
||||
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
|
||||
p.pump(1.)
|
||||
rest=[]
|
||||
for _ in range(10):p.pump(.1);rest.append(p.get_state())
|
||||
if any(s is None for s in rest):raise RuntimeError('missing stop truth')
|
||||
status=p.status[-1]
|
||||
statuses=p.status[first_status:];commands=p.commands[first_cmd:]
|
||||
contacts=p.contacts[first_contacts:]
|
||||
err=math.hypot(rest[-1]['pos'][0]-xs[-1],rest[-1]['pos'][1]-LANE_Y)
|
||||
goal_z=msg.poses[-1].pose.position.z+.15
|
||||
drift=max(math.dist(s['pos'],rest[0]['pos']) for s in rest)
|
||||
checks=dict(acknowledged=status.goal_id>old_id,
|
||||
state_as_expected=status.state==(status.FAILED if blocked else status.SUCCEEDED),
|
||||
perception_fresh=p.ready,
|
||||
stopped=drift<.02 and max(math.hypot(*s['twist_world'][:2]) for s in rest)<.01,
|
||||
original_goal_preserved=abs(status.goal.x-xs[-1])<1e-6 and abs(status.goal.y-LANE_Y)<1e-6)
|
||||
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:
|
||||
mid=[s for s in states if -.35<s['pos'][0]<2.2]
|
||||
checks.update(active=any(s.state==s.ACTIVE for s in statuses),physical_arrival=err<.10,
|
||||
physical_height=abs(rest[-1]['pos'][2]-goal_z)<.03,
|
||||
ramp_pitch=bool(mid) and max(abs(s['rpy'][1]-math.atan2(.597,3.5)) for s in mid)<.05,
|
||||
ramp_height=bool(mid) and max(abs(s['pos'][2]-((1.6119-.597*s['pos'][0])/3.5+.15)) for s in mid)<.04,
|
||||
lane=max(abs(s['pos'][1]-LANE_Y) for s in states)<.03,
|
||||
real_ramp_contacts=any(('ramp_north' if LANE_Y>0 else 'ramp_south') in pair for m in contacts for s in m.states
|
||||
for pair in (s.collision1_name,s.collision2_name)),
|
||||
penetration=bool(contacts) and max((d for m in contacts for s in m.states for d in s.depths),default=1)<.005)
|
||||
return dict(checks=checks,ok=all(checks.values()),duration_sim_s=p.now()-t0,
|
||||
goal=[xs[-1],LANE_Y,goal_z],position_error_m=err,stop_drift_m=drift,
|
||||
input_path=[[s.pose.position.x,s.pose.position.y,s.pose.position.z] for s in msg.poses],
|
||||
samples=states,stop_samples=rest,commands=commands,
|
||||
statuses=[dict(t=s.header.stamp.sec+s.header.stamp.nanosec*1e-9,state=s.state,reason=s.reason,
|
||||
goal=[s.goal.x,s.goal.y,s.goal.z],traj_id=s.traj_id) for s in statuses])
|
||||
|
||||
|
||||
def main():
|
||||
global LANE_Y
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--out',required=True)
|
||||
ap.add_argument('--side',choices=('red','blue'),default='red')
|
||||
ap.add_argument('--case',choices=('round_trip','stairs_rejected'),default='round_trip')
|
||||
args=ap.parse_args()
|
||||
if args.side=='blue':LANE_Y=-LANE_Y
|
||||
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',side=args.side,cases={},collector_sha256=hashlib.sha256(source).hexdigest())
|
||||
sim,p=Sim(str(out/'sim')),None
|
||||
try:
|
||||
spawn=(1.5,LANE_Y,.5,0.) if args.case=='stairs_rejected' else (3.5,LANE_Y,.15,0.)
|
||||
ok,why=sim.start(navigation=True,terrain=True,spawn=spawn);report['startup']=why
|
||||
if not ok:raise RuntimeError(why)
|
||||
rclpy.init();p=TerrainProbe()
|
||||
if not p.wait_clock():raise RuntimeError('no clock')
|
||||
end=time.monotonic()+90
|
||||
while time.monotonic()<end:
|
||||
rclpy.spin_once(p,timeout_sec=.02)
|
||||
if p.ready and p.status and p.path_pub.get_subscription_count()>0:break
|
||||
else:raise RuntimeError('terrain pipeline not ready')
|
||||
p.pump(2.)
|
||||
# A distant goal outside the sliding map is allowed to approach before
|
||||
# re-evaluation. Test immediate rejection only with the goal observed.
|
||||
cases=([('stairs_rejected',[1.5,-2.5],True)] if args.case=='stairs_rejected' else
|
||||
[('uphill',[3.5,2.7,-.8,-1.2],False),('downhill',[-1.2,-.8,2.7,3.5],False)])
|
||||
for name,xs,blocked in cases:
|
||||
result=run_path(p,xs,blocked)
|
||||
report['cases'][name]=result
|
||||
(out/(name+'.json')).write_text(json.dumps(result,indent=2)+'\n')
|
||||
np.savez_compressed(out/(name+'_map.npz'),**{t:points(m) for t,m in p.clouds.items()})
|
||||
print(name,result['checks'],'error',result['position_error_m'],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()) else 'FAIL'
|
||||
except Exception as exc:
|
||||
report['error']=repr(exc);print(report['error'],flush=True)
|
||||
finally:
|
||||
if p is not None:p.send(0.,0.,0.);p.destroy_node()
|
||||
if rclpy.ok():rclpy.shutdown()
|
||||
report['teardown']=sim.stop()
|
||||
(out/'result.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
return {'PASS':0,'FAIL':30,'INVALID':40}[report['status']]
|
||||
|
||||
|
||||
if __name__=='__main__':sys.exit(main())
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/python3
|
||||
"""Reproduce the pinned upstream ramp face-winding correction, without moving vertices."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
UPSTREAM_SHA256 = '5344932eae23391872e371758bbe9a70a6b5b9979fa53d3862b3183bee331f13'
|
||||
|
||||
|
||||
def corrected_bytes(source):
|
||||
if hashlib.sha256(source).hexdigest() != UPSTREAM_SHA256:
|
||||
raise ValueError('Unknown upstream ramp: review geometry before applying this repair')
|
||||
lines=source.decode().splitlines(keepends=True)
|
||||
return ''.join('f '+' '.join(reversed(l.split()[1:]))+'\n' if l.startswith('f ') else l
|
||||
for l in lines).encode()
|
||||
|
||||
|
||||
def geometry(data):
|
||||
lines=data.decode().splitlines()
|
||||
vertices=[tuple(map(float,l.split()[1:])) for l in lines if l.startswith('v ')]
|
||||
faces=[tuple(int(v)-1 for v in l.split()[1:]) for l in lines if l.startswith('f ')]
|
||||
volume=0.
|
||||
for f in faces:
|
||||
a,b,c=[vertices[i] for i in f]
|
||||
volume+=(a[0]*(b[1]*c[2]-b[2]*c[1])+a[1]*(b[2]*c[0]-b[0]*c[2])+a[2]*(b[0]*c[1]-b[1]*c[0]))/6
|
||||
edges={}
|
||||
for f in faces:
|
||||
for a,b in zip(f,f[1:]+f[:1]):edges[(a,b)]=edges.get((a,b),0)+1
|
||||
closed=all(count==1 and edges.get((b,a))==1 for (a,b),count in edges.items())
|
||||
return vertices,faces,volume,closed
|
||||
|
||||
|
||||
def verify(source,target):
|
||||
sv,sf,volume_in,closed_in=geometry(source)
|
||||
tv,tf,volume_out,closed_out=geometry(target)
|
||||
return dict(upstream_sha256=hashlib.sha256(source).hexdigest(),
|
||||
repaired_sha256=hashlib.sha256(target).hexdigest(),
|
||||
exact_pinned_repair=target==corrected_bytes(source),
|
||||
vertices_unchanged=sv==tv,
|
||||
all_faces_reversed=tf==[tuple(reversed(f)) for f in sf],
|
||||
closed_before=closed_in,closed_after=closed_out,
|
||||
signed_volume_before_m3=volume_in,signed_volume_after_m3=volume_out)
|
||||
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('source');ap.add_argument('--output',required=True)
|
||||
args=ap.parse_args();source=Path(args.source).read_bytes();target=corrected_bytes(source)
|
||||
evidence=verify(source,target)
|
||||
assert all(evidence[k] for k in ('exact_pinned_repair','vertices_unchanged','all_faces_reversed','closed_before','closed_after'))
|
||||
assert evidence['signed_volume_before_m3']<0<evidence['signed_volume_after_m3']
|
||||
Path(args.output).write_bytes(target)
|
||||
print(json.dumps(evidence,indent=2))
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/python3
|
||||
"""Numerical/reference-frame and fail-closed contract tests; no Gazebo required."""
|
||||
from array import array
|
||||
import copy
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
import rclpy
|
||||
from nav_msgs.msg import Odometry
|
||||
from sensor_msgs.msg import PointCloud2,PointField
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src/br_sim_bringup/scripts'))
|
||||
from lio_navigation_adapter import FixedAlignment,LioNavigationAdapter,quaternion,rotation,shifted_twist,float_fields
|
||||
|
||||
|
||||
class Recorder:
|
||||
def __init__(self):self.messages=[]
|
||||
def publish(self,m):self.messages.append(copy.deepcopy(m))
|
||||
|
||||
|
||||
class GeometryTests(unittest.TestCase):
|
||||
def test_known_start_maps_imu_and_optical_origins(self):
|
||||
imu=np.array([.011,.02329,.25588]);prior=np.array([-4.5,4.5,.15,math.pi/2])
|
||||
p=np.array([.2,-.3,.02]);q=np.array([0.,0.,math.sin(.35),math.cos(.35)])
|
||||
a=FixedAlignment(prior,imu,p,q)
|
||||
base,bq=a.pose(p,q,-imu);lidar,_=a.pose(p,q,np.array([0.,0.,.3])-imu)
|
||||
np.testing.assert_allclose(base,prior[:3],atol=1e-12)
|
||||
np.testing.assert_allclose(lidar,prior[:3]+[0,0,.3],atol=1e-12)
|
||||
self.assertAlmostEqual(math.atan2(rotation(bq)[1,0],rotation(bq)[0,0]),math.pi/2)
|
||||
old_t=a.t.copy();later,_=a.pose(p+[1,0,0],q,-imu)
|
||||
np.testing.assert_allclose(later-base,a.R@[1,0,0],atol=1e-12)
|
||||
np.testing.assert_array_equal(a.t,old_t)
|
||||
|
||||
def test_rotating_imu_lever_arm_by_finite_difference(self):
|
||||
offset=np.array([.011,.02329,.25588]);yaw=.8;w=.4;dt=1e-6
|
||||
def R(y):return np.array([[math.cos(y),-math.sin(y),0],[math.sin(y),math.cos(y),0],[0,0,1]])
|
||||
imu_world_velocity=(R(yaw+w*dt)@offset-R(yaw-w*dt)@offset)/(2*dt)
|
||||
imu_body_velocity=R(yaw).T@imu_world_velocity
|
||||
base=shifted_twist(imu_body_velocity,[0,0,w],-offset)
|
||||
np.testing.assert_allclose(base,[0,0,0],atol=1e-10)
|
||||
lidar=shifted_twist(imu_body_velocity,[0,0,w],np.array([0,0,.3])-offset)
|
||||
np.testing.assert_allclose(lidar,[0,0,0],atol=1e-10)
|
||||
|
||||
def test_invalid_quaternions_are_rejected(self):
|
||||
for values in ([0,0,0,0],[0,0,0,2],[float('nan'),0,0,1]):
|
||||
with self.assertRaises(ValueError):quaternion(values)
|
||||
|
||||
|
||||
class AdapterTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):rclpy.init()
|
||||
@classmethod
|
||||
def tearDownClass(cls):rclpy.shutdown()
|
||||
def setUp(self):
|
||||
self.node=LioNavigationAdapter();self.time=1.;self.node.now_s=lambda:self.time
|
||||
for key in ('body_pub','sensor_pub','world_pub','planning_pub','ready_pub','status_pub'):setattr(self.node,key,Recorder())
|
||||
def tearDown(self):self.node.destroy_node()
|
||||
def odom(self,t):
|
||||
self.time=t;m=Odometry();m.header.frame_id='camera_init';m.child_frame_id='body'
|
||||
m.header.stamp.sec=int(t);m.header.stamp.nanosec=round((t-int(t))*1e9)
|
||||
m.pose.pose.orientation.w=1.;return m
|
||||
def anchor(self):
|
||||
for t in np.arange(1.,2.11,.05):self.node.on_odom(self.odom(float(t)))
|
||||
self.assertIsNotNone(self.node.alignment)
|
||||
|
||||
def test_stale_and_discontinuous_odometry_never_reanchors(self):
|
||||
self.anchor();t=self.node.odom_stamp;translation=self.node.alignment.t.copy()
|
||||
stale=self.odom(t);self.time=t+.3;count=len(self.node.body_pub.messages)
|
||||
self.node.on_odom(stale);self.node.health()
|
||||
self.assertFalse(self.node.ready_pub.messages[-1].data)
|
||||
self.assertEqual(len(self.node.body_pub.messages),count)
|
||||
self.node.on_odom(self.odom(t+1.))
|
||||
self.assertTrue(self.node.fault)
|
||||
self.assertEqual(len(self.node.body_pub.messages),count)
|
||||
np.testing.assert_array_equal(self.node.alignment.t,translation)
|
||||
|
||||
def test_paired_cloud_filters_original_indices_and_preserves_stamp(self):
|
||||
self.anchor();n=111;data=np.zeros((n,6),dtype='<f4');data[:,3]=1.
|
||||
data[0,3:]=[0,0,-.3] # self return, regardless of latest robot pose
|
||||
data[1,2]=-self.node.alignment.t[2] # world ground
|
||||
m=PointCloud2();m.header.frame_id='camera_init';m.header.stamp=self.odom(self.time).header.stamp
|
||||
m.height=1;m.width=n;m.point_step=24;m.row_step=24*n
|
||||
m.fields=[PointField(name=name,offset=i*4,datatype=PointField.FLOAT32,count=1) for i,name in enumerate(('x','y','z','lidar_x','lidar_y','lidar_z'))]
|
||||
m.data=array('B',data.tobytes());self.node.on_cloud(m);self.node.health()
|
||||
self.assertTrue(self.node.ready_pub.messages[-1].data)
|
||||
full=self.node.world_pub.messages[-1];filtered=self.node.planning_pub.messages[-1]
|
||||
self.assertEqual(filtered.header.stamp,m.header.stamp)
|
||||
xyz=np.stack(float_fields(filtered,('x','y','z')),axis=-1).reshape(n,3)
|
||||
self.assertTrue(np.isnan(xyz[:2]).all());self.assertTrue(np.isfinite(xyz[2:]).all())
|
||||
for a,b in zip(float_fields(full,('lidar_x','lidar_y','lidar_z')),float_fields(filtered,('lidar_x','lidar_y','lidar_z'))):np.testing.assert_array_equal(a,b)
|
||||
|
||||
def test_wrong_source_frame_latches_stop(self):
|
||||
m=self.odom(1.);m.header.frame_id='world';self.node.on_odom(m)
|
||||
self.assertTrue(self.node.fault);self.assertIsNone(self.node.alignment)
|
||||
|
||||
def test_known_slope_uncertainty_preserves_raised_obstacles(self):
|
||||
self.anchor();self.node.planes=[[-.8,2.7,3.,4.,-.597/3.5,0.,1.6119/3.5]]
|
||||
self.node.surface_tolerance=.06
|
||||
xyz=[]
|
||||
for bias in (-.04,0.,.04):
|
||||
for height in (0.,.15):
|
||||
xyz.extend([[1.,3.5,(1.6119-.597)/3.5+bias+height]]*20)
|
||||
data=np.ones((len(xyz),6),dtype='<f4');data[:,:3]=np.asarray(xyz)-self.node.alignment.t
|
||||
m=PointCloud2();m.header.frame_id='camera_init';m.header.stamp=self.odom(self.time).header.stamp
|
||||
m.height=1;m.width=len(data);m.point_step=24;m.row_step=24*len(data)
|
||||
m.fields=[PointField(name=n,offset=i*4,datatype=PointField.FLOAT32,count=1) for i,n in enumerate(('x','y','z','lidar_x','lidar_y','lidar_z'))]
|
||||
m.data=array('B',data.tobytes());original=bytes(m.data);self.node.on_cloud(m)
|
||||
result=np.stack(float_fields(self.node.planning_pub.messages[-1],('x','y','z')),axis=-1).reshape(-1,3)
|
||||
for i in range(3):
|
||||
self.assertTrue(np.isnan(result[i*40:i*40+20]).all())
|
||||
self.assertTrue(np.isfinite(result[i*40+20:(i+1)*40]).all())
|
||||
self.assertEqual(bytes(m.data),original)
|
||||
full=np.stack(float_fields(self.node.world_pub.messages[-1],('x','y','z')),axis=-1).reshape(-1,3)
|
||||
np.testing.assert_allclose(full,xyz,atol=1e-6)
|
||||
|
||||
def test_downstream_planning_loss_revokes_readiness(self):
|
||||
self.anchor();self.node.planning_topic='/sim/navigation/terrain_planning_cloud'
|
||||
self.node.planning_max_age=.2
|
||||
self.node.cloud_stamp=self.time;self.node.downstream_stamp=self.time
|
||||
self.node.health();self.assertTrue(self.node.ready_pub.messages[-1].data)
|
||||
self.time+=.19;self.node.odom_stamp=self.time;self.node.cloud_stamp=self.time
|
||||
self.node.health();self.assertTrue(self.node.ready_pub.messages[-1].data)
|
||||
self.time+=.02;self.node.odom_stamp=self.time;self.node.cloud_stamp=self.time
|
||||
self.node.health();self.assertFalse(self.node.ready_pub.messages[-1].data)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user