283 lines
16 KiB
Python
283 lines
16 KiB
Python
"""Local intent from current range and causal multi-view surface observations.
|
|
|
|
Changing the camera sector must not move a still observed goal to that sector's
|
|
image centre. This selects measured points, never a route or permission to move;
|
|
the native planner still admits the complete commanded body sweep.
|
|
"""
|
|
|
|
import math
|
|
|
|
import numpy as np
|
|
|
|
from .semantic_surface import SemanticSurface
|
|
|
|
|
|
class ObservedGoals:
|
|
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.
|
|
|
|
This removes the greedy progress constraint ONLY during a surveyed
|
|
recovery. It proposes a heading/destination, not a path or a clearance
|
|
receipt. The native planner and body/support guards remain mandatory.
|
|
"""
|
|
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.
|
|
return prior
|
|
def inspect_heading():
|
|
# Nav-style Spin intent: inspect with front range sensors when the
|
|
# panoramic image has no usable metric correspondence (self occlusion
|
|
# included). These XY values encode a bearing, NEVER a drive goal.
|
|
x, y, z, w = pose[3:7]
|
|
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
|
directions = [yaw+offset for offset in (math.pi/2, -math.pi/2, math.pi)]
|
|
views = [np.asarray(pose[:2])+2*geometry["length_m"]*np.array([math.cos(a),math.sin(a)])
|
|
for a in directions]
|
|
for xy in sorted(views, key=lambda p: math.dist(p, target)):
|
|
if all(math.dist(xy, p[:2]) > .6 for p in excluded):
|
|
return dict(goal=[*xy.tolist(), pose[2]-geometry["body_contact_height_m"]],
|
|
reverse=False, kind="orient")
|
|
return None
|
|
permitted = self.surface.permitted_terrain(points, now)
|
|
if not len(permitted):
|
|
return None if prior is not None else inspect_heading()
|
|
xy = np.asarray(pose[:2])
|
|
if prior is not None:
|
|
point = np.asarray(prior["goal"])
|
|
cell = tuple(self.surface.cell_keys(point[None])[0])
|
|
permission, stamp = self.surface.cells.get(cell, (0, -math.inf))
|
|
# The point may enter the near camera/range blind strip. Retain its
|
|
# causal intent only; current swept support still vetoes every tick.
|
|
if (permission != 1 or not self.surface.retained(cell, stamp, now)
|
|
or (candidate_mask is not None and not candidate_mask(point[None])[0])
|
|
or (math.dist(point[:2], xy) > .6
|
|
and not np.any(np.linalg.norm(permitted-point, axis=1) <= .2))):
|
|
return None
|
|
return prior
|
|
delta = permitted[:, :2] - xy
|
|
distance = np.linalg.norm(delta, axis=1)
|
|
good = (distance >= .6) & (distance <= 2 * geometry["length_m"])
|
|
good &= np.abs(permitted[:, 2] - (pose[2]-geometry["body_contact_height_m"])) <= (
|
|
geometry["max_step_m"] + distance*math.tan(math.radians(geometry["max_slope_degrees"])))
|
|
if candidate_mask is not None:
|
|
good &= candidate_mask(permitted)
|
|
for failed in excluded:
|
|
good &= np.linalg.norm(permitted[:, :2] - np.asarray(failed[:2]), axis=1) > .6
|
|
candidates = permitted[good]
|
|
if not len(candidates):
|
|
return inspect_heading()
|
|
x, y, z, w = pose[3:7]
|
|
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
|
|
delta = candidates[:, :2] - xy
|
|
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 measured retreat is one option, alongside forward arcs and
|
|
# stopped pivots. It is never an obligatory first recovery action.
|
|
# 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 order:
|
|
point = candidates[i]
|
|
key = tuple(self.surface.cell_keys(point[None])[0])
|
|
if key in tried:
|
|
continue
|
|
tried.add(key)
|
|
forward = delta[i]/distance[i]
|
|
lateral = np.array([-forward[1], forward[0]])
|
|
across = point[:2]+offsets[:, None]*lateral
|
|
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):
|
|
continue
|
|
heights = permitted[nearest, 2]
|
|
fit = np.polyfit(offsets, heights, 1)
|
|
if (abs(fit[0]) > math.tan(math.radians(geometry["max_slope_degrees"]))
|
|
or np.max(np.abs(heights-np.polyval(fit, offsets))) > .05):
|
|
continue
|
|
self.evidence = dict(source="surveyed-local-maneuver", goal=point.tolist(),
|
|
reverse=bool(reverse[i]), authority="intent-only; live native admission required")
|
|
return dict(goal=point.tolist(), reverse=bool(reverse[i]))
|
|
# A visible permitted sector can be too narrow/sparse to establish a
|
|
# 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 order:
|
|
if abs(errors[i]) >= math.radians(30):
|
|
return dict(goal=candidates[i].tolist(), reverse=False, kind="orient")
|
|
return inspect_heading()
|
|
|
|
def choose(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
|
|
self.evidence = None
|
|
if target is None:
|
|
return None
|
|
points, pose, target = map(lambda x: np.asarray(x, dtype=float), (points, pose, target))
|
|
if points.ndim != 2 or points.shape[1] != 3 or not np.isfinite(points).all():
|
|
raise ValueError("Invalid observed goal range")
|
|
if not len(points):
|
|
return None
|
|
direction = target - pose[:2]
|
|
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)
|
|
good = (
|
|
(distance >= 0.4) & (distance <= 3.5) & (progress < remaining - 0.1)
|
|
& (np.abs(points[:, 2] - (pose[2] - geometry["body_contact_height_m"]))
|
|
<= distance * math.tan(math.radians(geometry["max_slope_degrees"])))
|
|
)
|
|
if candidate_mask is not None:
|
|
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:
|
|
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):
|
|
return None
|
|
offsets = np.linspace(-geometry["width_m"] / 2, geometry["width_m"] / 2,
|
|
math.ceil(geometry["width_m"] / 0.1) + 1)
|
|
|
|
def supported(point):
|
|
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)
|
|
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])]
|
|
self.evidence = {
|
|
"source": "current-range-and-observed-semantic-memory",
|
|
"goal": point.tolist(),
|
|
"oldest_surface_age_seconds": max(now - allowed[key] for key in keys),
|
|
"authority": "intent-only; native swept-obstacle-and-support-admission-required",
|
|
}
|
|
return True
|
|
|
|
# A lens switch cannot replace a currently measured, permitted goal.
|
|
# A new prohibition, missing current range or changed corridor can.
|
|
if prior is not None:
|
|
before = np.asarray(prior, dtype=float)
|
|
matched = np.linalg.norm(candidates - before, axis=1) <= 0.15
|
|
if (math.dist(before[:2], pose[:2]) > 0.8 and matched.any()
|
|
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()
|
|
# 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.
|
|
horizon = min(remaining, 3.5)
|
|
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))
|
|
for index in np.argsort(score, kind="stable"):
|
|
if supported(candidates[index]):
|
|
return candidates[index].tolist()
|
|
return None
|