Choose local passage centres before route guidance

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 23:40:19 +03:00
parent e61aa6da5f
commit 8bd2a9967a
6 changed files with 187 additions and 53 deletions
@@ -12,6 +12,7 @@ import numpy as np
from scipy.spatial import cKDTree
from .semantic_surface import SemanticSurface
from .observed_passages import passage_centres
class ObservedGoals:
@@ -316,8 +317,6 @@ class ObservedGoals:
remaining = float(np.linalg.norm(direction))
if remaining <= 0.4:
return None # Exact arrival remains the native whole-body receipt.
forward = direction / remaining
lateral = np.array([-forward[1], forward[0]])
delta = points[:, :2] - pose[:2]
distance = np.linalg.norm(delta, axis=1)
progress = np.linalg.norm(points[:, :2] - target, axis=1)
@@ -330,30 +329,39 @@ class ObservedGoals:
good &= candidate_mask(points)
for failed in excluded:
good &= np.linalg.norm(points[:, :2] - np.asarray(failed[:2]), axis=1) > 0.6
candidates = points[good]
if len(candidates) < 8:
if not np.any(good):
return None
allowed = {
key: stamp for key, (permission, stamp) in self.surface.cells.items()
if permission == 1 and self.surface.retained(key, stamp, now)
}
candidates = candidates[[tuple(key) in allowed
for key in self.surface.cell_keys(candidates)]]
if not len(candidates):
permitted = points[[tuple(key) in allowed for key in self.surface.cell_keys(points)]]
local = np.linalg.norm(permitted[:, :2]-pose[:2], axis=1)
permitted = permitted[(local <= 6.) & (np.abs(permitted[:, 2] -
(pose[2]-geometry['body_contact_height_m'])) <= geometry.get('max_step_m', .1)
+ local*math.tan(math.radians(geometry['max_slope_degrees'])))]
if candidate_mask is not None:
permitted = permitted[candidate_mask(permitted)]
candidates = points[good]
candidates = candidates[[tuple(key) in allowed for key in self.surface.cell_keys(candidates)]]
if not len(candidates) or len(permitted) < 8:
return None
offsets = np.linspace(-geometry["width_m"] / 2, geometry["width_m"] / 2,
math.ceil(geometry["width_m"] / 0.1) + 1)
def supported(point):
bearing = point[:2]-pose[:2]
bearing /= max(np.linalg.norm(bearing), 1e-9)
lateral = np.array([-bearing[1], bearing[0]])
across = point[:2] + offsets[:, None] * lateral
# Bind each lateral query to measured, permitted ground at its own
# height. Do not copy the centre elevation across a cross-slope or
# project a sidewalk label through an overhang onto another floor.
distances = np.linalg.norm(across[:,None,:]-candidates[None,:,:2],axis=2)
distances = np.linalg.norm(across[:,None,:]-permitted[None,:,:2],axis=2)
nearest = np.argmin(distances,axis=1)
if np.any(distances[np.arange(len(across)),nearest] > .15):
return False
keys = [tuple(cell) for cell in self.surface.cell_keys(candidates[nearest])]
keys = [tuple(cell) for cell in self.surface.cell_keys(permitted[nearest])]
self.evidence = {
"source": "current-range-and-observed-semantic-memory",
"goal": point.tolist(),
@@ -384,43 +392,23 @@ class ObservedGoals:
self.evidence['approach_clearance_m'] = (
float(retained_clearance) if math.isfinite(retained_clearance) else None)
return retain.tolist()
# Score the task direction at the existing 3.5 m observation horizon.
# Distance to a remote endpoint mostly rewards longitudinal advance:
# slightly farther side returns can beat a clear straight destination
# and make successive measured goals oscillate across the corridor.
# This reference only ranks actual permitted returns. It is never a
# generated drive goal, a straight-line route or a clearance receipt.
reference = pose[:2] + forward * horizon
# A smooth local attraction, normalized to metres like boundary_cost.
# Its gradient diminishes near the reference so centimetres of extra
# advance cannot outweigh clearance from an observed corridor edge.
distance_to_target = np.sum((candidates[:, :2] - reference)**2, axis=1) / horizon
# The declared task, not the selected lens, owns the preferred direction.
x,y,z,w = pose[3:7]
heading = math.atan2(2*(w*z+x*y),1-2*(y*y+z*z))
bearing = np.arctan2(candidates[:,1]-pose[1],candidates[:,0]-pose[0])-heading
score = (distance_to_target + .2*np.abs(np.arctan2(np.sin(bearing),np.cos(bearing)))
+ self.boundary_cost(candidates, geometry, now))
clearance_cost, clearances = self.clearance_cost(
candidates, pose, geometry, now, lookahead_m=horizon)
score += clearance_cost
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
selected = candidates[index]
if retain is not None and not (
retained_clearance < geometry['width_m']
and clearances[index] > retained_clearance + .1
):
selected = retain
supported(retain)
if self.evidence is not None:
self.evidence['approach_clearance_m'] = (
float(self.approach_clearance(selected[None], pose, geometry, now)[0])
if self.clearance_observation is not None
and 0 <= now-self.clearance_observation[0] <= .8
and len(self.clearance_observation[1]) else None)
if self.evidence is not None and not math.isfinite(
self.evidence.get('approach_clearance_m') or 0.):
self.evidence['approach_clearance_m'] = None
return selected.tolist()
observed = self.clearance_observation
obstacles = (observed[1] if observed is not None and 0 <= now-observed[0] <= .8
else np.empty((0, 2)))
for passages in passage_centres(permitted, pose, target, geometry, obstacles):
for passage in passages:
distance = np.linalg.norm(candidates[:, :2]-passage['xy'], axis=1)
for index in np.argsort(distance, kind="stable"):
if distance[index] > .25:
break
selected = candidates[index]
if not supported(selected):
continue
clearance = self.approach_clearance(selected[None], pose, geometry, now)[0]
self.evidence.update(source="observed-passage-centre",
passage_width_m=float(passage['width']),
passage_centre_xy=passage['xy'].tolist(),
route_role="rank-distinct-passages-only",
approach_clearance_m=float(clearance) if math.isfinite(clearance) else None)
return selected.tolist()
return None
@@ -0,0 +1,63 @@
"""Measured passage centres for local intent, independent of waypoint attraction.
The route ranks distinct passages. It cannot move a passage's centre toward its
endpoint. This is a proposal to the native planner, never a free-space or swept
body certificate. In particular small gaps in a sampled cross-section are not
converted to positive semantic cells.
"""
import math
import numpy as np
def passage_centres(points, pose, target, geometry, obstacles):
position = np.asarray(pose[:2])
x, y, z, w = pose[3:7]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
local = (points[:, :2]-position) @ axes
hazards = (obstacles-position) @ axes if len(obstacles) else np.empty((0, 2))
width = geometry['width_m']
length = geometry.get('length_m', width)
route = (np.asarray(target)-position) @ axes
# Common forward sections avoid rewarding a lens side with longer rays.
# The 3.5 m authority horizon is unchanged. The complete measured section,
# including returns laterally outside that circle, supplies the boundaries.
horizon = min(3., float(local[:, 0].max()))
for along in np.arange(horizon, .59, -.2):
lateral = np.sort(local[np.abs(local[:, 0]-along) <= length/2, 1])
if len(lateral) < 8:
continue
# 20 cm semantic cells: two adjacent measured cells are one interval.
# Larger unsupported intervals remain distinct passages.
groups = np.split(lateral, np.flatnonzero(np.diff(lateral) > .3)+1)
intervals = [(float(g[0]), float(g[-1])) for g in groups if len(g) >= 3]
near = hazards[(hazards[:, 0] >= .4)
& (hazards[:, 0] <= along+length)]
for boundary in sorted(set(np.round(near[:, 1]/.1).astype(int))):
low, high = boundary*.1-.1, boundary*.1+.1
intervals = [piece for a,b in intervals for piece in (
[(a,b)] if high <= a or low >= b else
[(a,min(b,low)),(max(a,high),b)]) if piece[1]>piece[0]]
centres=[]
for low,high in intervals:
if high-low < width:
continue
middle=(low+high)/2
# A broad open area has no nearby pair of boundaries to centre
# between. The route can choose a direction within its interior.
if high-low >= 2*3.5 and route[0] > .1:
middle=float(np.clip(along*route[1]/route[0],low+width,high-width))
xy=position+axes @ np.array([along,middle])
if np.linalg.norm(xy-position) > 3.5:
continue
centres.append(dict(xy=xy, width=high-low, along=float(along),
bounds=[low,high], yaw=yaw))
if centres:
# Topological choice: the endpoint ranks passages, never samples
# within one passage. Native planning still validates connectivity.
direction=np.asarray(target)-position
centres.sort(key=lambda c: abs(math.atan2(
direction[0]*(c['xy'][1]-position[1])-direction[1]*(c['xy'][0]-position[0]),
np.dot(direction,c['xy']-position))))
yield centres
+4 -1
View File
@@ -707,6 +707,9 @@ class ComposedInference:
and self.mission.can_query_arrival(pose)
and np.linalg.norm(np.asarray(pose[:2]) - arrival_target) <= 3.5
)
route_transition_nearby = bool(not recovering and arrival_target is not None
and isinstance(self.mission, RoutedMission)
and math.dist(pose[:2], arrival_target) <= 3.5)
terminal_region = bool(
nearby
and math.dist(pose[:2], arrival_target)
@@ -840,7 +843,7 @@ class ComposedInference:
if arrival_candidate or body_goal_query
else None,
"route_transition_target": arrival_target
if nearby and isinstance(self.mission, RoutedMission) else None,
if route_transition_nearby else None,
"max_speed_mps": min(self.max_speed, 0.1)
if intent["state"] == "reversing" or intent.get("corner_approach")
else min(self.max_speed, inputs.get("source.crossing-admission", {}).get("speed_limit_mps") or self.max_speed),
@@ -325,8 +325,17 @@ class RoutedMission(WaypointMission):
return True
return super().heading_progress(pose, seconds)
def advisory_joint(self):
segments = self.leg['segments']
return bool(segments and self.segment_index < len(segments)-1
and segments[self.segment_index].get('guidance_only')
and not segments[self.segment_index].get('return_to_anchor'))
def can_query_arrival(self, pose):
return not self.route_failure and self.remaining is not None
# Intermediate advisory nodes select the next route leg; they are not
# destinations for chassis placement. Only the current support receipt
# may advance that cursor while free-space navigation owns the path.
return not self.route_failure and self.remaining is not None and not self.advisory_joint()
def arrival_target(self):
segments = self.leg["segments"]
@@ -406,7 +415,7 @@ class RoutedMission(WaypointMission):
or inclination(pose) >= 30
or self.segment_index >= len(segments) - 1
or segments[self.segment_index].get("return_to_anchor")
or math.dist(pose[:2], self.arrival_target()) <= 0.4
or (not self.advisory_joint() and math.dist(pose[:2], self.arrival_target()) <= 0.4)
):
return None
expected = dict(
@@ -473,7 +482,12 @@ class RoutedMission(WaypointMission):
self.completed_length += math.dist(segment["start_xy"], segment["end_xy"])
self.segment_index += 1
self.last_transition_time = seconds
self.anchor = self.goal = self.best_distance = self.recovery_goal = None
# A route cursor transition changes the itinerary, not the observed
# passage. Revalidate its existing local goal against the new segment
# instead of manufacturing a fresh lateral target on every graph joint.
if self.goal is not None and not self.goal_permitted(self.goal):
self.goal = None
self.anchor = self.best_distance = self.recovery_goal = None
self.attempts = 0
self.turn_started = self.turn_goal = self.turn_best_error = None
self.state = "replanning"
+28 -1
View File
@@ -334,7 +334,10 @@ def test_clear_retained_intent_does_not_recompute_alternative_approaches(selecto
# New nearby geometry must still cause the alternatives to be evaluated.
selector.observe_navigation(clearance_receipt(position, [[1.6, 0.]]), position, 1, 'run', 1.1)
assert selector.choose(points, position, target, goal, (), GEOMETRY, 1.2) != goal
assert max(sizes) > 1
changed = selector.choose(points, position, target, goal, (), GEOMETRY, 1.2)
assert changed is not None
assert evaluate(np.array([changed]), position, GEOMETRY, 1.2)[0] > (
evaluate(np.array([goal]), position, GEOMETRY, 1.2)[0] + .1)
def test_clearance_is_bounded_below_exact_continuous_segments(selector):
@@ -455,3 +458,27 @@ def test_shared_bearing_queries_conservatively_bound_common_horizon(selector):
expected.append(np.min(np.linalg.norm(obstacles-(a+projection[:, None]*(b-a)), axis=1)))
assert np.all(actual <= np.asarray(expected)+1e-10)
assert np.max(np.asarray(expected)-actual) < .041
@pytest.mark.parametrize('yaw,shift', [(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
def test_route_endpoint_can_select_a_passage_but_cannot_move_its_centre(selector,yaw,shift):
points,pose,_,_,rotation=road(yaw,shift)
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
goals=[]
for endpoint in ([8,-5],[8,0],[8,5],[675,-9]):
goal=selector.choose(points,pose,np.array(shift)+rotation@endpoint,None,(),GEOMETRY,1.)
assert goal is not None
goals.append(goal)
assert all(np.array_equal(goal,goals[0]) for goal in goals)
assert abs(((np.array(goals[0][:2])-shift)@rotation)[1])<.1
def test_route_selects_the_relevant_observed_branch(selector):
pose=[0,0,.37,0,0,0,1]
points=np.array([[x,y,0.] for x in np.arange(.4,3.5,.07)
for y in np.arange(-3.,3.01,.07) if abs(y)>1.])
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
for sign in [-1,1]:
goal=selector.choose(points,pose,[8,sign*5],None,(),GEOMETRY,1.)
assert goal is not None and sign*goal[1]>1.5
assert np.min(np.linalg.norm(points-goal,axis=1))<1e-9
+39
View File
@@ -282,3 +282,42 @@ def test_component_chain_cannot_reverse_a_one_way_edge():
'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)