442 lines
23 KiB
Python
442 lines
23 KiB
Python
"""A route prior cannot become a rail, motion evidence, or a stale task."""
|
|
import copy
|
|
import math
|
|
|
|
import numpy as np
|
|
import pytest
|
|
|
|
from k1link.simulation.ai_polygon.route_graph import (
|
|
PRIOR_MAP_SCHEMA, build_route, disc_permitted, discs_permitted, validate_routing,
|
|
)
|
|
from k1link.simulation.ai_polygon.route_preparation import (
|
|
RoutePreparationStore, preparation_identity, validate_prepared, SCHEMA,
|
|
)
|
|
from k1link.simulation.ai_polygon.run_inputs import digest
|
|
from k1link.simulation.ai_polygon.robots import select_robot
|
|
|
|
|
|
def fixture():
|
|
points=[dict(id='a'*16,position=[0.,0.,0.]),dict(id='b'*16,position=[12.,0.,0.])]
|
|
world=dict(sha256='a'*64,world_id='aiworld-'+'a'*32,collider_sha256='b'*64,
|
|
settings={'prepared':True},local_scene={'collision_rotation':[0,0,0]})
|
|
robot=select_robot('dcd006-v020')
|
|
identity=preparation_identity(world,robot,points)
|
|
nodes=[dict(id=str(i),xy=p,z=0.) for i,p in enumerate([[0.,0.],[4.,0.],[8.,0.],[12.,0.],[0.,5.],[12.,5.]])]
|
|
edges=[]
|
|
for a,b in [(0,1),(1,2),(2,3),(0,4),(4,5),(5,3)]:
|
|
edges.append(dict(id=str(len(edges)),start=str(a),end=str(b),half_width_m=1.,bidirectional=True,
|
|
cost_m=math.dist(nodes[a]['xy'],nodes[b]['xy'])))
|
|
graph=dict(schema_version=PRIOR_MAP_SCHEMA,frame='world-xy-metres',world_sha256=world['sha256'],
|
|
nodes=nodes,edges=edges,no_go=[],corridor_policy='advisory',
|
|
source={k:identity[k] for k in ('provider','provider_sha256','collider_sha256')})
|
|
graph['sha256']=digest(graph)
|
|
routing=dict(map=graph,start_node='0',goal_nodes=['3'],blocked_edges=[])
|
|
inputs=dict(routing=routing,robot={'geometry':{'length_m':1.,'width_m':1.}},mission={'route_xy':[[12.,0.]]},sha256='c'*64)
|
|
result=dict(schema_version=SCHEMA,identity=identity,routing=routing,preview_xyz=[p['position'] for p in points],length_m=12.)
|
|
result['sha256']=digest(result)
|
|
return world,robot,points,inputs,result
|
|
|
|
|
|
def test_prior_is_not_a_rail_and_does_not_erase_no_go():
|
|
*_,inputs,_=fixture()
|
|
route=build_route(inputs)
|
|
segments=route['legs'][0]['segments']
|
|
assert len(segments)==1 and segments[0]['edge_ids']==['0','1','2']
|
|
assert route['authority']=='route-intent-only'
|
|
assert disc_permitted([5,4],.8,segments,[]) # freely measured local detour
|
|
assert discs_permitted([[5,4],[6,6]],.8,segments,[]).all()
|
|
no_go=[dict(lower_xy=[4.,3.],upper_xy=[6.,5.])]
|
|
assert not disc_permitted([5,4],.8,segments,no_go)
|
|
assert discs_permitted([[5,4],[7,7]],.8,segments,no_go).tolist()==[False,True]
|
|
hard=[{k:v for k,v in s.items() if k not in ('guidance_only','edge_ids')} for s in segments]
|
|
assert not disc_permitted([5,4],.8,hard,[])
|
|
|
|
|
|
def test_observed_exclusion_can_use_an_alternate_branch():
|
|
*_,inputs,_=fixture()
|
|
route=build_route(inputs,unavailable_edges=['0','1','2'])
|
|
assert route['legs'][0]['status']=='ready'
|
|
assert route['legs'][0]['length_m']==22.
|
|
assert [s['end_xy'] for s in route['legs'][0]['segments']]==[[0.,5.],[12.,5.],[12.,0.]]
|
|
|
|
|
|
def test_prior_world_and_map_identities_are_not_interchangeable():
|
|
*_,inputs,_=fixture()
|
|
with pytest.raises(ValueError,match='identity'):
|
|
validate_routing(inputs['routing'],'d'*64,[[12.,0.]])
|
|
inputs['routing']['map']['edges'][0]['cost_m']=0.
|
|
with pytest.raises(ValueError):
|
|
validate_routing(inputs['routing'],'a'*64,[[12.,0.]])
|
|
|
|
|
|
def test_preparation_owner_retry_and_stale_draft(tmp_path):
|
|
world,robot,points,_,result=fixture()
|
|
store=RoutePreparationStore(tmp_path)
|
|
row=store.request(world,robot,points)
|
|
assert store.request(world,robot,points)==row
|
|
store.claim(row['key'],'worker')
|
|
with pytest.raises(RuntimeError,match='owner'):
|
|
store.update(row['key'],{'action':'complete','result':result},'other')
|
|
finished=store.update(row['key'],{'action':'complete','result':result},'worker')
|
|
assert finished['status']=='ready' and store.pending() is None
|
|
assert store.for_plan(row['key'],world,robot,points)==result
|
|
changed=copy.deepcopy(points);changed[-1]['position'][0]+=.1
|
|
with pytest.raises(ValueError,match='соответствует'):
|
|
store.for_plan(row['key'],world,robot,changed)
|
|
assert store.update(row['key'],{'action':'release'},'worker')['status']=='ready'
|
|
|
|
|
|
def test_interrupted_preparation_cannot_launch(tmp_path):
|
|
world,robot,points,*_=fixture()
|
|
store=RoutePreparationStore(tmp_path)
|
|
row=store.request(world,robot,points);store.claim(row['key'],'worker')
|
|
store.update(row['key'],{'action':'release'},'worker')
|
|
with pytest.raises(ValueError,match='спланируйте'):
|
|
store.for_plan(row['key'],world,robot,points)
|
|
assert store.request(world,robot,points)['status']=='queued'
|
|
|
|
|
|
def test_http_save_preserves_json_points_in_prepared_route(tmp_path, monkeypatch):
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
from k1link.web.ai_polygon_api import build_ai_polygon_router
|
|
from k1link.simulation.ai_polygon.worlds import WorldStore
|
|
from k1link.simulation.ai_polygon.editor_cache import EditorCache
|
|
world,robot,points,_,result=fixture()
|
|
cache={'world':world,'status':'ready','identity':'test',
|
|
'files':{'collision.glb':{'sha256':'b'*64}}}
|
|
monkeypatch.setattr(WorldStore,'get',lambda self,key:world)
|
|
monkeypatch.setattr(EditorCache,'get',lambda self,key:cache)
|
|
monkeypatch.setattr(EditorCache,'identity',lambda self,value:'test')
|
|
store=RoutePreparationStore(tmp_path)
|
|
row=store.request(world,robot,points);store.claim(row['key'],'worker')
|
|
store.update(row['key'],{'action':'complete','result':result},'worker')
|
|
app=FastAPI();app.include_router(build_ai_polygon_router(tmp_path))
|
|
body=dict(cache_key='a'*64,robot_id=robot['robot_id'],robot_sha256=robot['sha256'],
|
|
draft_id='d'*32,sequence=1,name='Prepared route',points=points,
|
|
route_preparation_key=row['key'])
|
|
with TestClient(app) as client:
|
|
response=client.post('/api/v1/ai-polygon/plans',json=body)
|
|
assert response.status_code==201,response.text
|
|
saved=response.json()
|
|
assert saved['prepared_route']['sha256']==result['sha256']
|
|
assert client.post('/api/v1/ai-polygon/plans',json=body).json()['plan_id']==saved['plan_id']
|
|
body['points'][1]['position'][0]=11.
|
|
assert client.post('/api/v1/ai-polygon/plans',json=body).status_code==400
|
|
|
|
|
|
def test_advisory_joint_requires_actual_progress_and_current_support():
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_,inputs,_=fixture()
|
|
inputs['routing']['blocked_edges']=['0','1','2']
|
|
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps':1.})
|
|
mission=RoutedMission(inputs)
|
|
def sample(x,y,t,supported=True):
|
|
pose=[x,y,0.,0.,0.,0.,1.]
|
|
mission.route_observation(pose,t)
|
|
mission.last_time,mission.last_pose=t,tuple(pose)
|
|
body=dict(observation=dict(pose=pose,target_xy=mission.arrival_target(),
|
|
simulation_time_seconds=t,execution_inputs_sha256=inputs['sha256']),
|
|
admitted=supported,collision_free=True,support_known=True,
|
|
positive_surface_required=True,support_samples=4,supported_samples=4)
|
|
return mission.confirm_corridor_transition(pose,t,body)
|
|
assert sample(0.,0.,0.) is None # soft corridor is not permission to skip all joints
|
|
assert sample(0.,4.,4.,False) is None
|
|
assert sample(0.,4.,5.) is not None
|
|
assert mission.segment_index==1 and mission.index==0
|
|
assert sample(0.,4.,6.) is None
|
|
|
|
|
|
def test_native_abort_retires_soft_joint_goal_but_keeps_final_and_return_anchor():
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_, inputs, _ = fixture()
|
|
inputs["routing"]["blocked_edges"] = ["0", "1", "2"]
|
|
inputs.update(sensors={"schema_version": "missioncore.simulation-sensor-rig/v4"},
|
|
behavior={"max_speed_mps": 1.})
|
|
mission = RoutedMission(inputs)
|
|
pose = [0., 0., 0., 0., 0., 0., 1.]
|
|
mission.route_observation(pose, 0.)
|
|
mission.last_time, mission.last_pose = 0., tuple(pose)
|
|
goal = [0., 4.9, 0.]
|
|
mission.goal = goal
|
|
aborted = dict(status="blocked", speed_mps=0., yaw_rate_rps=0.,
|
|
route_observation={"observation": dict(pose=pose, simulation_time_seconds=0.,
|
|
execution_inputs_sha256=inputs["sha256"])},
|
|
planning_result=dict(status="aborted", goal_xy=goal[:2]))
|
|
mission.reject_local_plan(aborted, pose, 0., inputs["sha256"])
|
|
assert mission.goal is None and mission.failed_goals == [goal]
|
|
assert mission.segment_index == 0 and mission.index == 0
|
|
# Returning from a closed edge and the operator's final goal remain visits.
|
|
mission.leg["segments"][0]["return_to_anchor"] = True
|
|
mission.goal = goal
|
|
mission.retire_local_goal(None, failed=True)
|
|
assert mission.goal == goal
|
|
mission.segment_index = len(mission.leg["segments"]) - 1
|
|
mission.route_observation(pose, 1.)
|
|
final = [*mission.route_target, 0.]
|
|
mission.goal = final
|
|
mission.retire_local_goal(None, failed=True)
|
|
assert mission.goal == final
|
|
|
|
|
|
@pytest.mark.parametrize("condition", ["supported", "unknown", "stale", "remote",
|
|
"early", "no-go", "hard", "return", "reverse"])
|
|
def test_observed_detour_can_pass_advisory_joint_without_returning_to_line(condition):
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_, inputs, _ = fixture()
|
|
inputs["routing"]["blocked_edges"] = ["0", "1", "2"]
|
|
inputs.update(sensors={"schema_version": "missioncore.simulation-sensor-rig/v4"},
|
|
behavior={"max_speed_mps": 1.})
|
|
mission = RoutedMission(inputs)
|
|
mission.route_observation([0., 0., 0., 0., 0., 0., 1.], 0.)
|
|
# A wide observed passage, offset from the prior, near the next joint.
|
|
# No scene coordinates or obstacle labels supply movement permission.
|
|
pose = [2.8, 4.5, 0., 0., 0., 0., 1.]
|
|
if condition == "remote":
|
|
pose[0] = 4.
|
|
if condition == "early":
|
|
pose[1] = 3.
|
|
mission.route_observation(pose, 10.)
|
|
mission.last_time, mission.last_pose = 10., tuple(pose)
|
|
body = dict(observation=dict(pose=pose, target_xy=mission.arrival_target(),
|
|
simulation_time_seconds=10., execution_inputs_sha256=inputs["sha256"]),
|
|
admitted=True, collision_free=True, support_known=True,
|
|
positive_surface_required=True, support_samples=4, supported_samples=4)
|
|
if condition == "unknown":
|
|
body.update(admitted=False, support_known=False, supported_samples=0)
|
|
if condition == "stale":
|
|
body["observation"]["simulation_time_seconds"] = 9.
|
|
if condition == "no-go":
|
|
mission.global_route["no_go"] = [dict(lower_xy=[2., 4.], upper_xy=[3., 5.])]
|
|
if condition == "hard":
|
|
for segment in mission.leg["segments"]:
|
|
segment.pop("guidance_only", None)
|
|
if condition == "return":
|
|
mission.leg["segments"][0]["return_to_anchor"] = True
|
|
if condition == "reverse":
|
|
mission.leg["segments"][1]["end_xy"] = [0., 0.]
|
|
result = mission.confirm_corridor_transition(pose, 10., body)
|
|
assert (result is not None) is (condition == "supported")
|
|
assert mission.segment_index == (1 if condition == "supported" else 0)
|
|
assert mission.index == 0 # a corridor transition never completes a task goal
|
|
if result:
|
|
assert result["authority"] == "adjacent-route-intent-only; not-mission-arrival"
|
|
assert result["body"] == body
|
|
assert mission.confirm_corridor_transition(pose, 10., body) is None
|
|
|
|
|
|
@pytest.mark.parametrize('angle', [0., .9, -2.1])
|
|
@pytest.mark.parametrize('offset', [-8., 8.])
|
|
@pytest.mark.parametrize('condition', ['passed', 'early', 'unknown', 'stale',
|
|
'forbidden', 'return', 'reverse', 'recovering'])
|
|
def test_passed_advisory_joint_uses_progress_and_current_body_not_lateral_distance(
|
|
angle, offset, condition):
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_, inputs, _ = fixture()
|
|
inputs['routing']['blocked_edges'] = ['0', '1', '2']
|
|
rotation = np.array([[math.cos(angle), -math.sin(angle)],
|
|
[math.sin(angle), math.cos(angle)]])
|
|
origin = np.array([37., -23.])
|
|
def world(xy):
|
|
return (rotation @ xy + origin).tolist()
|
|
for node in inputs['routing']['map']['nodes']:
|
|
node['xy'] = world(node['xy'])
|
|
graph = inputs['routing']['map']
|
|
graph['sha256'] = digest({k: v for k, v in graph.items() if k != 'sha256'})
|
|
inputs.update(sensors={'schema_version': 'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps': 1.})
|
|
inputs['mission']['route_xy'] = [world([12., 0.])]
|
|
mission = RoutedMission(inputs)
|
|
mission.route_observation([*world([0., 0.]), 0., 0., 0., 0., 1.], 0.)
|
|
pose = [*world([offset, 4.5 if condition == 'early' else 5.5]), 0., 0., 0., 0., 1.]
|
|
mission.route_observation(pose, 10.)
|
|
mission.last_time, mission.last_pose = 10., tuple(pose)
|
|
body = dict(observation=dict(pose=pose, target_xy=mission.arrival_target(),
|
|
simulation_time_seconds=10., execution_inputs_sha256=inputs['sha256']),
|
|
admitted=True, collision_free=True, support_known=True,
|
|
positive_surface_required=True, support_samples=4, supported_samples=4)
|
|
if condition == 'unknown':
|
|
body.update(admitted=False, support_known=False, supported_samples=0)
|
|
if condition == 'stale':
|
|
body['observation']['simulation_time_seconds'] = 9.
|
|
if condition == 'forbidden':
|
|
mission.global_route['no_go'] = [dict(lower_xy=(np.array(pose[:2])-.2).tolist(),
|
|
upper_xy=(np.array(pose[:2])+.2).tolist())]
|
|
if condition == 'return':
|
|
mission.leg['segments'][0]['return_to_anchor'] = True
|
|
if condition == 'reverse':
|
|
mission.leg['segments'][1]['end_xy'] = world([0., 0.])
|
|
if condition == 'recovering':
|
|
mission.recovery_goal = [*world([offset, 4.]), 0.]
|
|
assert not mission.can_query_arrival(pose) or condition == 'return'
|
|
result = mission.confirm_corridor_transition(pose, 10., body)
|
|
assert (result is not None) is (condition == 'passed')
|
|
assert mission.segment_index == (1 if condition == 'passed' else 0)
|
|
assert mission.index == 0
|
|
if result:
|
|
assert mission.confirm_corridor_transition(pose, 10., body) is None
|
|
# The new intent runs along the next edge from the actual position;
|
|
# it neither turns back to the old hint nor completes the task goal.
|
|
np.testing.assert_allclose(np.array(mission.route_target)-pose[:2], rotation @ [6., 0.])
|
|
|
|
|
|
@pytest.mark.parametrize('direction', ['forward', 'reverse', 'at-node'])
|
|
def test_local_blockage_keeps_original_graph_edge_and_nearby_return_node(direction):
|
|
from k1link.simulation.ai_polygon.route_feedback import blocked_route_piece
|
|
*_, inputs, _ = fixture()
|
|
if direction == 'reverse':
|
|
inputs['routing'].update(start_node='3', goal_nodes=['0'])
|
|
inputs['mission']['route_xy'] = [[0., 0.]]
|
|
segment = build_route(inputs)['legs'][0]['segments'][0]
|
|
pose = [2.8, .2] if direction == 'reverse' else ([8., 0.] if direction == 'at-node' else [9.2, .2])
|
|
hazard = [1.8, .1, 0.] if direction == 'reverse' else [10.2, .1, 0.]
|
|
edge, anchor, closed = blocked_route_piece(inputs['routing'], segment, [hazard], pose)
|
|
assert (edge['id'], anchor, closed) == (('0', '1', ['0']) if direction == 'reverse' else ('2', '2', ['2']))
|
|
|
|
|
|
def test_compressed_advisory_reroute_uses_nearby_branch_without_closing_the_passed_chain(monkeypatch):
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_, inputs, _ = fixture()
|
|
graph = inputs['routing']['map']
|
|
graph['nodes'].append(dict(id='6', xy=[8., 5.], z=0.))
|
|
graph['edges'].extend([
|
|
dict(id='6', start='2', end='6', half_width_m=1., bidirectional=True, cost_m=5.),
|
|
dict(id='7', start='6', end='5', half_width_m=1., bidirectional=True, cost_m=4.)])
|
|
graph['sha256'] = digest({k:v for k,v in graph.items() if k!='sha256'})
|
|
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps':1.})
|
|
mission = RoutedMission(inputs)
|
|
mission.route_observation([0.,0.,0.,0.,0.,0.,1.],0.)
|
|
pose = [9.2,.2,0.,0.,0.,0.,1.]
|
|
mission.route_observation(pose,10.)
|
|
mission.last_time, mission.last_pose = 10., tuple(pose)
|
|
receipt = dict(hazards_xyz=[[10.2,.1,0.],[10.2,.2,0.],[10.2,.3,0.]])
|
|
monkeypatch.setattr(mission.blockage, 'observe', lambda *args: receipt)
|
|
original = copy.deepcopy(mission.global_route)
|
|
event = mission.observe_navigation({},np.empty((0,3)),pose,10.)
|
|
assert event['status'] == 'ready' and event['anchor_node'] == '2'
|
|
assert mission.unavailable_edges == {'2'}
|
|
segments = mission.leg['segments']
|
|
assert segments[0]['start_xy'] == pose[:2]
|
|
assert segments[0]['end_xy'] == [8.,0.] and segments[0]['edge_ids'] == ['2']
|
|
assert segments[0]['return_to_anchor'] is True
|
|
assert segments[1]['end_xy'] == [8.,5.]
|
|
assert math.dist(pose[:2], mission.arrival_target()) < 1.3
|
|
assert mission.global_route == original # Preparation remains immutable.
|
|
assert mission.index == 0 and mission.segment_index == 0
|
|
assert not mission.confirm_arrival(pose,10.,0,admitted=False)
|
|
|
|
|
|
def test_component_chain_cannot_reverse_a_one_way_edge():
|
|
from k1link.simulation.ai_polygon.route_feedback import blocked_route_piece
|
|
*_, inputs, _ = fixture()
|
|
segment = build_route(inputs)['legs'][0]['segments'][0]
|
|
inputs['routing']['map']['edges'][1]['bidirectional'] = False
|
|
broken = {**segment,'start_xy':segment['end_xy'],'end_xy':segment['start_xy'],
|
|
'edge_ids':list(reversed(segment['edge_ids']))}
|
|
with pytest.raises(ValueError,match='oriented graph chain'):
|
|
blocked_route_piece(inputs['routing'],broken,[[1.,0.,0.]],[3.,0.])
|
|
|
|
|
|
def test_advisory_joint_preserves_local_passage_intent_for_revalidation():
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_,inputs,_=fixture()
|
|
inputs['routing']['blocked_edges']=['0','1','2']
|
|
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps':1.})
|
|
mission=RoutedMission(inputs)
|
|
mission.route_observation([0,0,0,0,0,0,1],0.)
|
|
mission.goal=[.5,4.8,0.]
|
|
before=list(mission.goal)
|
|
mission.advance_segment([0.,4.,0.,0.,0.,0.,1.],5.)
|
|
assert mission.segment_index==1
|
|
assert mission.goal==before
|
|
# It remains an intent. The subsequent selector can revoke it immediately.
|
|
chosen=[]
|
|
def reject(target,prior,excluded):
|
|
chosen.append(prior)
|
|
return None
|
|
goal,intent=mission.update([0.,4.,0.,0.,0.,0.,1.],5.1,reject)
|
|
assert before in chosen
|
|
assert goal is None and intent['state']=='no-road'
|
|
|
|
|
|
def test_advisory_joint_is_never_an_exact_arrival_destination():
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_,inputs,_=fixture()
|
|
inputs['routing']['blocked_edges']=['0','1','2']
|
|
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps':1.})
|
|
mission=RoutedMission(inputs)
|
|
pose=[0.,0.,0.,0.,0.,0.,1.]
|
|
mission.route_observation(pose,0.)
|
|
assert not mission.can_query_arrival(pose)
|
|
# A declared final destination still requires exact whole-body arrival.
|
|
mission.segment_index=len(mission.leg['segments'])-1
|
|
mission.route_observation(pose,0.)
|
|
assert mission.can_query_arrival(pose)
|
|
|
|
|
|
@pytest.mark.parametrize("offset", [-3.,0.,3.])
|
|
def test_advisory_joint_is_a_direction_not_lateral_attraction(offset):
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_,inputs,_=fixture()
|
|
inputs['routing']['blocked_edges']=['0','1','2']
|
|
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps':1.})
|
|
mission=RoutedMission(inputs)
|
|
mission.route_observation([0.,0.,0.,0.,0.,0.,1.],0.)
|
|
# The actual open passage can pass a map joint on either side. Neither
|
|
# the goal selector nor the stopped view acquisition should face the joint.
|
|
for t,y in enumerate([2.,4.,5.,6.],start=10):
|
|
pose=[offset,y,0.,0.,0.,0.,1.]
|
|
mission.route_observation(pose,float(t*4))
|
|
direction=np.array(mission.route_target)-pose[:2]
|
|
assert direction[0] == pytest.approx(0.) and direction[1] > 3.5
|
|
assert mission.orientation_target()['xy'] == mission.route_target
|
|
assert mission.arrival_target() == [0.,5.]
|
|
assert mission.segment_index == 0 # direction is not a transition receipt
|
|
assert not mission.can_query_arrival(pose)
|
|
# A required return anchor and final mission destination retain exact XY.
|
|
mission.leg['segments'][0]['return_to_anchor']=True
|
|
mission.route_observation(pose,60.)
|
|
assert mission.route_target == [0.,5.]
|
|
mission.segment_index=len(mission.leg['segments'])-1
|
|
mission.route_observation(pose,61.)
|
|
assert mission.route_target == mission.leg['goal_xy']
|
|
|
|
|
|
@pytest.mark.parametrize("angle,offset", [(0., 3.), (.7, -3.), (-1.2, 3.)])
|
|
def test_progress_past_advisory_joint_uses_observed_continuation(angle, offset):
|
|
from k1link.simulation.ai_polygon.route_mission import RoutedMission
|
|
*_, inputs, _ = fixture()
|
|
axes = np.array([[math.cos(angle), -math.sin(angle)],
|
|
[math.sin(angle), math.cos(angle)]])
|
|
for node in inputs['routing']['map']['nodes']:
|
|
node['xy'] = (axes @ node['xy']).tolist()
|
|
graph = inputs['routing']['map']
|
|
graph['sha256'] = digest({k: v for k, v in graph.items() if k != 'sha256'})
|
|
inputs['mission']['route_xy'] = [(axes @ [12., 0.]).tolist()]
|
|
inputs['routing']['blocked_edges'] = ['0', '1', '2']
|
|
inputs.update(sensors={'schema_version': 'missioncore.simulation-sensor-rig/v4'},
|
|
behavior={'max_speed_mps': 1.})
|
|
mission = RoutedMission(inputs)
|
|
def step(x, y, seconds):
|
|
xy = axes @ [x, y]
|
|
yaw = angle + math.pi/2
|
|
pose = [*xy, 0., 0., 0., math.sin(yaw/2), math.cos(yaw/2)]
|
|
# Measured local goals continue along the actual passage beside the
|
|
# approximate joint. Changing a goal alone must earn no progress.
|
|
return mission.update(pose, seconds, lambda *_: [*(axes @ [x, y+3]), 0.])
|
|
step(0., 0., 0.)
|
|
for i, y in enumerate(np.arange(3., 15.5, .5)):
|
|
step(offset, y, 5.+i*2)
|
|
assert mission.attempts == 0 and mission.fault is None
|
|
assert mission.segment_index == 0 and mission.index == 0
|
|
# This is watchdog progress only; no route joint or arrival is admitted.
|
|
# Back/forth motion and refreshed goals cannot replenish the watchdog.
|
|
for i in range(6):
|
|
step(offset, 14.8 if i % 2 == 0 else 15., 55.+i*2)
|
|
assert mission.attempts >= 1
|