227 lines
12 KiB
Python
227 lines
12 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
|