Files
NODEDC_MISSION_CORE/simulation/ai-polygon/navigation/observed_goals.py
T

465 lines
27 KiB
Python

"""Local intent from a causal, measured world-space surface.
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
from collections import OrderedDict
import numpy as np
from scipy.spatial import cKDTree
from .semantic_surface import SemanticSurface
from .observed_passages import passage_centres
class ObservedGoals:
def __init__(self, *, reverse_heading_tolerance=math.pi/4):
self.reverse_heading_tolerance = reverse_heading_tolerance
# Intent and native terrain use the same bounded, capture-deduplicated
# evidence rule. A single conflicting segmentation must not cancel a
# progressing path that repeated observations still support. Geometry
# and live swept-body guards remain immediate and independent.
self.surface = SemanticSurface(retain_near=True, fuse_observations=True)
self.measured = {}
self.seen_semantics = OrderedDict()
self.evidence = None
self.clearance_observation = None
self.clearance_index = None
def observe(self, samples, captured_at, pose, *, frame_id=None, capture_id=None):
if frame_id is not None and frame_id in self.seen_semantics:
return
self.surface.observe(samples, captured_at, pose, evidence_id=capture_id)
if frame_id is not None:
self.seen_semantics[frame_id] = True
while len(self.seen_semantics) > 128:
self.seen_semantics.popitem(last=False)
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 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, *, lookahead_m=None):
"""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
if not len(candidates):
return distances
if self.clearance_index is None or self.clearance_index[0] is not observed:
self.clearance_index = (observed, cKDTree(observed[1]))
tree = self.clearance_index[1]
xy = np.asarray(pose[:2])
delta = candidates[:, :2]-xy
length = np.linalg.norm(delta, axis=1)
direction = delta / np.maximum(length[:, None], 1e-9)
inverse = angular_error = None
if lookahead_m is not None:
# Compare bearings over one common horizon. A short destination
# before an obstacle must not hide that obstacle from intent cost.
# This extends a scoring query, never the measured drive goal.
# Dense range samples often describe almost the same bearing.
# Share radial queries in quarter-degree bins; subtract the exact
# maximum displacement caused by that rotation from each result.
# This is still a lower bound, with <= 4.1 cm total error at 3.5 m.
bearing = np.arctan2(direction[:, 1], direction[:, 0])
bins = np.rint(bearing/math.radians(.25)).astype(int)
unique, inverse = np.unique(bins, return_inverse=True)
quantized = unique*math.radians(.25)
angular_error = 2*lookahead_m*np.abs(np.sin((bearing-quantized[inverse])/2))
direction = np.column_stack((np.cos(quantized), np.sin(quantized)))
length = np.full(len(unique), lookahead_m)
distances = np.full(len(unique), np.inf)
start = np.minimum(length, geometry.get("length_m", geometry["width_m"])/2)
# Nearest-obstacle distance is 1-Lipschitz. Sampling at <= 5 cm and
# subtracting half the actual spacing gives a conservative continuous
# segment lower bound (error <= 2.5 cm), without an N*M hazard matrix.
# This is a soft ranking cost only, never a swept-body safety receipt.
for first in range(0, len(length), 128):
last = min(first+128, len(length))
steps = np.maximum(1, np.ceil((length[first:last]-start[first:last])/.05).astype(int))
spacing = (length[first:last]-start[first:last])/steps
along = (start[first:last, None]
+ np.minimum(np.arange(int(steps.max())+1)[None], steps[:, None])
* spacing[:, None])
queries = xy + along[:, :, None]*direction[first:last, None]
nearest = tree.query(queries.reshape(-1, 2), workers=1)[0].reshape(along.shape)
distances[first:last] = np.maximum(0., nearest.min(axis=1)-spacing/2)
if inverse is not None:
return np.maximum(0., distances[inverse]-angular_error)
return distances
def clearance_cost(self, candidates, pose, geometry, now, *, lookahead_m=None):
clearance = self.approach_clearance(candidates, pose, geometry, now,
lookahead_m=lookahead_m)
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.
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
# Query nearest XY neighbours until one also lies in the candidate's
# exact height interval. Usually the first return qualifies. Unlike a
# dense candidate-by-barrier matrix this does no work for distant
# obstacles once a nearer relevant boundary has been found.
tree = cKDTree(barriers[:, :2])
heights = np.sort(barriers[:, 2])
lower = candidates[:, 2]-geometry.get('max_step_m', .1)
upper = candidates[:, 2]+geometry.get('height_m', width)
has_relevant = (np.searchsorted(heights, np.nextafter(upper, np.inf), side='right')
> np.searchsorted(heights, np.nextafter(lower, -np.inf), side='left'))
for start in range(0, len(candidates), 128):
pending = np.arange(start, min(start+128, len(candidates)))
pending = pending[has_relevant[pending]]
count = 1
while len(pending):
distance, indices = tree.query(candidates[pending, :2], k=count, workers=1)
distance = np.asarray(distance).reshape(len(pending), count)
indices = np.asarray(indices).reshape(len(pending), count)
dz = barriers[indices, 2]-candidates[pending, 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)
found = np.isfinite(nearest)
cost[pending[found]] = 2*width*np.exp(-nearest[found]/width)
pending = pending[~found]
if count == len(barriers):
break
count = min(2*count, len(barriers))
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)
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.
# 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, *, travel_direction=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.
allowed = {
key: stamp for key, (permission, stamp) in self.surface.cells.items()
if permission == 1 and self.surface.retained(key, stamp, now)
}
# A current observation must still see some known permitted surface.
# A wholly missing/other-height scene cannot be replaced by old memory.
if not any(tuple(key) in allowed for key in self.surface.cell_keys(points)):
return None
remembered = np.array([point for key, point in self.measured.items()
if key in allowed], dtype=float).reshape(-1, 3)
# Goal selection consumes the observed world, not just the current
# body-facing range crop. Both new and retained intentions may refer to
# actual earlier returns; no timestamp or physical support is created.
# Native planning and live swept-body admission still use current range.
points = np.concatenate((points, remembered))
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
if not np.any(good):
return None
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, support=permitted, *, source="measured-surface-memory"):
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,:]-support[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(support[nearest])]
self.evidence = {
"source": source,
"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
# Positive measured extent has already been bounded by local distance,
# height, permission lifetime and the mission's permitted region.
passage_points = permitted
retain = None
if prior is not None:
before = np.asarray(prior, dtype=float)
cell = tuple(self.surface.cell_keys(before[None])[0])
matched = np.linalg.norm(passage_points - before, axis=1) <= 0.15
# A routed local passage is a through-intent, not a succession of
# stopping points. Advance its lookahead along the selected
# continuation before the chassis starts chasing a near lateral
# endpoint. A changed visible extent alone must not re-elect the
# lateral centre on every reached point.
# The projected XY is only a query: return an actual permitted
# range sample, with the existing width and obstacle checks. Never
# extrapolate range, terrain permission, or a motion certificate.
if travel_direction is not None and cell in allowed and matched.any():
continuation = np.asarray(travel_direction, dtype=float)
if (continuation.shape != (2,) or not np.isfinite(continuation).all()
or np.linalg.norm(continuation) <= 1e-9):
raise ValueError("Invalid passage travel direction")
continuation = continuation / np.linalg.norm(continuation)
along = float((before[:2]-pose[:2]) @ continuation)
advance = min(3., remaining)-along
if (along > 0 and advance >= float(self.surface.cell_size[0])
and all(math.dist(before[:2], failed[:2]) > 0.6 for failed in excluded)):
query = before[:2]+advance*continuation
nearby = np.linalg.norm(candidates[:, :2]-query, axis=1)
for index in np.argsort(nearby, kind="stable"):
if nearby[index] > .15:
break
selected = candidates[index]
clearance = self.approach_clearance(selected[None], pose, geometry, now,
lookahead_m=min(remaining, 3.5))[0]
if clearance < geometry['width_m'] or not supported(selected,
source="continuing-observed-passage"):
continue
self.evidence['approach_clearance_m'] = (
float(clearance) if math.isfinite(clearance) else None)
return selected.tolist()
if (0.8 < math.dist(before[:2], pose[:2]) <= 3.5
and math.dist(before[:2], target) < remaining - 0.1
and cell in allowed 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, passage_points, source="retained-observed-passage")):
retain = before
horizon = min(remaining, 3.5)
retained_clearance = (self.approach_clearance(
retain[None], pose, geometry, now, lookahead_m=horizon)[0]
if retain is not None else None)
if retain is not None and retained_clearance >= geometry['width_m']:
# The selection rule below cannot replace this still supported
# intention. Avoid recomputing all alternative approaches each
# sensor tick: doing so used most of the original plan lease.
self.evidence['approach_clearance_m'] = (
float(retained_clearance) if math.isfinite(retained_clearance) else None)
return retain.tolist()
observed = self.clearance_observation
obstacles = (observed[1] if observed is not None and 0 <= now-observed[0] <= .8
else np.empty((0, 2)))
# New and retained goals share one measured world-space representation.
for passages in passage_centres(passage_points, pose, target, geometry, obstacles,
travel_direction=travel_direction):
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=("continuation-direction-and-branch-selection" if travel_direction is not None
else "rank-distinct-passages-only"),
approach_clearance_m=float(clearance) if math.isfinite(clearance) else None)
return selected.tolist()
return None