Files
RC2027_BR_code/sim_ws/tools/check_narrow_navigation.py
T

189 lines
8.4 KiB
Python
Raw Normal View History

#!/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())