Files
NODEDC_MISSION_CORE/tests/test_observed_recovery.py
T

383 lines
17 KiB
Python

import math
import pytest
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
from k1link.simulation.ai_polygon.observed_recovery import ObservedRecovery
def pose(x=0, y=0, yaw=0):
return [x, y, .37, 0, 0, math.sin(yaw/2), math.cos(yaw/2)]
def survey(recovery, position, choose, start=0):
recovery.tick(position, start, choose)
recovery.tick(position, start+.2, choose)
for index, sector in enumerate(recovery.sectors):
now = start+.4+index*.2
request = recovery.view_request(position, now)
assert request["yaw_degrees"] == sector
recovery.observe_view(request, position, now)
goal, state = recovery.tick(position, now, choose)
assert goal is None
return now
@pytest.mark.parametrize("destination,reverse", [([0, 1.5, 0], False),
([0, -1.5, 0], False),
([-.65, 0, 0], True)])
def test_survey_precedes_any_manoeuvre_and_is_not_a_body_turn(destination, reverse):
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=destination, reverse=reverse)
calls = []
def choose(prior, excluded):
calls.append(prior)
return selected
assert r.tick(pose(), 0, choose)[0] is None
assert not calls and r.orientation() is None
now = survey(r, pose(), choose, .2)
request = r.view_request(pose(), now+.2)
assert request is not None
assert r.tick(pose(), now+.2, choose)[0] is None
r.observe_view(request, pose(), now+.2)
assert r.tick(pose(), now+.3, choose) == (
destination, "reversing" if reverse else "manoeuvring")
if not reverse:
assert r.orientation()["xy"] == destination[:2]
# No old camera result can keep authorising this sector indefinitely.
assert r.tick(pose(), now+2.5, choose)[0] is None
def test_old_request_and_pre_request_capture_cannot_acknowledge_survey():
r = ObservedRecovery()
r.begin(pose(), 0, [])
r.tick(pose(), 0, lambda *_: None)
r.tick(pose(), .2, lambda *_: None)
first = r.view_request(pose(), .2)
r.observe_view(first, pose(), .1)
assert not r.views
r.begin(pose(), 1, [])
r.tick(pose(), 1, lambda *_: None)
r.tick(pose(), 1.2, lambda *_: None)
second = r.view_request(pose(), 1.2)
assert first != second
r.observe_view(first, pose(), 1.2)
assert not r.views
def test_blocked_manoeuvre_is_retired_before_trying_another_direction():
r = ObservedRecovery()
r.begin(pose(), 0, [])
first = dict(goal=[0, 1.5, 0], reverse=False)
choose = lambda prior, excluded: first if not excluded else dict(goal=[0, -1.5, 0], reverse=False)
now = survey(r, pose(), choose)
r.observe_view(r.view_request(pose(), now+.1), pose(), now+.1)
r.tick(pose(), now+.2, choose)
assert r.tick(pose(), now+9, choose)[0] is None
assert r.excluded == [first["goal"]]
r.tick(pose(), now+9.2, choose)
assert r.selected["goal"] == [0, -1.5, 0]
def test_survey_does_not_assume_rear_ground_or_create_a_destination():
r = ObservedRecovery()
r.begin(pose(), 0, [])
survey(r, pose(), lambda *_: None)
assert not r.active and r.selected is None
def test_orientation_only_recovery_never_creates_a_translation_goal():
r = ObservedRecovery()
r.begin(pose(), 0, [])
choose = lambda *_: dict(goal=[0, 2, 0], reverse=False, kind="orient")
now = survey(r, pose(), choose)
r.observe_view(r.view_request(pose(), now+.1), pose(), now+.1)
assert r.tick(pose(), now+.2, choose) == (None, 'orienting')
assert r.orientation()['xy'] == [0, 2]
# Rotation alone completes this observation manoeuvre, with zero travel.
assert r.tick(pose(yaw=math.pi/2), now+4, choose) == (None, 'replanning')
assert not r.active
def test_progressing_turn_is_not_abandoned_at_an_absolute_duration_limit():
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=[0, 2, 0], reverse=False, kind='orient')
choose = lambda *_: selected
start = survey(r, pose(), choose)
option = r.option
for step in range(1, 146):
now, position = start+step, pose(yaw=.01*step)
r.observe_view(r.view_request(position, now), position, now)
assert r.tick(position, now, choose) == (None, 'orienting')
assert r.active and r.option == option and not r.excluded
assert r.tick(pose(yaw=math.pi/2), start+146, choose) == (None, 'replanning')
assert not r.active
def test_recovery_distance_and_rotation_do_not_replenish_task_progress():
mission = WaypointMission([[10, 0]])
normal = lambda *_: [2, 0, 0]
maneuver = lambda *_: dict(goal=[0, 1.5, 0], reverse=False)
mission.update(pose(), 0, normal, choose_maneuver=maneuver)
assert mission.update(pose(), 8, normal, choose_maneuver=maneuver)[1]["state"] == "surveying"
survey(mission.recovery, pose(), maneuver, 8)
mission.recovery.observe_view(mission.recovery.view_request(pose(), 10), pose(), 10)
goal, intent = mission.update(pose(), 10.1, normal, choose_maneuver=maneuver)
assert goal == [0, 1.5, 0] and intent["state"] == "manoeuvring"
mission.update(pose(0, 1.4, math.pi/2), 13, normal, choose_maneuver=maneuver)
assert not mission.recovery.active and mission.attempts == 1
mission.update(pose(), 14, normal, choose_maneuver=maneuver)
assert mission.attempts == 1 and mission.best_distance == 10
def test_completed_recovery_invalidates_old_alignment_and_preserves_retry_budget(monkeypatch):
import importlib
from pathlib import Path
monkeypatch.syspath_prepend(str(Path(__file__).parents[1]/'simulation/ai-polygon'))
approach = importlib.import_module('navigation.arrival_approach').ArrivalApproach()
mission = WaypointMission([[10, 0]])
normal = lambda *_: [2, 0, 0]
mission.update(pose(), 0, normal)
target = mission.orientation_target()
assert approach.command(pose(), target, 0, .2, 0, enabled=True)[2]['phase'] == 'local-path'
assert approach.completed
mission.recovery.begin(pose(), 8, [])
mission.attempts = 1
mission.recovery.phase = 'executing'
mission.recovery.selected = dict(goal=[-2, 0, 0], reverse=False, kind='orient')
# The physical manoeuvre finishes facing backward, farther from the task.
position = pose(-1, yaw=math.pi)
mission.update(position, 100, normal, choose_maneuver=lambda prior, _: prior)
assert not mission.recovery.active
new_target = mission.orientation_target()
assert new_target['xy'] == target['xy'] and new_target['key'] != target['key']
assert mission.turn_started is None
assert approach.command(position, new_target, 100, .2, 0, enabled=True)[2]['phase'] == 'braking'
v, w, evidence = approach.command(position, new_target, 100.2, .2, 0, enabled=True)
assert v == 0 and abs(w) > 0 and evidence['phase'] == 'aligning'
# Re-alignment alone must not credit retreat as route progress.
mission.heading_progress(position, 100)
mission.heading_progress(pose(-1), 120)
assert mission.attempts == 1 and mission.best_distance == 10 and mission.index == 0
@pytest.mark.parametrize('failure', ['footprint', 'no-path'])
def test_repeated_fresh_body_veto_retires_option_without_waiting_progress_timeout(failure):
r = ObservedRecovery(); p = pose(); r.begin(p,0,[])
selected = dict(goal=[0,1.5,0],reverse=False)
choose = lambda *_: selected
now = survey(r,p,choose)
r.observe_view(r.view_request(p,now+.1),p,now+.1)
r.tick(p,now+.2,choose)
key = (r.sequence,r.option)
def reply(t,failure=failure):
return dict(status='blocked',speed_mps=0,yaw_rate_rps=0,
diagnostic=dict(failure=failure),route_observation=dict(observation=dict(
pose=p,simulation_time_seconds=t,execution_inputs_sha256='run')))
# Wrong option, stale receipts, and missing observations cannot reject it.
r.observe_navigation(reply(now+.2),p,now+.2,(0,0),'run')
r.observe_navigation(reply(now+.2),p,now+.8,key,'run')
r.observe_navigation(reply(now+.8),p,now+.8,key,'different-run')
assert r.blockage is None
r.observe_navigation(reply(now+.8),p,now+.8,key,'run')
r.observe_navigation(reply(now+1),p,now+1,key,'run')
assert not r.blocked_option
# Planner/data waiting breaks confirmation; it is not an obstacle.
r.observe_navigation(reply(now+1.1,'stale-range'),p,now+1.1,key,'run')
assert r.blockage is None
r.observe_navigation(reply(now+1.2),p,now+1.2,key,'run')
r.observe_navigation(reply(now+1.8),p,now+1.8,key,'run')
assert r.blocked_option
assert r.tick(p,now+1.9,choose) == (None,'surveying')
assert r.excluded == [selected['goal']]
r.tick(p,now+2,choose)
assert not r.blocked_option and r.blockage is None
def completed_path(position, seconds, goal):
return dict(status='waiting-for-plan', speed_mps=0., yaw_rate_rps=0.,
diagnostic=dict(failure='native-action-complete'),
action_result=dict(status='succeeded', kind='path', goal_xy=goal[:2]),
route_observation=dict(observation=dict(pose=position,
simulation_time_seconds=seconds, execution_inputs_sha256='run')))
def test_native_local_completion_returns_to_mission_without_rejecting_goal():
mission = WaypointMission([[10, 0]])
def choose(*_):
return [3., 0., 0.]
selected = dict(goal=[2., 0., 0.], reverse=False)
def maneuver(*_):
return selected
mission.update(pose(), 0, choose, choose_maneuver=maneuver)
mission.update(pose(), 8, choose, choose_maneuver=maneuver)
survey(mission.recovery, pose(), maneuver, 8)
# A native local action can succeed outside the legacy 30 cm test. It is
# completion of that action only, never the mission arrival receipt.
position, now = pose(1.61), 12.
receipt = completed_path(position, now, selected['goal'])
r = mission.recovery
r.observe_navigation(receipt, position, now, (r.sequence, r.option), 'run')
goal, intent = mission.update(position, now, choose, choose_maneuver=maneuver)
assert (goal, intent['state']) == (None, 'replanning')
assert not r.active and r.excluded == [[3., 0., 0.]] and mission.index == 0
assert intent['last_recovery_attempt']['completion'] == receipt['action_result']
goal, intent = mission.update(position, now+.1, choose, choose_maneuver=maneuver)
assert goal == [3., 0., 0.] and intent['state'] == 'following'
assert mission.fault is None
@pytest.mark.parametrize('mismatch', ['run', 'time', 'pose', 'option', 'goal', 'kind',
'failed', 'missing', 'nonzero', 'status'])
def test_unbound_or_unsuccessful_result_cannot_complete_local_recovery(mismatch):
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=[2., 0., 0.], reverse=False)
def choose(*_):
return selected
survey(r, pose(), choose)
position, now = pose(1.61), 2.
receipt = completed_path(position, now, selected['goal'])
key, run = (r.sequence, r.option), 'run'
if mismatch == 'run':
run = 'another-run'
elif mismatch == 'time':
now += .1
elif mismatch == 'pose':
position = pose(1.6)
elif mismatch == 'option':
key = (r.sequence, r.option+1)
elif mismatch == 'goal':
receipt['action_result']['goal_xy'] = [3., 0.]
elif mismatch == 'kind':
receipt['action_result']['kind'] = 'spin'
elif mismatch == 'failed':
receipt['action_result']['status'] = 'aborted'
elif mismatch == 'missing':
receipt.pop('action_result')
elif mismatch == 'nonzero':
receipt['speed_mps'] = .1
elif mismatch == 'status':
receipt['status'] = 'blocked'
r.observe_navigation(receipt, position, now, key, run)
r.tick(position, now+.1, choose)
assert r.active and r.selected == selected
@pytest.mark.parametrize('reverse', [False, True])
@pytest.mark.parametrize('mismatch', [None, 'run', 'time', 'pose', 'option', 'goal', 'kind',
'missing', 'nonzero', 'status'])
def test_only_bound_native_abort_retires_the_local_option(reverse, mismatch):
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=[-2. if reverse else 2., 0., 0.], reverse=reverse)
choose = lambda *_: selected
survey(r, pose(), choose)
position, now = pose(), 2.
receipt = completed_path(position, now, selected['goal'])
receipt.update(status='blocked', diagnostic=dict(failure='native-action-aborted'))
receipt['action_result'].update(status='aborted', kind='backup' if reverse else 'path')
key, run = (r.sequence, r.option), 'run'
if mismatch == 'run': run = 'another-run'
elif mismatch == 'time': now += .1
elif mismatch == 'pose': position = pose(.1)
elif mismatch == 'option': key = (r.sequence, r.option+1)
elif mismatch == 'goal': receipt['action_result']['goal_xy'] = [9., 0.]
elif mismatch == 'kind': receipt['action_result']['kind'] = 'spin'
elif mismatch == 'missing': receipt.pop('action_result')
elif mismatch == 'nonzero': receipt['speed_mps'] = .1
elif mismatch == 'status': receipt['status'] = 'waiting-for-plan'
r.observe_navigation(receipt, position, now, key, run)
assert r.blocked_option is (mismatch is None)
assert r.completion is None
if mismatch is None:
assert r.tick(position, now+.1, choose)[0] is None
assert r.excluded == [selected['goal']]
@pytest.mark.parametrize("reverse", [False, True])
def test_native_action_finishes_its_own_distance_before_returning_to_route(reverse):
r = ObservedRecovery()
r.begin(pose(), 0, [])
sign = -1 if reverse else 1
selected = dict(goal=[sign*.7, 0., 0.], reverse=reverse)
choose = lambda *_: selected
now = survey(r, pose(), choose)
receipt = completed_path(pose(), now, selected['goal'])
receipt.update(status='path', speed_mps=sign*.1,
controller_goal=['backup' if reverse else 'path', selected['goal'][:2], .1])
receipt.pop('action_result')
r.observe_navigation(receipt, pose(), now, (r.sequence, r.option), 'run')
position = pose(sign*.45)
r.observe_view(r.view_request(position, now+1), position, now+1)
assert r.tick(position, now+1, choose) == (
selected['goal'], 'reversing' if reverse else 'manoeuvring')
assert r.active and r.completion is None
# A completed native action stops intent even slightly past its goal.
position = pose(sign*.71)
receipt = completed_path(position, now+2, selected['goal'])
receipt['action_result']['kind'] = 'backup' if reverse else 'path'
r.observe_navigation(receipt, position, now+2, (r.sequence, r.option), 'run')
assert r.tick(position, now+2, choose) == (None, 'replanning')
assert not r.active
@pytest.mark.parametrize('mismatch', ['run', 'time', 'pose', 'option', 'goal', 'kind'])
def test_unbound_owner_cannot_suppress_legacy_completion(mismatch):
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=[-.7, 0., 0.], reverse=True)
choose = lambda *_: selected
now = survey(r, pose(), choose)
receipt = completed_path(pose(), now, selected['goal'])
receipt.update(status='path', speed_mps=-.1,
controller_goal=['backup', [-.7, 0.], .1])
receipt.pop('action_result')
position, key, run = pose(), (r.sequence, r.option), 'run'
if mismatch == 'run': run = 'other'
elif mismatch == 'time': now += .1
elif mismatch == 'pose': position = pose(.1)
elif mismatch == 'option': key = (r.sequence, r.option+1)
elif mismatch == 'goal': receipt['controller_goal'][1] = [-1., 0.]
elif mismatch == 'kind': receipt['controller_goal'][0] = 'spin'
r.observe_navigation(receipt, position, now, key, run)
assert r.native_action is None
assert r.tick(pose(-.45), now+1, choose) == (None, 'replanning')
def test_native_owner_does_not_bypass_unknown_view_or_progress_budget():
r = ObservedRecovery()
r.begin(pose(), 0, [])
selected = dict(goal=[-.7, 0., 0.], reverse=True)
choose = lambda *_: selected
now = survey(r, pose(), choose)
receipt = completed_path(pose(), now, selected['goal'])
receipt.update(status='path', speed_mps=-.1,
controller_goal=['backup', [-.7, 0.], .1])
receipt.pop('action_result')
r.observe_navigation(receipt, pose(), now, (r.sequence, r.option), 'run')
# Close enough for the former distance threshold, but no current rear view.
assert r.tick(pose(-.45), now+3, choose) == (None, 'surveying')
assert r.active
assert r.tick(pose(-.45), now+12, choose) == (None, 'surveying')
assert r.excluded == [selected['goal']]
r.tick(pose(-.45), now+12.1, choose)
assert r.native_action is None
def test_backup_keeps_rear_observation_when_lateral_error_dominates_near_goal():
r = ObservedRecovery()
r.phase = 'executing'
r.sequence, r.option = 1, 1
r.selected = dict(goal=[-.7, 0., 0.], reverse=True)
request = r.view_request(pose(), 1.)
assert request['yaw_degrees'] == 180
near = pose()
near[0], near[1] = -.68, -.05
assert r.view_request(near, 2.) == request
# Observation freshness still expires; stable direction grants no motion.
r.observe_view(request, pose(), 1.)
assert not r.view_current(near, 4.)