Guide local goals around observed obstacles and finish native recovery

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 13:06:04 +03:00
parent 51406fc90c
commit ade3c19d2a
10 changed files with 281 additions and 12 deletions
+5 -1
View File
@@ -44,7 +44,11 @@ def configuration(inputs, robot):
static_layer=dict(plugin='nav2_costmap_2d::StaticLayer', map_topic='/observed_map',
map_subscribe_transient_local=True, subscribe_to_updates=False),
inflation_layer=dict(plugin='nav2_costmap_2d::InflationLayer',
cost_scaling_factor=3.0, inflation_radius=math.hypot(x, y) + 0.15),
# A gentle field over the local goal horizon makes observed
# obstacles influence the path before the body is beside them.
# Full footprint, lethal cells and support gates are unchanged.
cost_scaling_factor=1.0 / geometry['width_m'],
inflation_radius=max(3.5, math.hypot(x, y) + 0.15)),
)
# Bound the corner displacement from a full angular bin to half a map
# cell. Humble floors the start heading; a coarse primitive lattice can
@@ -39,7 +39,8 @@ def observed_turn_support(angle, terrain, pose, monitor, contact_height):
return bool(np.all(states=='observed-supported'))
def alignment_angle(pose, goal, terrain, detected, monitor, contact_height):
def alignment_angle(pose, goal, terrain, detected, monitor, contact_height, *,
collision_terrain=None):
delta = np.asarray(goal[:2]) - np.asarray(pose[:2])
if np.linalg.norm(delta) <= .4:
return None
@@ -49,8 +50,13 @@ def alignment_angle(pose, goal, terrain, detected, monitor, contact_height):
angle = math.atan2(math.sin(bearing), math.cos(bearing))
if abs(angle) < math.pi/6:
return None
if not monitor.rotation_clear(angle, terrain, pose):
collision = terrain if collision_terrain is None else collision_terrain
if not monitor.rotation_clear(angle, collision, pose):
return None
if collision_terrain is not None:
forbidden = terrain[terrain[:, 3] > collision[:, 3]]
if not monitor.ground_envelope().rotation_clear(angle, forbidden, pose):
return None
objects = DetectionObstacles(monitor)
hazards = np.column_stack((detected, np.full(len(detected), objects.cost)))
if not objects.monitor.rotation_clear(angle, hazards, pose):
+15 -5
View File
@@ -143,6 +143,15 @@ class Navigation:
detected=observed['detected']):
return self.reply('stale-range')
route = route_observation(terrain, pose, value, self.monitor.max_step)
# Return the same observed search obstacles used by Smac, as bounded
# intent guidance only. Goal selection must see unlabelled solids too.
hazards = observed['search_terrain']
hazards = hazards[hazards[:, 3] > self.monitor.max_step + 1e-4, :2]
if len(hazards):
_, indices = np.unique(np.floor(hazards / .05), axis=0, return_index=True)
hazards = hazards[np.sort(indices)]
receipts['clearance_observation'] = dict(
observation=route['observation'], obstacles_xy=hazards.tolist())
support = route_support(self.monitor, observed, value, self.inputs)
if support is not None:
receipts["route_support"] = support
@@ -183,7 +192,8 @@ class Navigation:
if (not reverse and value['translation_allowed'] and not aligning
and alignment_key != self.attempted_alignment):
turn = alignment_angle(pose, goal, terrain, observed['detected'], self.monitor,
value['body_contact_height_m'])
value['body_contact_height_m'],
collision_terrain=observed['collision_terrain'])
orienting = aligning or turn is not None or (not reverse and orientation is not None
and orientation_key != self.completed_orientation
and not value['translation_allowed'])
@@ -207,16 +217,16 @@ class Navigation:
self.attempted_alignment = alignment_key
local_path = [[0.,0.,0.],[0.,0.,0.]]
elif reverse:
key = ('backup', tuple(goal[:2]), limit)
completed = self.completed_action(key, route)
if completed is not None:
return completed
delta = goal[:2]-pose[:2]
heading = yaw_of(pose)
rear = -float(delta @ [math.cos(heading), math.sin(heading)])
if rear <= 0:
self.node.stop()
return self.reply('reverse-goal-is-not-behind', status='blocked')
key = ('backup', tuple(goal[:2]), limit)
completed = self.completed_action(key, route)
if completed is not None:
return completed
if key != self.action_key:
with self.owner_lock:
self.action_key = None
@@ -18,6 +18,7 @@ class ObservedGoals:
self.surface = SemanticSurface(retain_near=True)
self.measured = {}
self.evidence = None
self.clearance_observation = None
def observe(self, samples, captured_at, pose):
self.surface.observe(samples, captured_at, pose)
@@ -30,6 +31,59 @@ class ObservedGoals:
if key in self.surface.cells
and self.surface.retained(key, self.surface.cells[key][1], captured_at)}
def observe_navigation(self, result, pose, seconds, execution_inputs_sha256, captured_at):
"""Use native observed geometry for intent, never as motion admission."""
receipt = result.get("clearance_observation")
expected = dict(pose=list(pose), simulation_time_seconds=seconds,
execution_inputs_sha256=execution_inputs_sha256)
if not isinstance(receipt, dict) or receipt.get("observation") != expected:
return
points = np.asarray(receipt.get("obstacles_xy"), dtype=float)
if not points.size:
points = np.empty((0, 2))
if (points.ndim != 2 or points.shape[1] != 2 or len(points) > 30000
or not np.isfinite(points).all() or not math.isfinite(captured_at)):
raise ValueError("Invalid observed clearance guidance")
self.clearance_observation = (captured_at, points.copy())
def approach_clearance(self, candidates, pose, geometry, now):
"""Minimum obstacle distance along candidate approaches, in metres.
These straight segments rank spatial intentions; they are not paths.
Smac still chooses the actual path and every commanded sweep must pass
live body, support, semantic and freshness admission. No new free cells
or positive surface labels are created here.
"""
distances = np.full(len(candidates), np.inf)
observed = self.clearance_observation
if observed is None or not 0 <= now-observed[0] <= .8 or not len(observed[1]):
return distances
obstacles = observed[1]
xy = np.asarray(pose[:2])
delta = candidates[:, :2]-xy
length = np.linalg.norm(delta, axis=1)
# The currently occupied body is shared by every approach. Compare the
# corridor ahead of it, preserving the same full-body live veto below.
start = np.minimum(length, geometry.get("length_m", geometry["width_m"])/2)
direction = delta / np.maximum(length[:, None], 1e-9)
low = np.minimum(xy, candidates[:, :2].min(0))-4*geometry['width_m']
high = np.maximum(xy, candidates[:, :2].max(0))+4*geometry['width_m']
obstacles = obstacles[np.all((obstacles >= low) & (obstacles <= high), axis=1)]
if not len(obstacles):
return distances
offsets = obstacles-xy
for first in range(0, len(candidates), 128):
last = min(first+128, len(candidates))
along = np.clip(direction[first:last] @ offsets.T,
start[first:last, None], length[first:last, None])
difference = (offsets[None]-along[:, :, None]*direction[first:last, None])
distances[first:last] = np.sqrt(np.min(np.sum(difference*difference, axis=2), axis=1))
return distances
def clearance_cost(self, candidates, pose, geometry, now):
clearance = self.approach_clearance(candidates, pose, geometry, now)
return 4*geometry['width_m']*np.exp(-clearance/geometry['width_m']), clearance
def boundary_cost(self, candidates, geometry, now):
"""Soft clearance preference, like an inflation potential in a costmap.
@@ -137,6 +191,7 @@ class ObservedGoals:
turning = np.where(reverse, math.pi-np.abs(errors), np.abs(errors))
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
score += self.boundary_cost(candidates, geometry, now)
score += self.clearance_cost(candidates, pose, geometry, now)[0]
# Recovery actions need a fair turn, as in Nav2's RoundRobin recovery
# subtree. Distance-to-task alone can spend every retry on almost the
# same forward approach before ever considering a measured retreat.
@@ -250,6 +305,7 @@ class ObservedGoals:
# A lens switch cannot replace a currently measured, permitted goal.
# A new prohibition, missing current range or changed corridor can.
retain = None
if prior is not None:
before = np.asarray(prior, dtype=float)
matched = np.linalg.norm(candidates - before, axis=1) <= 0.15
@@ -257,7 +313,7 @@ class ObservedGoals:
and all(math.dist(before[:2], failed[:2]) > 0.6 for failed in excluded)
and (candidate_mask is None or candidate_mask(before[None])[0])
and supported(before)):
return before.tolist()
retain = before
# 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
@@ -276,7 +332,27 @@ class ObservedGoals:
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)
score += clearance_cost
retained_clearance = (self.approach_clearance(retain[None], pose, geometry, now)[0]
if retain is not None else None)
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
return candidates[index].tolist()
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()
return None
@@ -844,6 +844,10 @@ class ComposedInference:
"allow_reverse": intent["state"] == "reversing",
},
)
if getattr(self, "observed_goals", None) is not None:
self.observed_goals.observe_navigation(
result, pose, inputs["source.simulation-time"], self.inputs["sha256"],
inputs.get("source.range-captured-at", calibration.get("captured_at", -math.inf)))
self.mission.reject_local_plan(
result, pose, inputs["source.simulation-time"], self.inputs["sha256"])
self.mission.recovery.observe_navigation(