Add prepared urban route guidance to Gaussian simulation planning
Introduce a content-bound scene route provider, advisory runtime graph and plan-preview-launch workflow. Preserve live sensing authority and retire blocked intermediate goals without discarding final-arrival evidence. Bound native visual context losslessly and provide verified cache relocation. Full Maroseyka route qualification remains open.
This commit is contained in:
@@ -0,0 +1,180 @@
|
||||
"""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
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Small synthetic geometry: no scene names, memorized turns or manual paths."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
pytest.importorskip('scipy')
|
||||
ADAPTER=Path(__file__).parents[1]/'simulation/ai-polygon'
|
||||
sys.path.insert(0,str(ADAPTER))
|
||||
from scene_route_field import ground_envelope, route_graph
|
||||
from k1link.simulation.ai_polygon.route_graph import build_route
|
||||
|
||||
|
||||
def street(*,car=False,gap=False):
|
||||
x,y=np.meshgrid(np.arange(0,24.01,.25),np.arange(-4,4.01,.25),indexing='ij')
|
||||
vertices=np.column_stack([x.ravel(),y.ravel(),np.zeros(x.size)])
|
||||
n=y.shape[1]
|
||||
faces=[]
|
||||
for i in range(x.shape[0]-1):
|
||||
for j in range(n-1):
|
||||
a=i*n+j;b=a+n
|
||||
if (car and 9<=x[i,j]<13 and -1<=y[i,j]<1) or (gap and 9<=x[i,j]<13):
|
||||
continue
|
||||
faces.extend([[a,b,a+1],[a+1,b,b+1]])
|
||||
if car:
|
||||
roof=vertices.copy();roof[:,2]=1.5
|
||||
rows=np.argwhere((x>=9)&(x<13)&(y>=-1)&(y<1))
|
||||
roof_faces=[]
|
||||
for i,j in rows:
|
||||
a=i*n+j;b=a+n
|
||||
roof_faces.extend([[a,b,a+1],[a+1,b,b+1]])
|
||||
faces+= (np.asarray(roof_faces)+len(vertices)).tolist()
|
||||
vertices=np.concatenate([vertices,roof])
|
||||
return vertices,np.array(faces)
|
||||
|
||||
|
||||
def test_small_enclosed_occlusion_does_not_sculpt_global_directions():
|
||||
base=ground_envelope(*street(),[1,0,0])
|
||||
occupied=ground_envelope(*street(car=True),[1,0,0])
|
||||
assert np.array_equal(base[2],occupied[2])
|
||||
assert not base[3].any() and occupied[3].any()
|
||||
source=dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64)
|
||||
positions=[[1.,0.,0.],[22.,0.,0.]]
|
||||
def route(field):
|
||||
graph=route_graph(*field,positions,source,'c'*64)
|
||||
return build_route(dict(routing=graph,mission={'route_xy':[[22.,0.]]},robot={'geometry':{'length_m':1.,'width_m':1.}},sha256='d'*64))['legs']
|
||||
assert route(base)==route(occupied)
|
||||
|
||||
|
||||
def test_open_gap_is_not_filled_to_make_a_successful_route():
|
||||
field=ground_envelope(*street(gap=True),[1,0,0])
|
||||
origin,height,envelope,unknown=field
|
||||
far=np.floor((np.array([20,0])-origin)/.5).astype(int)
|
||||
assert not envelope[tuple(far)] and not unknown[tuple(far)]
|
||||
with pytest.raises(ValueError,match='Endpoint'):
|
||||
route_graph(*field,[[1.,0.,0.],[22.,0.,0.]],
|
||||
dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64),'c'*64)
|
||||
|
||||
|
||||
def test_goal_on_another_height_layer_does_not_attach_to_street():
|
||||
field=ground_envelope(*street(),[1,0,0])
|
||||
with pytest.raises(ValueError,match='Endpoint'):
|
||||
route_graph(*field,[[1.,0.,0.],[22.,0.,2.]],
|
||||
dict(provider='synthetic',provider_sha256='a'*64,collider_sha256='b'*64),'c'*64)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Disk exhaustion must fail before conversion, not corrupt a published cache."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
path=Path(__file__).parents[1]/'simulation/ai-polygon/gaussian_cache.py'
|
||||
spec=importlib.util.spec_from_file_location('storage_under_test',path)
|
||||
cache=importlib.util.module_from_spec(spec);spec.loader.exec_module(cache)
|
||||
|
||||
|
||||
def test_disk_budget_precedes_conversion_and_verified_reuse(tmp_path,monkeypatch):
|
||||
source=tmp_path/'scene.ply';source.write_bytes(b'source')
|
||||
recipe=dict(reader='reader',writer='writer',runtime='runtime',output_schema='schema')
|
||||
calls=[]
|
||||
def convert(source,output):
|
||||
calls.append(source);output.write_bytes(b'verified-usd')
|
||||
monkeypatch.setattr(cache.shutil,'disk_usage',lambda _:SimpleNamespace(free=0))
|
||||
with pytest.raises(RuntimeError,match='Недостаточно места'):
|
||||
cache.prepare_gaussian(source,convert,recipe)
|
||||
assert not calls and not list(tmp_path.rglob('receipt.json'))
|
||||
monkeypatch.setattr(cache.shutil,'disk_usage',lambda _:SimpleNamespace(free=10*1024**3))
|
||||
path,receipt=cache.prepare_gaussian(source,convert,recipe)
|
||||
monkeypatch.setattr(cache.shutil,'disk_usage',lambda _:SimpleNamespace(free=0))
|
||||
assert cache.prepare_gaussian(source,convert,recipe)==(path,receipt)
|
||||
assert len(calls)==1 and path.read_bytes()==b'verified-usd'
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Curved visual context must retain whole original Gaussian records."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
|
||||
path=Path(__file__).parents[1]/'simulation/ai-polygon/route_region.py'
|
||||
spec=importlib.util.spec_from_file_location('region_under_test',path)
|
||||
region=importlib.util.module_from_spec(spec);spec.loader.exec_module(region)
|
||||
|
||||
|
||||
def test_curved_region_preserves_context_and_every_attribute(tmp_path):
|
||||
points=np.array([[0,7,0,10,20],[10,8,1.99,11,21],[20,9,10,12,22],
|
||||
[0,10,20,13,23],[10,11,10,14,24]],dtype='<f4')
|
||||
header=('ply\nformat binary_little_endian 1.0\nelement vertex 5\n'
|
||||
'property float x\nproperty float y\nproperty float z\n'
|
||||
'property float f_rest_0\nproperty float opacity\nend_header\n').encode()
|
||||
source=tmp_path/'in.ply';source.write_bytes(header+points.tobytes());output=tmp_path/'out.ply'
|
||||
receipt=region.select_region(source,output,[[0,0],[20,0],[20,20]],radius=2,chunk=2)
|
||||
raw=output.read_bytes();end=raw.index(b'end_header\n')+len(b'end_header\n')
|
||||
assert raw[end:]==points[:3].tobytes()
|
||||
assert b'element vertex 00000000000000000003\n' in raw[:end]
|
||||
assert receipt['retained_count']==3 and receipt['source_count']==5
|
||||
assert receipt['all_attributes_preserved'] and not receipt['decimated']
|
||||
assert source.read_bytes()==header+points.tobytes()
|
||||
Reference in New Issue
Block a user