Restore observed recovery through native Nav2

This commit is contained in:
DCCONSTRUCTIONS
2026-10-08 11:11:12 +03:00
parent 117e937906
commit 140b6002e0
12 changed files with 1351 additions and 24 deletions
@@ -13,12 +13,51 @@ from .semantic_surface import SemanticSurface
class ObservedGoals:
def __init__(self):
def __init__(self, *, reverse_heading_tolerance=math.pi/4):
self.reverse_heading_tolerance = reverse_heading_tolerance
self.surface = SemanticSurface(retain_near=True)
self.measured = {}
self.evidence = None
def observe(self, samples, captured_at, pose):
self.surface.observe(samples, captured_at, pose)
sample = np.asarray(samples, dtype=float).reshape(-1, 4)
for key, point in zip(self.surface.cell_keys(sample), sample, strict=True):
self.measured[tuple(key)] = point[:3].copy()
# Same lifetime and classification owner as the semantic cells. Keep
# actual range returns, never invented voxel centres or hidden geometry.
self.measured = {key: point for key, point in self.measured.items()
if key in self.surface.cells
and self.surface.retained(key, self.surface.cells[key][1], captured_at)}
def boundary_cost(self, candidates, geometry, now):
"""Soft clearance preference, like an inflation potential in a costmap.
A far waypoint is an objective, not a straight-line corridor. Prefer
space away from observed exclusions before reaching their hard veto.
Actual rectangular body/swept support admission remains independent.
"""
barriers = np.array([point for key, point in self.measured.items()
if self.surface.cells.get(key, (1, 0))[0] == 0
and self.surface.retained(key, self.surface.cells[key][1], now)],
dtype=float).reshape(-1, 3)
cost = np.zeros(len(candidates))
if not len(barriers):
return cost
width = geometry['width_m']
# Ignore remote returns before pairwise work; each batch is bounded.
low, high = candidates[:,:2].min(0)-4*width, candidates[:,:2].max(0)+4*width
barriers = barriers[np.all((barriers[:,:2]>=low)&(barriers[:,:2]<=high),axis=1)]
if not len(barriers):
return cost
for start in range(0,len(candidates),128):
batch = candidates[start:start+128]
distance = np.linalg.norm(batch[:,None,:2]-barriers[None,:,:2],axis=2)
dz = barriers[None,:,2]-batch[:,None,2]
relevant = (dz>=-geometry.get('max_step_m', .1)) & (dz<=geometry.get('height_m',width))
nearest = np.min(np.where(relevant,distance,np.inf),axis=1)
cost[start:start+len(batch)] = 2*width*np.exp(-nearest/width)
return cost
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
"""Measured local destinations may temporarily move away from the task.
@@ -30,6 +69,11 @@ class ObservedGoals:
points = np.asarray(points, dtype=float).reshape(-1, 3)
if not len(points) or target is None:
return None
retained = np.array([point for point in self.measured.values()
if np.linalg.norm(point[:2]-np.asarray(pose[:2]))
<= 2*geometry['length_m']], dtype=float).reshape(-1, 3)
if len(retained):
points = np.concatenate((points, retained))
if prior is not None and prior.get("kind") == "orient":
# The viewing intent survives its source leaving the crop. Current
# range and full swept-body support still govern the actual pivot.
@@ -82,16 +126,40 @@ class ObservedGoals:
bearings = np.arctan2(delta[:, 1], delta[:, 0]) - yaw
errors = np.arctan2(np.sin(bearings), np.cos(bearings))
distance = np.linalg.norm(delta, axis=1)
# A short straight back-out is one option, alongside forward arcs and
# A measured retreat is one option, alongside forward arcs and
# stopped pivots. It is never an obligatory first recovery action.
reverse = (np.abs(errors) > math.pi-.12) & (distance <= .8)
# This is a destination proposal, not a swept-clearance certificate.
# Distance is already bounded by the same robot-sized local horizon.
# The blind strip may hide nearby floor; a farther observed rear goal
# must not become a forced 180-degree turn merely because it exceeds
# a separate short-retreat cutoff. Live sweeps still admit every tick.
reverse = np.abs(errors) > math.pi-self.reverse_heading_tolerance
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)
# 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.
# Balance failed local directions; the rear sector uses reverse.
# Retain the existing geometric score within each family.
# This schedules intentions only, never certifies a body trajectory.
def family(relative):
return np.floor((relative + math.pi/4) / (math.pi/2)).astype(int) % 4
families = family(errors)
failures = np.zeros(4, dtype=int)
if excluded:
failed_delta = np.asarray(excluded)[:, :2] - xy
failed_distance = np.linalg.norm(failed_delta, axis=1)
failed_angle = np.arctan2(failed_delta[:, 1], failed_delta[:, 0])-yaw
failed_angle = np.arctan2(np.sin(failed_angle), np.cos(failed_angle))
nearby = failed_distance <= 2*geometry['length_m']
np.add.at(failures, family(failed_angle[nearby]), 1)
order = np.lexsort((score, failures[families]))
offsets = np.linspace(-geometry["width_m"]/2, geometry["width_m"]/2,
math.ceil(geometry["width_m"]/.1)+1)
# Search once per 20 cm observed cell, not every duplicate ray return.
tried = set()
for i in np.argsort(score, kind="stable"):
for i in order:
point = candidates[i]
key = tuple(self.surface.cell_keys(point[None])[0])
if key in tried:
@@ -116,7 +184,7 @@ class ObservedGoals:
# translation destination while still being worth inspecting with the
# front depth sensors. This grants ONLY an orientation intent. Neither
# the point nor the camera survey certifies the ground under a pivot.
for i in np.argsort(score, kind="stable"):
for i in order:
if abs(errors[i]) >= math.radians(30):
return dict(goal=candidates[i].tolist(), reverse=False, kind="orient")
return inspect_heading()
@@ -192,7 +260,11 @@ class ObservedGoals:
return before.tolist()
distance_to_target = np.linalg.norm(candidates[:, :2] - target, axis=1)
# The declared task, not the selected lens, owns the preferred direction.
score = distance_to_target + 2 * np.abs((candidates[:, :2] - pose[:2]) @ lateral)
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))
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
return candidates[index].tolist()