Local preservation snapshot, not a new deployment or simulation acceptance.
200 lines
10 KiB
Python
200 lines
10 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):
|
|
self.surface = SemanticSurface(retain_near=True)
|
|
self.evidence = None
|
|
|
|
def observe(self, samples, captured_at, pose):
|
|
self.surface.observe(samples, captured_at, pose)
|
|
|
|
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
|
|
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 short straight back-out 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)
|
|
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
|
|
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"):
|
|
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 np.argsort(score, kind="stable"):
|
|
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()
|
|
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)
|
|
for index in np.argsort(score, kind="stable"):
|
|
if supported(candidates[index]):
|
|
return candidates[index].tolist()
|
|
return None
|