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,223 @@
|
||||
"""Offline, replaceable geometric route prior. Worker CPU only.
|
||||
|
||||
The envelope describes likely connected ground, not a pedestrian/legal map.
|
||||
Small enclosed occlusions are UNKNOWN, never asserted free. Their obstacle
|
||||
silhouettes do not sculpt the global route. Live perception remains mandatory.
|
||||
No prepared field, mesh or inferred height enters the local sensor pipeline.
|
||||
"""
|
||||
import json
|
||||
import hashlib
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "src"))
|
||||
|
||||
import numpy as np
|
||||
from scipy import ndimage
|
||||
from scipy.sparse import coo_matrix
|
||||
from scipy.sparse.csgraph import connected_components
|
||||
|
||||
from terrain import load_glb
|
||||
from k1link.simulation.ai_polygon.route_graph import build_route, PRIOR_MAP_SCHEMA
|
||||
from k1link.simulation.ai_polygon.route_preparation import SCHEMA, provider_identity
|
||||
from k1link.simulation.ai_polygon.run_inputs import digest, robot_geometry
|
||||
|
||||
CELL = .5
|
||||
STRIDE = 4 # 2 m graph; the runtime receives coalesced direction segments.
|
||||
MAX_CELLS = 2_000_000
|
||||
MAX_NODES = 16384
|
||||
|
||||
|
||||
def ground_envelope(vertices, faces, seed):
|
||||
triangles = vertices[faces]
|
||||
normal = np.cross(triangles[:,1]-triangles[:,0],triangles[:,2]-triangles[:,0])
|
||||
length = np.linalg.norm(normal,axis=1)
|
||||
flat = np.abs(normal[:,2]) >= np.maximum(1e-8,length)*math.cos(math.radians(25))
|
||||
samples = np.concatenate((triangles[flat].reshape(-1,3),triangles[flat].mean(axis=1)))
|
||||
if not len(samples):
|
||||
raise ValueError("No ground candidates in scene")
|
||||
origin = np.floor(vertices[:,:2].min(axis=0)/CELL)*CELL-CELL
|
||||
shape = np.ceil((vertices[:,:2].max(axis=0)-origin)/CELL).astype(int)+2
|
||||
if int(np.prod(shape)) > MAX_CELLS:
|
||||
raise ValueError("Scene exceeds route preparation cell budget")
|
||||
# Lower surface is a declared single-level approximation. Raised roofs are
|
||||
# disconnected by height, not identified as cars/buildings by their size.
|
||||
ij = np.floor((samples[:,:2]-origin)/CELL).astype(int)
|
||||
height = np.full(tuple(shape),np.inf)
|
||||
np.minimum.at(height,(ij[:,0],ij[:,1]),samples[:,2])
|
||||
valid = np.isfinite(height)
|
||||
seed_cell = np.floor((np.asarray(seed[:2])-origin)/CELL).astype(int)
|
||||
nearby = np.argwhere(valid & (np.abs(height-seed[2]) <= .6))
|
||||
if not len(nearby):
|
||||
raise ValueError("Start has no matching ground layer")
|
||||
nearest = nearby[np.argmin(np.linalg.norm(nearby-seed_cell,axis=1))]
|
||||
if np.linalg.norm(nearest-seed_cell)*CELL > 1:
|
||||
raise ValueError("Start outside mapped surface")
|
||||
# Height connectivity removes roofs and keeps the selected terrain layer.
|
||||
labels = np.full(height.shape,-1,dtype=np.int32)
|
||||
labels[valid] = np.arange(np.count_nonzero(valid))
|
||||
rows,cols = [],[]
|
||||
for axis in (0,1):
|
||||
a = (slice(None,-1),slice(None)) if axis==0 else (slice(None),slice(None,-1))
|
||||
b = (slice(1,None),slice(None)) if axis==0 else (slice(None),slice(1,None))
|
||||
with np.errstate(invalid='ignore'):
|
||||
adjacent = valid[a]&valid[b]&(np.abs(height[a]-height[b]) <= .1+CELL*math.tan(math.radians(25)))
|
||||
rows.extend(labels[a][adjacent]); cols.extend(labels[b][adjacent])
|
||||
matrix = coo_matrix((np.ones(len(rows),dtype=np.uint8),(rows,cols)),shape=(np.count_nonzero(valid),)*2).tocsr()
|
||||
_,components = connected_components(matrix,directed=False)
|
||||
ground = np.zeros(height.shape,dtype=bool)
|
||||
ground[valid] = components == components[labels[tuple(nearest)]]
|
||||
# Close only bounded, enclosed holes. No connection across open terrain,
|
||||
# a scene boundary, a long wall or an unobserved street is invented.
|
||||
holes = ndimage.binary_fill_holes(ground)&~ground
|
||||
regions,count = ndimage.label(holes)
|
||||
unknown = np.zeros(height.shape,dtype=bool)
|
||||
for index,sl in enumerate(ndimage.find_objects(regions),1):
|
||||
if sl is None:
|
||||
continue
|
||||
local = regions[sl]==index
|
||||
span = max(s.stop-s.start for s in sl)*CELL
|
||||
if span > 6 or np.count_nonzero(local)*CELL**2 > 24:
|
||||
continue
|
||||
region = regions==index
|
||||
rim = ndimage.binary_dilation(region)&ground
|
||||
heights = height[rim]
|
||||
if not len(heights) or np.ptp(heights) > .8:
|
||||
continue
|
||||
unknown |= region
|
||||
envelope = ground|unknown
|
||||
nearest_ground = ndimage.distance_transform_edt(~ground,return_distances=False,return_indices=True)
|
||||
height[unknown] = height[tuple(nearest_ground[:,unknown])]
|
||||
return origin,height,envelope,unknown
|
||||
|
||||
|
||||
def route_graph(origin, height, envelope, unknown, positions, source, world_sha256):
|
||||
clearance = ndimage.distance_transform_edt(envelope)*CELL
|
||||
ids = np.full(envelope.shape,-1,dtype=np.int32)
|
||||
cells = np.argwhere(envelope & (clearance >= .75))
|
||||
cells = cells[(cells[:,0]%STRIDE==0)&(cells[:,1]%STRIDE==0)]
|
||||
if not 1 <= len(cells) <= MAX_NODES-len(positions):
|
||||
raise ValueError("Route graph exceeds node budget or has no ground")
|
||||
nodes = []
|
||||
for i,(x,y) in enumerate(cells):
|
||||
ids[x,y] = i
|
||||
nodes.append(dict(id=str(i),xy=(origin+(np.array([x,y])+.5)*CELL).tolist(),z=float(height[x,y])))
|
||||
edges = []
|
||||
|
||||
def line(a,b):
|
||||
n=max(2,int(np.linalg.norm(b-a)*2)+1)
|
||||
ij=np.rint(np.linspace(a,b,n)).astype(int)
|
||||
if np.any(ij<0) or np.any(ij>=np.array(envelope.shape)):
|
||||
return None
|
||||
if not envelope[ij[:,0],ij[:,1]].all():
|
||||
return None
|
||||
# Keep boundaries expensive. The route follows broad ground structure,
|
||||
# with a bounded preference that cannot outweigh a long useful detour.
|
||||
width=float(np.min(clearance[ij[:,0],ij[:,1]]))
|
||||
z=height[ij[:,0],ij[:,1]]
|
||||
if np.any(np.abs(np.diff(z))>.5):
|
||||
return None
|
||||
return width
|
||||
|
||||
def connect(i,j,a,b):
|
||||
width=line(a,b)
|
||||
if width is None or width < .5:
|
||||
return
|
||||
endpoints=np.rint(np.array([a,b])).astype(int)
|
||||
actual_height=height[endpoints[:,0],endpoints[:,1]]
|
||||
if np.any(np.abs(actual_height-np.array([nodes[i]["z"],nodes[j]["z"]]))>.6):
|
||||
return
|
||||
length=math.dist(nodes[i]["xy"],nodes[j]["xy"])
|
||||
if length < .05:
|
||||
return
|
||||
edges.append(dict(id=str(len(edges)),start=str(i),end=str(j),half_width_m=min(20,width),
|
||||
bidirectional=True,cost_m=length*(1+2/max(.5,width))))
|
||||
|
||||
for i,a in enumerate(cells):
|
||||
for dx,dy in ((STRIDE,0),(0,STRIDE),(STRIDE,STRIDE),(STRIDE,-STRIDE)):
|
||||
b=a+[dx,dy]
|
||||
if np.any(b<0) or np.any(b>=np.array(envelope.shape)):
|
||||
continue
|
||||
j=int(ids[tuple(b)])
|
||||
if j>=0:
|
||||
connect(i,j,a,b)
|
||||
goals=[]
|
||||
for position in positions:
|
||||
cell=(np.asarray(position[:2])-origin)/CELL-.5
|
||||
index=len(nodes)
|
||||
nodes.append(dict(id=str(index),xy=position[:2],z=position[2]))
|
||||
distances=np.linalg.norm(cells-cell,axis=1)*CELL
|
||||
added=len(edges)
|
||||
for j in np.argsort(distances)[:12]:
|
||||
if distances[j]>3:
|
||||
break
|
||||
connect(index,int(j),cell,cells[j])
|
||||
if added==len(edges):
|
||||
raise ValueError("Endpoint is outside connected ground envelope")
|
||||
goals.append(str(index))
|
||||
if len(edges)>65536:
|
||||
raise ValueError("Route graph edge budget exceeded")
|
||||
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=source)
|
||||
graph["sha256"]=digest(graph)
|
||||
return dict(map=graph,start_node=goals[0],goal_nodes=goals[1:],blocked_edges=[])
|
||||
|
||||
|
||||
def prepare(request, collider, output, field_cache):
|
||||
identity=request["identity"]
|
||||
if identity["provider_sha256"] != provider_identity():
|
||||
raise ValueError("Installed route provider changed")
|
||||
world=request["world"]
|
||||
positions=[p["position"] for p in identity["points"]]
|
||||
# Terrain extraction is independent of A/B; selection of a height component
|
||||
# uses the declared start layer and is therefore explicitly cache-bound.
|
||||
field_identity=dict(world=world["sha256"],collider=identity["collider_sha256"],
|
||||
provider=identity["provider_sha256"],seed=positions[0],
|
||||
rotation=world["local_scene"]["collision_rotation"])
|
||||
cache=Path(field_cache)/(digest(field_identity)+'.npz')
|
||||
cache.parent.mkdir(parents=True,exist_ok=True)
|
||||
receipt=cache.with_suffix(".json")
|
||||
valid_cache=cache.exists() and receipt.exists()
|
||||
if valid_cache:
|
||||
with cache.open("rb") as stream:
|
||||
valid_cache=json.loads(receipt.read_text()).get("sha256")==hashlib.file_digest(stream,"sha256").hexdigest()
|
||||
if valid_cache:
|
||||
with np.load(cache,allow_pickle=False) as value:
|
||||
origin,height,envelope,unknown=(value[k] for k in ('origin','height','envelope','unknown'))
|
||||
else:
|
||||
vertices,faces=load_glb(collider,world["local_scene"]["collision_rotation"])
|
||||
origin,height,envelope,unknown=ground_envelope(vertices,faces,positions[0])
|
||||
np.savez_compressed(cache,origin=origin,height=height,envelope=envelope,unknown=unknown)
|
||||
with cache.open("rb") as stream:
|
||||
receipt.write_text(json.dumps({"sha256":hashlib.file_digest(stream,"sha256").hexdigest(),"identity":field_identity}))
|
||||
source={k:identity[k] for k in ('provider','provider_sha256','collider_sha256')}
|
||||
routing=route_graph(origin,height,envelope,unknown,positions,source,world['sha256'])
|
||||
inputs=dict(routing=routing,mission={"route_xy":[p[:2] for p in positions[1:]]},
|
||||
robot={"geometry":robot_geometry(request['robot'])},sha256=request['key'])
|
||||
route=build_route(inputs)
|
||||
if any(leg['status']!='ready' for leg in route['legs']):
|
||||
raise ValueError("No complete route between all task points")
|
||||
node_z={tuple(n['xy']):n['z'] for n in routing['map']['nodes']}
|
||||
preview=[positions[0]]
|
||||
for leg in route['legs']:
|
||||
for segment in leg['segments']:
|
||||
xy=segment['end_xy']; preview.append([*xy,node_z[tuple(xy)]])
|
||||
result=dict(schema_version=SCHEMA,identity=identity,routing=routing,preview_xyz=preview,
|
||||
length_m=sum(leg['length_m'] for leg in route['legs']),
|
||||
evidence=dict(field_sha256=digest(field_identity),cell_m=CELL,
|
||||
mapped_cells=int(envelope.sum()),uncertain_cells=int(unknown.sum()),
|
||||
authority='route-intent-only',
|
||||
limitations=['geometric-prior-not-pedestrian-map','single-ground-layer',
|
||||
'small-enclosed-occlusions-unknown','live-sensors-required']))
|
||||
result['sha256']=digest(result)
|
||||
Path(output).write_text(json.dumps(result,allow_nan=False,separators=(",",":")),encoding='utf-8')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
import argparse
|
||||
parser=argparse.ArgumentParser()
|
||||
for name in ('request','collider','output','field-cache'):
|
||||
parser.add_argument('--'+name,required=True)
|
||||
args=parser.parse_args()
|
||||
prepare(json.loads(Path(args.request).read_text(encoding='utf-8')),args.collider,args.output,args.field_cache)
|
||||
Reference in New Issue
Block a user