Compare commits

..
12 Commits
17 changed files with 942 additions and 128 deletions
@@ -24,11 +24,13 @@ class ContinuousComposition(ComposedInference):
self.recovery_view_request = None
self.recovery_detection_view = None
self.last_supplement = -math.inf
self.crossing = MarkedCrossing(self.geometry)
self.crossing = MarkedCrossing(self.geometry, observation_range_m=max(
12., self.inputs["sensors"]["mounts"]["k1"]["range_m"][1]))
def reset(self):
super().reset()
self.crossing = MarkedCrossing(self.geometry)
self.crossing = MarkedCrossing(self.geometry, observation_range_m=max(
12., self.inputs["sensors"]["mounts"]["k1"]["range_m"][1]))
self.recovery_view_request = None
self.recovery_detection_view = None
@@ -87,8 +89,21 @@ class ContinuousComposition(ComposedInference):
allowed = permissions[indices]
known = (values["segmentation.known"][indices] | crossing_mask[indices]) & (permitted[indices] | ~allowed)
known &= self.camera_source.semantic_pixels(u[visible], v[visible])
samples = np.column_stack((points[visible][known], allowed[known].astype(int)))
if crossing.get("admitted"):
# The observed crossing AREA owns this semantic exception, including
# current range in the camera's near blind strip. Waiting for that
# ground to reappear in the image leaves old road prohibitions under
# the rover. No new points/support or traffic permission are created.
crossing_ground = self.crossing.ground_mask(points)
visible_indices = np.flatnonzero(visible)
crossing_ground[visible_indices[known]] = False # already classified
classes = values["segmentation.labels"][indices]
crossing_ground[visible_indices[~np.isin(classes, (0, 1, 2, 3))]] = False
samples = np.concatenate((samples, np.column_stack((
points[crossing_ground], np.ones(int(crossing_ground.sum()))))))
sample = {
"samples": np.column_stack((points[visible][known], allowed[known].astype(int))).tolist(),
"samples": samples.tolist(),
"captured_at": observation["captured_at"], "pose": observation["pose"],
"frame_id": f"{frame_id}:{yaw}:{pitch}", "capture_id": str(frame_id),
}
+3 -2
View File
@@ -279,7 +279,7 @@ def mounted_range_returns(query, origin, directions, key, spec, forward, *,
itself is scalar, avoiding thousands of tiny NumPy allocations per frame.
"""
count = len(directions)
maximum = np.full(count, 8.0) if key == "k1" else np.minimum(8.0, 6.0 / forward)
maximum = np.full(count, spec["range_m"][1]) if key == "k1" else np.minimum(8.0, 6.0 / forward)
# PhysX consumes Float3 internally. Native callers avoid repeated pybind
# sequence conversion; portable checks can use the identical tuple contract.
mount = query_vector(origin)
@@ -304,7 +304,8 @@ def mounted_range_returns(query, origin, directions, key, spec, forward, *,
distances = np.linalg.norm(positions - origin, axis=1)
depth = np.full(count, np.nan, np.float32)
if key == "k1":
valid = np.isfinite(distances) & (distances >= spec["range_m"][0])
valid = (np.isfinite(distances) & (distances >= spec["range_m"][0])
& (distances <= spec["range_m"][1]))
positions[no_hit] = origin + directions[no_hit] * maximum[no_hit, None]
clear = valid | no_hit
else:
+31 -15
View File
@@ -20,7 +20,7 @@ import yaml
from action_msgs.msg import GoalStatus
from configuration import observed_configuration
from differential_motion import alignment_angle
from navigation.arrival_approach import validate_orientation
from navigation.arrival_approach import validate_orientation, orientation_identity
from navigation.continuous_control import ContinuousControl
from navigation.footprint import Footprint
from navigation.route_observation import route_observation
@@ -103,8 +103,8 @@ class Navigation:
or not value.get('continuous', False)):
return None
target = value.get('arrival_target')
return (orientation['key'], tuple(orientation['xy']),
value['max_speed_mps'], tuple(target) if target is not None else None)
return (orientation_identity(orientation), value['max_speed_mps'],
tuple(target) if target is not None else None)
@staticmethod
def reply(reason, *, status='waiting-for-plan', **extra):
@@ -199,7 +199,7 @@ class Navigation:
if not value.get('visual_goal_available'):
goal[:2] = target
reverse = value['allow_reverse']
orientation_key = ('spin', orientation['key'], tuple(orientation['xy'])) if orientation else None
orientation_key = ('spin', *orientation_identity(orientation)) if orientation else None
if (orientation_key is not None and self.action_key == orientation_key
and self.node.terminal is not None and self.node.terminal.done()
and self.node.terminal.result().status == GoalStatus.STATUS_SUCCEEDED):
@@ -283,17 +283,33 @@ class Navigation:
or entered-self.path_planned_at >= 1.0):
path, status = self.node.plan(pose, goal, math.atan2(goal[1]-pose[1],goal[0]-pose[0]))
if path is None or len(path.poses) < 2:
self.stop()
# Humble has no typed planner error code. Preserve its
# terminal abort without inventing an obstacle diagnosis.
feedback = (dict(planning_result=dict(status='aborted', goal_xy=goal[:2].tolist()))
if status == GoalStatus.STATUS_ABORTED else {})
return self.reply('no-path', status='blocked', route_observation=route, **feedback)
if not continuing:
self.revoke_command()
self.node.follow(path, continuing=continuing)
self.path, self.path_planned_at = path, entered
self.path_context = context
native = self.node.native_command()
# A rejected extension does not invalidate the executing
# path. Never restart it or recycle its old velocity: keep
# only a live same-leg action, admitted below against this
# observation and against current range on every tick.
if (status == GoalStatus.STATUS_ABORTED and following and continuing
and context is not None and value.get('arrival_target') is None
and key != self.action_key and self.path is not None
and len(self.path.poses) >= 2 and self.node.terminal is not None
and not self.node.terminal.done() and native is not None
and time.monotonic()-native[0] <= .25):
receipts['refinement_result'] = dict(status='aborted',
goal_xy=goal[:2].tolist(), executing_goal_xy=list(self.action_key[1]))
key = self.action_key
else:
self.stop()
# Humble has no typed planner error code. Preserve its
# terminal abort without inventing an obstacle diagnosis.
feedback = (dict(planning_result=dict(status='aborted', goal_xy=goal[:2].tolist()))
if status == GoalStatus.STATUS_ABORTED else {})
return self.reply('no-path', status='blocked', route_observation=route, **feedback)
else:
if not continuing:
self.revoke_command()
self.node.follow(path, continuing=continuing)
self.path, self.path_planned_at = path, entered
self.path_context = context
path = self.path
c, s = math.cos(yaw_of(pose)), math.sin(yaw_of(pose))
local_path = [[(p.pose.position.x-pose[0])*c+(p.pose.position.y-pose[1])*s,
@@ -182,7 +182,7 @@ def validate_orientation(value):
return None
if (
not isinstance(value, dict)
or set(value) != {"key", "xy"}
or set(value) not in ({"key", "xy"}, {"key", "xy", "direction_xy"})
or not isinstance(value["key"], str)
or not re.fullmatch(r"[a-zA-Z0-9_-]{1,80}", value["key"])
or not isinstance(value["xy"], list)
@@ -193,9 +193,24 @@ def validate_orientation(value):
)
):
raise ValueError("Invalid orientation intent")
direction = value.get("direction_xy")
if "direction_xy" in value and (
not isinstance(direction, list) or len(direction) != 2
or any(isinstance(v, bool) or not isinstance(v, (float, int))
or not math.isfinite(v) for v in direction)
or not math.isclose(math.hypot(*direction), 1., abs_tol=1e-9)
):
raise ValueError("Invalid orientation direction")
return value
def orientation_identity(value):
"""A translated bearing endpoint is the same intent; a new bearing is not."""
direction = value.get("direction_xy")
return (value["key"], "direction", tuple(direction)) if direction is not None else (
value["key"], "point", tuple(value["xy"]))
class ArrivalApproach:
def __init__(self):
self.turning = self.completed = False
@@ -1,4 +1,4 @@
"""Local intent from current range and causal multi-view surface observations.
"""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;
@@ -12,6 +12,7 @@ import numpy as np
from scipy.spatial import cKDTree
from .semantic_surface import SemanticSurface
from .observed_passages import passage_centres
class ObservedGoals:
@@ -303,7 +304,7 @@ class ObservedGoals:
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):
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
@@ -316,8 +317,21 @@ class ObservedGoals:
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]])
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)
@@ -330,48 +344,89 @@ class ObservedGoals:
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:
if not np.any(good):
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):
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):
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,:]-candidates[None,:,:2],axis=2)
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(candidates[nearest])]
keys = [tuple(cell) for cell in self.surface.cell_keys(support[nearest])]
self.evidence = {
"source": "current-range-and-observed-semantic-memory",
"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
# A lens switch cannot replace a currently measured, permitted goal.
# A new prohibition, missing current range or changed corridor can.
# 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)
matched = np.linalg.norm(candidates - before, axis=1) <= 0.15
if (math.dist(before[:2], pose[:2]) > 0.8 and matched.any()
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)):
and supported(before, passage_points, source="retained-observed-passage")):
retain = before
horizon = min(remaining, 3.5)
retained_clearance = (self.approach_clearance(
@@ -384,43 +439,26 @@ class ObservedGoals:
self.evidence['approach_clearance_m'] = (
float(retained_clearance) if math.isfinite(retained_clearance) else None)
return retain.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.
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))
clearance_cost, clearances = self.clearance_cost(
candidates, pose, geometry, now, lookahead_m=horizon)
score += clearance_cost
for index in np.argsort(score, kind="stable"):
if supported(candidates[index]):
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()
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
@@ -0,0 +1,91 @@
"""Measured passage centres for local intent, independent of waypoint attraction.
The route ranks distinct passages. It cannot move a passage's centre toward its
endpoint. This is a proposal to the native planner, never a free-space or swept
body certificate. In particular small gaps in a sampled cross-section are not
converted to positive semantic cells.
"""
import math
import numpy as np
from scipy.spatial import cKDTree
def passage_centres(points, pose, target, geometry, obstacles, *, travel_direction=None):
position = np.asarray(pose[:2])
# An explicitly selected route continuation stations the observed corridor.
# It is a direction, never the vector toward a remote endpoint. Legacy
# unrouted tasks retain their body-forward observation convention.
if travel_direction is None:
x, y, z, w = pose[3:7]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
else:
direction = np.asarray(travel_direction, dtype=float)
if direction.shape != (2,) or not np.isfinite(direction).all() or np.linalg.norm(direction) <= 1e-9:
raise ValueError("Invalid passage travel direction")
yaw = math.atan2(direction[1], direction[0])
axes = np.array([[math.cos(yaw), -math.sin(yaw)],
[math.sin(yaw), math.cos(yaw)]])
local = (points[:, :2]-position) @ axes
hazards = (obstacles-position) @ axes if len(obstacles) else np.empty((0, 2))
tree = cKDTree(hazards) if len(hazards) else None
width = geometry['width_m']
length = geometry.get('length_m', width)
route = (np.asarray(target)-position) @ axes
# Common forward sections avoid rewarding a lens side with longer rays.
# The 3.5 m authority horizon is unchanged. The complete measured section,
# including returns laterally outside that circle, supplies the boundaries.
horizon = min(3., float(local[:, 0].max()))
for along in np.arange(horizon, .59, -.2):
lateral = np.sort(local[np.abs(local[:, 0]-along) <= length/2, 1])
if len(lateral) < 8:
continue
# 20 cm semantic cells: two adjacent measured cells are one interval.
# Larger unsupported intervals remain distinct passages.
groups = np.split(lateral, np.flatnonzero(np.diff(lateral) > .3)+1)
intervals = [(float(g[0]), float(g[-1])) for g in groups if len(g) >= 3]
centres=[]
for low,high in intervals:
if high-low < width:
continue
# Rank lateral positions by their worst clearance to the observed
# passage limits and to solids along the whole continuing bearing.
# Keep each obstacle at its actual longitudinal coordinate: a wall
# beside the rover must not become a fictitious barrier ahead.
lateral_samples = np.linspace(low+width/2, high-width/2,
max(2, math.ceil((high-low-width)/.05)+1))
centre_clearance = np.minimum(lateral_samples-low, high-lateral_samples)
if tree is not None:
delta = np.column_stack((np.full(len(lateral_samples),along), lateral_samples))
direction = delta / np.linalg.norm(delta,axis=1)[:,None]
radial = np.linspace(length/2, 3.5, 65)
queries = direction[:,None,:]*radial[None,:,None]
distances = tree.query(queries.reshape(-1,2))[0].reshape(len(delta),-1)
centre_clearance = np.minimum(centre_clearance, distances.min(axis=1))
# Beyond the observation horizon, extra empty width has no local
# preference. Route direction can break ties only among equally
# clear interior samples, never overwrite an obstacle score.
centre_clearance = np.minimum(centre_clearance, 3.5)
peak = centre_clearance.max()
maxima = np.flatnonzero(centre_clearance >= peak-.025)
lobes = np.split(maxima, np.flatnonzero(np.diff(maxima)>1)+1)
# Two equally clear sides of an obstacle are separate choices.
# Averaging them would put the goal back through the obstacle.
lobe = min(lobes, key=lambda ids: abs(lateral_samples[ids].mean()-(low+high)/2))
middle = float(lateral_samples[lobe].mean())
if peak >= 3.5 and route[0] > .1:
preferred = along*route[1]/route[0]
middle = float(lateral_samples[maxima[np.argmin(
np.abs(lateral_samples[maxima]-preferred))]])
xy=position+axes @ np.array([along,middle])
if np.linalg.norm(xy-position) > 3.5:
continue
centres.append(dict(xy=xy, width=high-low, along=float(along),
bounds=[low,high], yaw=yaw))
if centres:
# Topological choice: the endpoint ranks passages, never samples
# within one passage. Native planning still validates connectivity.
direction=np.asarray(target)-position
centres.sort(key=lambda c: abs(math.atan2(
direction[0]*(c['xy'][1]-position[1])-direction[1]*(c['xy'][0]-position[0]),
np.dot(direction,c['xy']-position))))
yield centres
+8 -4
View File
@@ -589,14 +589,15 @@ class ComposedInference:
calibration = inputs["source.camera.calibration"]
if observed_goals is not None:
# Every lens contributes to the same causal surface memory.
# The current range packet must still measure the proposed goal.
# This is a newly assessed spatial intent, not a timestamp renewal
# of the previous image-space goal during a survey.
# Intent uses actually measured world-space surface across
# changing body views. Native live body/support admission stays
# separate and never receives synthetic range from this memory.
return observed_goals.choose(
inputs["source.lidar"], inputs["source.pose"], target,
None if prior_was_approach else prior, excluded, self.geometry,
time.monotonic(), self.mission.goals_permitted
if isinstance(self.mission, RoutedMission) else None,
travel_direction=(self.mission.orientation_target() or {}).get("direction_xy"),
)
if calibration.get("view_role") == "survey":
observed = self.task_view_intent.recall(target, time.monotonic())
@@ -707,6 +708,9 @@ class ComposedInference:
and self.mission.can_query_arrival(pose)
and np.linalg.norm(np.asarray(pose[:2]) - arrival_target) <= 3.5
)
route_transition_nearby = bool(not recovering and arrival_target is not None
and isinstance(self.mission, RoutedMission)
and math.dist(pose[:2], arrival_target) <= 3.5)
terminal_region = bool(
nearby
and math.dist(pose[:2], arrival_target)
@@ -840,7 +844,7 @@ class ComposedInference:
if arrival_candidate or body_goal_query
else None,
"route_transition_target": arrival_target
if nearby and isinstance(self.mission, RoutedMission) else None,
if route_transition_nearby else None,
"max_speed_mps": min(self.max_speed, 0.1)
if intent["state"] == "reversing" or intent.get("corner_approach")
else min(self.max_speed, inputs.get("source.crossing-admission", {}).get("speed_limit_mps") or self.max_speed),
+76 -18
View File
@@ -1,12 +1,13 @@
"""Observed crossing-area permission for the static simulation contour.
A zebra is an area, not a set of paint islands. Admission retains a bounded
metric footprint after a measured entry stop and observed sidewalk exit. Only
metric footprint after a measured approach stop and observed sidewalk exit. Only
current ground returns inside it can override unknown/carriageway semantics.
This is not traffic right-of-way: range, body, freshness and object vetoes remain
independent. Moving traffic needs a separately qualified gap/occlusion policy.
"""
import math
from collections import OrderedDict
import numpy as np
from scipy import ndimage
@@ -19,9 +20,52 @@ class MarkedCrossing:
grid_m = .2
ground_tolerance_m = .1
def __init__(self, geometry):
def __init__(self, geometry, *, observation_range_m=12.):
if not math.isfinite(observation_range_m) or not 12 <= observation_range_m <= 40:
raise ValueError("Invalid crossing observation range")
self.observation_range_m = observation_range_m
self.geometry = geometry
self.previous = self.stopped_since = self.active = None
self.measured = OrderedDict()
def _remember(self, points, sampled, ground, pose):
"""Join actual approach views before committing one crossing footprint.
A close camera crop cannot replace the wider marking seen on approach.
This bounded static-scene semantic evidence supplies no ground/support
certificate. Current range and objects still veto every commanded sweep.
"""
near = np.linalg.norm(points[:, :2]-pose[:2], axis=1) < self.observation_range_m
for point, label in zip(points[near & ground], sampled[near & ground]):
key = tuple(np.floor(point / [.2, .2, .06]).astype(int))
if label in (1, 3):
self.measured[key] = (point.copy(), int(label))
self.measured.move_to_end(key)
elif label in (4, 5):
self.measured.pop(key, None)
for key, (point, _) in list(self.measured.items()):
if np.linalg.norm(point[:2]-pose[:2]) >= self.observation_range_m:
del self.measured[key]
while len(self.measured) > 6000:
self.measured.popitem(last=False)
def ground_mask(self, points):
"""Crossing permission for current measured ground, including blind strips.
The camera established the bounded area; range establishes which actual
returns are still on its measured plane. This neither fills missing
range nor turns elevated objects into permitted ground.
"""
points = np.asarray(points, dtype=float).reshape(-1, 3)
if self.active is None:
return np.zeros(len(points), dtype=bool)
a = self.active
relative = points-a['origin']
coords = relative[:, :2] @ a['axes']
inside = np.all(coords @ a['equations'][:, :2].T + a['equations'][:, 2] <= 1e-7, axis=1)
planar = np.abs(np.column_stack((relative[:, :2], np.ones(len(points)))) @ a['plane']
- relative[:, 2]) <= self.ground_tolerance_m
return inside & planar & np.isfinite(points).all(axis=1)
def _groups(self, local, candidate):
"""Join neighbouring paint islands in metres, never the entire raster."""
@@ -61,26 +105,33 @@ class MarkedCrossing:
if (rank < 3 or np.linalg.norm(plane[:2]) > math.tan(math.radians(self.geometry['max_slope_degrees']))
or np.max(np.abs(design @ plane - xyz[:, 2])) > self.ground_tolerance_m):
continue
planar = np.abs(np.column_stack((points[:, :2]-pose[:2], np.ones(len(points)))) @ plane
- (points[:, 2]-pose[2])) <= self.ground_tolerance_m
exit_mask = ((sampled == 1) & ground & planar
# A sidewalk exit can be higher than the painted asphalt. Its
# semantic identity anchors the crossing area, not a coplanarity
# assertion. Native contact/slope/step checks still own passage.
exit_mask = ((sampled == 1) & ground
& (local[:, 0] >= high[0]-.3) & (local[:, 0] <= high[0]+4)
& (local[:, 1] >= low[1]) & (local[:, 1] <= high[1]))
exit_points = local[exit_mask]
exit_seen = (len(exit_points) >= 3
and np.linalg.eigvalsh(np.cov(exit_points.T))[0] > 1e-4)
and np.linalg.eigvalsh(np.cov(exit_points.T))[0] > 1e-4
and np.ptp(exit_points[:, 1]) >= self.geometry['width_m'])
state.update(marked_points=len(ids), exit_points=int(exit_mask.sum()),
observed_exit=bool(exit_seen), marked_width_m=float(high[1]-low[1]))
if not exit_seen:
state['state'] = 'incomplete-crossing'
continue
if np.linalg.norm(patch, axis=1).min() > self.geometry['length_m']/2+1.25:
continue
# Semantic permission must be established before native planning
# can approach across the road's unknown-cell inflation boundary.
# Requiring proximity to paint creates a circular precondition:
# motion needs permission, permission needs the forbidden motion.
# The measured footprint, exit and stopped observation bound this
# static-scene exception; it never grants the intervening road or
# replaces current swept-body/support/object admission.
if self.stopped_since is None or now-self.stopped_since < self.stop_seconds:
return {**state, 'state': 'waiting-for-stop'}
# Connect marking to observed pedestrian entry/exit within the same
# lateral span; no permission is extrapolated into unobserved road.
entry = ((sampled == 1) & ground & planar
entry = ((sampled == 1) & ground
& (local[:, 0] >= low[0]-1.5) & (local[:, 0] < low[0])
& (local[:, 1] >= low[1]) & (local[:, 1] <= high[1]))
footprint = np.vstack((patch, local[entry | exit_mask]))
@@ -112,7 +163,6 @@ class MarkedCrossing:
height = (points-pose[:3]) @ up + self.geometry['body_contact_height_m']
distance = np.linalg.norm(local, axis=1)
ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees']))
candidate = (sampled == 3) & ground & (local[:, 0] > 0) & (distance < 12)
now = captured_at
if advance and (self.previous is None or now > self.previous[0]):
if self.previous is not None:
@@ -131,23 +181,31 @@ class MarkedCrossing:
# Completion and abandonment revoke this manoeuvre. It cannot
# expand indefinitely by following unrelated new yellow pixels.
if (relative[0] > a['exit_forward']+self.geometry['length_m']/2
or np.linalg.norm(relative) > 16):
or np.linalg.norm(relative) > max(16., self.observation_range_m+self.geometry["length_m"])):
self.active = None
self.stopped_since = None
self.measured.clear()
state = {'scope': 'static-simulation; observed crossing ground only; no traffic-priority certification',
'admitted': False, 'active': False, 'speed_limit_mps': None,
'speed_policy': 'mission-profile-with-independent-collision-limits'}
if self.active is None:
state.update(self._admit(points, local, sampled, ground, candidate, pose, axes, now))
self._remember(points, sampled, ground, pose)
if self.measured:
remembered = np.array([v[0] for v in self.measured.values()])
classes = np.array([v[1] for v in self.measured.values()])
relative = (remembered[:, :2]-pose[:2]) @ axes
distance = np.linalg.norm(relative, axis=1)
height = (remembered-pose[:3]) @ up + self.geometry['body_contact_height_m']
on_ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees']))
paint = (classes == 3) & on_ground & (relative[:, 0] > 0) & (distance < self.observation_range_m)
state.update(self._admit(remembered, relative, classes, on_ground,
paint, pose, axes, now))
else:
state['state'] = 'sidewalk'
if self.active is None:
return denied, state
a = self.active
relative = points-a['origin']
coords = relative[:, :2] @ a['axes']
inside = np.all(coords @ a['equations'][:, :2].T + a['equations'][:, 2] <= 1e-7, axis=1)
planar = np.abs(np.column_stack((relative[:, :2], np.ones(len(points)))) @ a['plane']
- relative[:, 2]) <= self.ground_tolerance_m
admitted = inside & planar & np.isin(sampled, (0, 1, 2, 3))
admitted = self.ground_mask(points) & np.isin(sampled, (0, 1, 2, 3))
# Sparse raster permissions correspond to actual visible ground returns.
# Never fill a 2D hull over an occluding object; duplicate projected
# pixels with a non-ground return are conservatively denied.
@@ -192,11 +192,16 @@ class RoutedMission(WaypointMission):
along, lateral = projection(pose[:2], segment["start_xy"], segment["end_xy"])
self.remaining = max(0.0, self.leg["length_m"] - self.completed_length - along) + lateral * (
.15 if segment.get("guidance_only") else 1.)
# Supply a stable segment endpoint. The visual/local planner already
# chooses observed intermediate goals within its own lookahead. A second
# 0.8m target here sits in the camera blind strip and can make it choose
# unrelated farther pixels instead of remembering a visible corner.
self.route_target = list(segment["end_xy"])
if self.advisory_joint():
# A map joint describes continuation, not a chassis destination.
# Preserve its direction when the measured passage runs beside it:
# a lateral offset must not turn into a 90-degree attraction as the
# rover draws level. Arrival/adjacent-support queries still use the
# actual joint and alone advance the route cursor.
direction = np.asarray(segment["end_xy"]) - segment["start_xy"]
direction /= np.linalg.norm(direction)
self.route_target = (np.asarray(pose[:2]) + 6.*direction).tolist()
def distance_to_target(self, pose, target):
return self.remaining
@@ -204,11 +209,16 @@ class RoutedMission(WaypointMission):
def orientation_target(self):
if self.route_target is None or self.route_failure or self.fault:
return None
return {
target = {
"key": self.orientation_key(f"route-{self.index}-{self.segment_index}"
+ (f"-revision-{self.route_revision}" if self.route_revision else "")),
"xy": list(self.route_target),
}
if self.advisory_joint():
segment = self.leg["segments"][self.segment_index]
direction = np.asarray(segment["end_xy"]) - segment["start_xy"]
target["direction_xy"] = (direction / np.linalg.norm(direction)).tolist()
return target
def observe_maneuver(self, maneuver, pose, seconds):
"""A bound observed local placement earns time, never a route receipt."""
@@ -325,8 +335,17 @@ class RoutedMission(WaypointMission):
return True
return super().heading_progress(pose, seconds)
def advisory_joint(self):
segments = self.leg['segments']
return bool(segments and self.segment_index < len(segments)-1
and segments[self.segment_index].get('guidance_only')
and not segments[self.segment_index].get('return_to_anchor'))
def can_query_arrival(self, pose):
return not self.route_failure and self.remaining is not None
# Intermediate advisory nodes select the next route leg; they are not
# destinations for chassis placement. Only the current support receipt
# may advance that cursor while free-space navigation owns the path.
return not self.route_failure and self.remaining is not None and not self.advisory_joint()
def arrival_target(self):
segments = self.leg["segments"]
@@ -351,7 +370,7 @@ class RoutedMission(WaypointMission):
# native planner abort must retire a measured goal near that hint;
# preserving it as task-arrival evidence pins the rover to a blocked
# intermediate point. Explicit goals and return anchors retain it.
super().retire_local_goal(None if advisory_joint else self.route_target, failed=failed)
super().retire_local_goal(None if advisory_joint else self.arrival_target(), failed=failed)
def arrival_candidate(self, pose):
return (
@@ -406,7 +425,7 @@ class RoutedMission(WaypointMission):
or inclination(pose) >= 30
or self.segment_index >= len(segments) - 1
or segments[self.segment_index].get("return_to_anchor")
or math.dist(pose[:2], self.arrival_target()) <= 0.4
or (not self.advisory_joint() and math.dist(pose[:2], self.arrival_target()) <= 0.4)
):
return None
expected = dict(
@@ -473,7 +492,12 @@ class RoutedMission(WaypointMission):
self.completed_length += math.dist(segment["start_xy"], segment["end_xy"])
self.segment_index += 1
self.last_transition_time = seconds
self.anchor = self.goal = self.best_distance = self.recovery_goal = None
# A route cursor transition changes the itinerary, not the observed
# passage. Revalidate its existing local goal against the new segment
# instead of manufacturing a fresh lateral target on every graph joint.
if self.goal is not None and not self.goal_permitted(self.goal):
self.goal = None
self.anchor = self.best_distance = self.recovery_goal = None
self.attempts = 0
self.turn_started = self.turn_goal = self.turn_best_error = None
self.state = "replanning"
@@ -300,7 +300,7 @@ def mounted_sensor_rig(robot, camera_height, *, legacy=False, continuous=False):
camera_forward_m=0.665,
camera_pitch_degrees=-30.0,
focal_length_mm=13.0,
mounts=rover_mounts(camera_height),
mounts=rover_mounts(camera_height, urban_range=continuous),
)
if continuous:
if legacy:
@@ -8,11 +8,12 @@ import copy
import math
SCHEMA = "missioncore.rover-sensor-mounts/v1"
URBAN_SCHEMA = "missioncore.rover-sensor-mounts/v2"
def rover_mounts(height=0.8):
def rover_mounts(height=0.8, *, urban_range=False):
return {
"schema_version": SCHEMA,
"schema_version": URBAN_SCHEMA if urban_range else SCHEMA,
"frame": "body-x-forward-y-left-z-up-from-ground-contact",
"calibration_status": "engineering-approximation-not-device-calibration",
"insta360": {
@@ -47,10 +48,14 @@ def rover_mounts(height=0.8):
"tilt_forward_degrees": 15.0,
"body_size_m": [0.11, 0.11, 0.20],
"elevation_degrees": [-7.0, 52.0],
"range_m": [0.3, 8.0],
# K1 publishes 40m @10% reflectivity. This ideal first-hit
# surrogate uses a bounded 20m urban horizon, not a guarantee of
# real-device range/reflectivity or its native sampling pattern.
"range_m": [0.3, 20.0 if urban_range else 8.0],
"scope": (
"MID360-published-FOV; mount-assumed; "
"bounded-uniform-sampling-not-vendor-scan-pattern; 8m-lab-horizon"
"bounded-uniform-sampling-not-vendor-scan-pattern; "
+ ("20m-urban-horizon" if urban_range else "8m-lab-horizon")
),
},
}
@@ -63,7 +68,10 @@ def validate_mounts(value):
height = value["insta360"]["body_center_m"][2]
if type(height) not in (int, float) or not math.isfinite(height) or not 0.78 <= height <= 2:
raise ValueError("Invalid sensor mounting height")
if value != rover_mounts(height):
schema = value.get("schema_version")
if schema not in (SCHEMA, URBAN_SCHEMA):
raise ValueError("Unsupported sensor mount version")
if value != rover_mounts(height, urban_range=schema == URBAN_SCHEMA):
raise ValueError("Unsupported or changed sensor mount calibration")
except (KeyError, TypeError, IndexError) as exc:
raise ValueError("Invalid sensor mounts") from exc
+202 -3
View File
@@ -104,7 +104,7 @@ def test_new_prohibition_revokes_goal_and_cannot_be_refreshed_by_read(selector):
assert selector.choose(points, pose, target, goal, (), GEOMETRY, 40) is None
def test_current_range_corridor_and_exclusions_revoke_retained_goal(selector):
def test_corridor_and_exclusions_revoke_retained_goal_but_range_crop_does_not(selector):
points, pose, target, _, _ = road()
selector.observe(np.column_stack((points, np.ones(len(points)))), 0, pose)
goal = selector.choose(points, pose, target, None, (), GEOMETRY, .1)
@@ -113,7 +113,7 @@ def test_current_range_corridor_and_exclusions_revoke_retained_goal(selector):
assert result is not None and allowed(np.array([result]))[0]
assert selector.choose(points, pose, target, goal, [goal], GEOMETRY, .2) != goal
absent = points[np.linalg.norm(points - goal, axis=1) > .5]
assert selector.choose(absent, pose, target, goal, (), GEOMETRY, .2) != goal
assert selector.choose(absent, pose, target, goal, (), GEOMETRY, .2) == goal
def test_chassis_width_is_enforced_across_accumulated_views(selector):
@@ -334,7 +334,10 @@ def test_clear_retained_intent_does_not_recompute_alternative_approaches(selecto
# New nearby geometry must still cause the alternatives to be evaluated.
selector.observe_navigation(clearance_receipt(position, [[1.6, 0.]]), position, 1, 'run', 1.1)
assert selector.choose(points, position, target, goal, (), GEOMETRY, 1.2) != goal
assert max(sizes) > 1
changed = selector.choose(points, position, target, goal, (), GEOMETRY, 1.2)
assert changed is not None
assert evaluate(np.array([changed]), position, GEOMETRY, 1.2)[0] > (
evaluate(np.array([goal]), position, GEOMETRY, 1.2)[0] + .1)
def test_clearance_is_bounded_below_exact_continuous_segments(selector):
@@ -455,3 +458,199 @@ def test_shared_bearing_queries_conservatively_bound_common_horizon(selector):
expected.append(np.min(np.linalg.norm(obstacles-(a+projection[:, None]*(b-a)), axis=1)))
assert np.all(actual <= np.asarray(expected)+1e-10)
assert np.max(np.asarray(expected)-actual) < .041
@pytest.mark.parametrize('yaw,shift', [(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
def test_route_endpoint_can_select_a_passage_but_cannot_move_its_centre(selector,yaw,shift):
points,pose,_,_,rotation=road(yaw,shift)
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
goals=[]
for endpoint in ([8,-5],[8,0],[8,5],[675,-9]):
goal=selector.choose(points,pose,np.array(shift)+rotation@endpoint,None,(),GEOMETRY,1.)
assert goal is not None
goals.append(goal)
assert all(np.array_equal(goal,goals[0]) for goal in goals)
assert abs(((np.array(goals[0][:2])-shift)@rotation)[1])<.1
def test_route_selects_the_relevant_observed_branch(selector):
pose=[0,0,.37,0,0,0,1]
points=np.array([[x,y,0.] for x in np.arange(.4,3.5,.07)
for y in np.arange(-3.,3.01,.07) if abs(y)>1.])
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
for sign in [-1,1]:
goal=selector.choose(points,pose,[8,sign*5],None,(),GEOMETRY,1.)
assert goal is not None and sign*goal[1]>1.5
assert np.min(np.linalg.norm(points-goal,axis=1))<1e-9
@pytest.mark.parametrize("heading", [-25, 0, 25])
@pytest.mark.parametrize("yaw,shift", [(0,(0,0)),(73,(42,-17))])
def test_corridor_boundaries_do_not_rotate_with_the_rover(selector,heading,yaw,shift):
_,_,_,_,rotation=road(yaw,shift)
xy=np.array([[x,y] for x in np.arange(.4,6.,.07)
for y in np.arange(-1.5,1.51,.07)])
points=np.c_[xy@rotation.T+shift,np.zeros(len(xy))]
angle=math.radians(yaw+heading)
pose=[*shift,.37,0,0,math.sin(angle/2),math.cos(angle/2)]
selector.observe(np.c_[points,np.ones(len(points))],1,pose)
wall=np.array([[x,y] for x in np.arange(-.5,6.,.07) for y in [-1.6,1.6]])
selector.observe_navigation(clearance_receipt(pose,(wall@rotation.T+shift).tolist()),
pose,1,'run',1.)
goal=selector.choose(points,pose,np.array(shift)+rotation@[12,0],None,(),GEOMETRY,1.1)
assert goal is not None
local=(np.array(goal[:2])-shift)@rotation
assert local[0]>2.5 and abs(local[1])<.2
def test_symmetric_obstacle_does_not_average_two_passages_through_its_centre(selector):
points,pose,target,_,_=road()
selector.observe(np.c_[points,np.ones(len(points))],1,pose)
selector.observe_navigation(clearance_receipt(pose,[[1.6,0.]]),pose,1,'run',1.)
goal=selector.choose(points,pose,target,None,(),GEOMETRY,1.1)
assert goal is not None and abs(goal[1])>.35
assert selector.approach_clearance(np.array([goal]),pose,GEOMETRY,1.1)[0]>.2
@pytest.mark.parametrize("angle,shift", [(0,(0,0)), (73,(42,-17)), (-138,(-250,52))])
def test_wide_passage_does_not_erase_obstacle_clearance_for_route_direction(selector,angle,shift):
_,pose,_,_,rotation=road(angle,shift)
xy=np.array([[x,y] for x in np.arange(.4,6.,.07)
for y in np.arange(-4.,4.01,.07)])
points=np.c_[xy@rotation.T+shift,np.zeros(len(xy))]
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
hazard=(np.array([[2.,-1.3]])@rotation.T+shift).tolist()
selector.observe_navigation(clearance_receipt(pose,hazard),pose,1,'run',1.)
goal=selector.choose(points,pose,np.array(shift)+rotation@[8,-5],None,(),GEOMETRY,1.1)
assert goal is not None
assert selector.approach_clearance(np.array([goal]),pose,GEOMETRY,1.1)[0] > 1.5
assert ((np.array(goal[:2])-shift)@rotation)[1] > 0
@pytest.mark.parametrize("angle,shift", [(0,(0,0)), (73,(42,-17)), (-138,(-250,52))])
def test_selected_passage_survives_range_crop_without_creating_new_sensor_support(selector,angle,shift):
points,pose,target,_,rotation=road(angle,shift)
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
goal=selector.choose(points,pose,target,None,(),GEOMETRY,1.)
stamps=dict(selector.surface.cells)
# The same world goal leaves the live metric crop during a body turn.
local=(points[:,:2]-shift)@rotation
crop=points[local[:,1]>.7]
saved=crop.copy()
turn=math.radians(angle+20)
turned=[*pose[:3],0,0,math.sin(turn/2),math.cos(turn/2)]
retained=selector.choose(crop,turned,target,goal,(),GEOMETRY,2.)
assert retained==goal
assert selector.evidence['source']=='retained-observed-passage'
assert selector.evidence['oldest_surface_age_seconds']==1.
assert dict(selector.surface.cells)==stamps
np.testing.assert_array_equal(crop,saved)
# A new intention uses the same observed passage, even after the previous
# goal is reached. This is old measured evidence, not new sensor support.
replacement=selector.choose(crop,turned,target,None,(),GEOMETRY,2.,
travel_direction=rotation@[1.,0.])
assert replacement is not None
assert abs(((np.array(replacement[:2])-shift)@rotation)[1]) < .13
assert dict(selector.surface.cells)==stamps
np.testing.assert_array_equal(crop,saved)
# Without the earlier full-width observation, the same narrow crop cannot
# invent a traversable destination.
unseen=type(selector)()
unseen.observe(np.c_[crop,np.ones(len(crop))],1.,turned)
assert unseen.choose(crop,turned,target,None,(),GEOMETRY,2.) is None
# Current obstacle geometry can still revoke that retained intent.
obstacle=(np.asarray(shift)+rotation@[1.6,0.]).tolist()
selector.observe_navigation(clearance_receipt(turned,[obstacle]),turned,1,'run',2.)
assert selector.choose(crop,turned,target,goal,(),GEOMETRY,2.1)!=goal
@pytest.mark.parametrize('angle,shift', [(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
def test_local_intent_geometry_does_not_rotate_with_chassis(selector,angle,shift):
_,pose,target,_,rotation=road(angle,shift)
xy=np.array([[x,y] for x in np.arange(-4.,6.01,.08)
for y in np.arange(-1.6,1.61,.08)])
points=np.c_[xy@rotation.T+shift,np.zeros(len(xy))]
geometry={**GEOMETRY,'length_m':1.3636,'max_step_m':.1}
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
reference=selector.choose(points,pose,target,None,(),geometry,2.,
travel_direction=rotation@[1.,0.])
assert reference is not None
for offset in [-45,-30,-15,15,30,45]:
heading=math.radians(angle+offset)
turned=[*pose[:3],0,0,math.sin(heading/2),math.cos(heading/2)]
chosen=selector.choose(points,turned,target,None,(),geometry,2.,
travel_direction=rotation@[1.,0.])
np.testing.assert_allclose(chosen,reference,atol=1e-8)
def test_memory_goal_selection_does_not_refresh_expired_or_revoked_evidence(selector):
points,pose,target,_,_=road()
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
crop=points[points[:,1]>.7]
assert selector.choose(crop,pose,target,None,(),GEOMETRY,2.) is not None
original=dict(selector.surface.cells)
# Move the memory's retention centre away, making these old samples expire.
selector.surface.position=np.array([100.,100.])
assert selector.choose(crop,pose,target,None,(),GEOMETRY,40.) is None
assert dict(selector.surface.cells)==original
selector.observe(np.c_[points,np.zeros(len(points))],41.,pose)
assert selector.choose(crop,pose,target,None,(),GEOMETRY,41.) is None
def test_explicit_route_direction_is_separate_from_remote_goal(selector):
points,pose,_,_,_=road()
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
goals=[selector.choose(points,pose,target,None,(),GEOMETRY,2.,
travel_direction=[1.,0.])
for target in ([8.,-5.],[8.,0.],[8.,5.],[675.,-9.])]
assert goals[0] is not None
assert all(np.array_equal(goal,goals[0]) for goal in goals)
@pytest.mark.parametrize('angle,shift', [(0,(0,0)),(73,(42,-17)),(-138,(-250,52))])
def test_observed_through_passage_advances_without_chasing_a_new_lateral_centre(selector,angle,shift):
_,pose,_,_,rotation=road(angle,shift)
xy=np.array([[x,y] for x in np.arange(-1.,9.01,.08)
for y in np.arange(-2.5,4.01,.08)])
points=np.c_[xy@rotation.T+shift,np.zeros(len(xy))]
geometry={**GEOMETRY,'length_m':1.3636,'max_step_m':.1}
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
goal=[*(np.asarray(shift)+rotation@[3.,0.]),0.]
original=dict(selector.surface.cells)
# A widened/partially observed section changes its instantaneous midpoint.
# The already selected, clear through-passage must keep its lateral line
# while advancing the local horizon as the chassis makes forward progress.
for forward in [1.,1.7,2.4,3.1]:
position=np.asarray(shift)+rotation@[forward,.25]
moved=[*position,.37,0,0,math.sin(math.radians(angle-10)/2),math.cos(math.radians(angle-10)/2)]
goal=selector.choose(points,moved,position+rotation@[6.,0.],goal,(),geometry,2.,
travel_direction=rotation@[1.,0.])
assert goal is not None
local=(np.asarray(goal[:2])-shift)@rotation
assert local[0]-forward>2.7
assert abs(local[1])<.15
assert np.min(np.linalg.norm(points-goal,axis=1))<1e-9
assert dict(selector.surface.cells)==original
def test_through_passage_requires_measured_permission_and_current_clearance(selector):
points,pose,target,_,_=road()
# The first continuation is observed; its farther extrapolation is not.
selector.observe(np.c_[points,np.ones(len(points))],1.,pose)
prior=[1.5,0.,0.]
chosen=selector.choose(points,pose,target,prior,(),GEOMETRY,1.1,travel_direction=[1.,0.])
assert chosen is not None and chosen[0]>2.7 and abs(chosen[1])<.15
assert np.min(np.linalg.norm(points-chosen,axis=1))<1e-9
# A pole on the continued line defeats retention before physical contact.
selector.observe_navigation(clearance_receipt(pose,[[2.3,0.]]),pose,1,'run',1.1)
blocked=selector.choose(points,pose,target,prior,(),GEOMETRY,1.2,travel_direction=[1.,0.])
assert blocked is None or abs(blocked[1])>.3
# An explicit mission exclusion still owns the candidate region.
limited=selector.choose(points,pose,target,prior,(),GEOMETRY,1.2,
lambda p:p[:,0]<2.,travel_direction=[1.,0.])
assert limited is None or limited[0]<2.
# No remembered label can create unmeasured geometry beyond this cloud.
selector.clearance_observation=None
moved=[2.7,0.,.37,0.,0.,0.,1.]
end=selector.choose(points,moved,[8.,0.],chosen,(),GEOMETRY,1.3,travel_direction=[1.,0.])
assert end is None or end[0]<=points[:,0].max()
+21
View File
@@ -256,3 +256,24 @@ def test_coordinator_inputs_do_not_import_numpy_pydantic_or_core():
env={**os.environ, "PYTHONPATH": str(ROOT / "src")},
check=True,
)
def test_extended_lidar_horizon_is_versioned_and_old_mounts_stay_immutable():
from k1link.simulation.ai_polygon.sensor_mounts import rover_mounts, validate_mounts
from k1link.simulation.ai_polygon.run_inputs import mounted_sensor_rig, validate_sensor_rig
legacy = rover_mounts(.8)
current = mounted_sensor_rig(select_robot("dcd006-v020"), .8, continuous=True)
assert legacy["schema_version"] == "missioncore.rover-sensor-mounts/v1"
assert legacy["k1"]["range_m"] == [.3, 8.]
assert current["mounts"]["schema_version"] == "missioncore.rover-sensor-mounts/v2"
assert current["mounts"]["k1"]["range_m"] == [.3, 20.]
assert validate_mounts(legacy) == legacy
validate_sensor_rig(current)
# Archived v4 camera captures keep their original, explicit v1 range.
old_rig = copy.deepcopy(current); old_rig["mounts"] = legacy
validate_sensor_rig(old_rig)
assert digest(old_rig) != digest(current)
for spec in (legacy, current["mounts"]):
altered = copy.deepcopy(spec); altered["k1"]["range_m"][1] += 1.
with pytest.raises(ValueError, match="changed sensor mount"):
validate_mounts(altered)
+105 -4
View File
@@ -89,7 +89,8 @@ def test_grouping_does_not_join_distant_markings(module):
assert sorted(map(len, groups)) == [2, 4]
def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module):
@pytest.mark.parametrize("half_hidden", [False, True])
def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module, half_hidden):
composition = importlib.import_module('continuous_composition')
labels, points, pixels, pose = scene(); g = gate(module)
enter(g, (labels, points, pixels, pose))
@@ -100,10 +101,12 @@ def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module):
obj.crossing = g
obj.optics = SimpleNamespace(lens_axes=np.array([np.eye(3)]),
rectify_forward=lambda *a: (np.zeros((600,800,3),np.uint8), None))
obj.camera_source = SimpleNamespace(indices=lambda *a:pixels,
semantic_pixels=lambda *a:np.ones(len(points),bool))
visible = points[:, 1] >= 0 if half_hidden else np.ones(len(points), bool)
observed_pixels = tuple(p[visible] for p in pixels)
obj.camera_source = SimpleNamespace(indices=lambda *a:observed_pixels,
semantic_pixels=lambda *a:np.ones(int(visible.sum()),bool))
monkeypatch.setattr(composition, 'project', lambda *a:(None, np.zeros(len(points)),
np.zeros(len(points)), np.ones(len(points),bool)))
np.zeros(len(points)), visible))
obj.models = SimpleNamespace(labels={}, surface=lambda rgb:{'segmentation.labels':labels,
'segmentation.surface':np.isin(labels, (1,2,3)), 'segmentation.known':labels != 0})
observation = dict(calibration={'lens_axes':[np.eye(3)], 'intrinsics':[1,1,1,1]},
@@ -118,3 +121,101 @@ def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module):
permitted_points = set(map(tuple, samples[samples[:,3] == 1, :3]))
assert all(tuple(p) in permitted_points for p in points[expected_unknown])
assert not any(tuple(p) in permitted_points for p in points[np.abs(points[:,1]) > 1.1])
if half_hidden:
hidden_ground = g.ground_mask(points) & ~visible
assert hidden_ground.any()
assert all(tuple(p) in permitted_points for p in points[hidden_ground])
def test_approach_measurements_survive_a_narrow_near_camera_view(module):
labels, points, pixels, pose = scene(); g = gate(module)
# See the complete marking from farther away, without granting admission.
far = pose.copy(); far[0] = -3
assert not g.observe(labels, points, pixels, far, 10.)[1]['admitted']
# At the entry, the crop sees only a narrow strip, not the crossing width.
seen = np.abs(points[:, 1]) < .3
narrow = (labels, points[seen], tuple(p[seen] for p in pixels), pose)
g.observe(*narrow, 11.)
g.observe(*narrow, 11.4)
_, status = g.observe(*narrow, 11.8)
assert status['admitted']
intended = (points[:, 0] > 1.1) & (points[:, 0] < 6) & (np.abs(points[:, 1]) < .9)
assert g.ground_mask(points)[intended].all()
# A memory-free crop does not have enough width to invent a crossing.
assert not enter(gate(module), narrow)[1]['admitted']
def test_exit_sidewalk_need_not_be_coplanar_with_road(module):
data = scene(); labels, points, pixels, _ = data
sidewalk = labels[pixels] == 1
points[sidewalk, 2] = .15
mask, status = enter(gate(module), data)
assert status['admitted']
assert mask[pixels][labels[pixels] == 3].all()
# Permission is not a certificate that this physical step can be crossed.
# Raised exit ground still relies on its own sidewalk and support evidence.
assert not mask[pixels][sidewalk].any()
def test_small_exit_fragment_is_not_a_rover_width_exit(module):
data = scene(); labels, points, pixels, _ = data
bad = (points[:, 0] >= 6.5) & (np.abs(points[:, 1]) >= .3)
labels[pixels[0][bad], pixels[1][bad]] = 0
_, state = enter(gate(module), data)
assert state['exit_points'] > 3
assert not state['admitted'] and not state['observed_exit']
def test_retained_crossing_does_not_admit_new_ground_above_or_outside_it(module):
g = gate(module); assert enter(g, scene())[1]['admitted']
points = np.array([[3, 0, 0], [3, 0, .4], [3, 2, 0], [3, 0, -1.]])
assert g.ground_mask(points).tolist() == [True, False, False, False]
def test_wide_crossing_requires_measured_exit_within_declared_horizon(module):
x, y = np.meshgrid(np.arange(.4, 18., .2), np.arange(-1., 1.01, .2), indexing="ij")
points = np.column_stack((x.ravel(), y.ravel(), np.zeros(x.size)))
pixels = np.unravel_index(np.arange(len(points)), (512, 512))
labels = np.zeros((512, 512), np.uint8)
paint = (points[:,0] >= 1.) & (points[:,0] < 15.5) & (np.mod(points[:,0]+.01, 1.) < .45)
sidewalk = (points[:,0] < 1.) | (points[:,0] >= 16.)
labels[pixels[0][paint], pixels[1][paint]] = 3
labels[pixels[0][sidewalk], pixels[1][sidewalk]] = 1
data = labels, points, pixels, np.array([0.,0.,.37,0.,0.,0.,1.])
geometry = gate(module).geometry
assert not enter(module.MarkedCrossing(geometry), data)[1]["admitted"]
current = module.MarkedCrossing(geometry, observation_range_m=20.)
assert enter(current, data)[1]["admitted"]
# Enlarging the observation domain cannot manufacture an unobserved exit.
near = np.linalg.norm(points[:,:2], axis=1) <= 8.
cropped = labels, points[near], tuple(p[near] for p in pixels), data[-1]
assert not enter(module.MarkedCrossing(geometry, observation_range_m=20.), cropped)[1]["admitted"]
current = module.MarkedCrossing(geometry, observation_range_m=20.)
labels[pixels[0][points[:,0]>=16.], pixels[1][points[:,0]>=16.]] = 0
assert not enter(current, data)[1]["admitted"]
def test_observed_crossing_can_be_admitted_before_unknown_inflation_boundary(module):
labels, points, pixels, pose = scene()
# The native planner may stop before a painted stripe because the road
# around it is still unknown. Permission must not require first entering
# that denied area. Use an offset entry; no extra ground is supplied.
points[:, 0] += 1.6
g = gate(module)
mask, state = enter(g, (labels, points, pixels, pose))
assert state['admitted']
assert mask[pixels][labels[pixels] == 3].all()
# The permission remains on the reconstructed area, not the approach gap,
# unrelated road, or an object standing on the admitted crossing.
probe = np.array([[1., 0., 0.], [4., 0., 0.], [4., 2., 0.], [4., 0., .5]])
assert g.ground_mask(probe).tolist() == [False, True, False, False]
def test_more_distant_crossing_still_requires_a_measured_stop(module):
labels, points, pixels, pose = scene()
points[:, 0] += 1.6
g = gate(module)
for index in range(5):
pose[0] = .1 * index
mask, state = g.observe(labels, points, pixels, pose, 10. + .4*index)
assert not state['admitted'] and not mask.any()
+22
View File
@@ -83,3 +83,25 @@ settings.persistent = false
assert Path(prepare_experience(sdk, out)).read_bytes() == first
python.write_text(python.read_text().replace("6.1.0", "6.2.0"))
with pytest.raises(RuntimeError, match="Unsupported"): prepare_experience(sdk, out)
@pytest.mark.parametrize("maximum", [8., 20.])
def test_lidar_observation_horizon_comes_from_versioned_sensor_spec(maximum):
class Query:
def __init__(self): self.limits = []
def raycast_closest(self, origin, direction, distance, bothSides):
self.limits.append(distance)
if len(self.limits) == 1 and distance >= 14.:
return dict(hit=True, position=[14., 0., 0.], collision="/World/Exit")
return dict(hit=False)
q = Query(); ranges = []
observed, ends, _, paths = mounted_range_returns(q, np.zeros(3),
np.array([[1.,0.,0.],[0.,1.,0.]]), "k1", dict(range_m=[.3,maximum]), np.ones(2),
organized_ranges=ranges)
assert q.limits == [maximum, maximum]
assert len(observed) == int(maximum >= 14.)
assert paths == (["/World/Exit"] if maximum >= 14. else [])
np.testing.assert_array_equal(ranges[0], [14. if maximum >= 14. else maximum, maximum])
assert ends[-1].tolist() == [0., maximum, 0.]
# A missing return only contributes a clearing ray, never supporting ground.
assert not any(np.array_equal(p, ends[-1]) for p in observed)
+135 -2
View File
@@ -17,6 +17,7 @@ def bridge(monkeypatch):
root = Path(__file__).parents[1] / 'simulation/ai-polygon'
monkeypatch.syspath_prepend(str(root))
monkeypatch.syspath_prepend(str(root / 'nav2'))
from navigation.arrival_approach import validate_orientation, orientation_identity
from navigation.footprint import Footprint
from navigation.route_observation import route_observation
from route_support import route_support
@@ -24,8 +25,9 @@ def bridge(monkeypatch):
tree = ast.parse((root / 'nav2/server.py').read_text())
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Navigation')
scope = dict(np=np, math=math, time=time, route_support=route_support,
route_observation=route_observation, validate_orientation=lambda _: None,
alignment_angle=lambda *args: None)
route_observation=route_observation, validate_orientation=validate_orientation,
orientation_identity=orientation_identity,
alignment_angle=lambda *args, **kwargs: None)
exec(compile(ast.Module(body=[cls], type_ignores=[]), str(root / 'nav2/server.py'), 'exec'), scope)
navigation = scope['Navigation'].__new__(scope['Navigation'])
navigation.failure = None
@@ -219,3 +221,134 @@ def test_planner_rejection_revokes_inflight_command_before_native_stop(moving_br
result = navigation.tick(dict(pose=value['pose'], pose_age_seconds=0., measured_twist=[.4,0.,0.]))
assert result == dict(speed_mps=0., yaw_rate_rps=0., reason='changed-path')
assert seen == [None]
@pytest.mark.parametrize('changed', [False, True])
def test_directional_route_translation_preserves_owner_but_turn_revokes_it(moving_bridge, changed):
navigation, value, _, seen = moving_bridge
orientation = dict(key='route-0-1', xy=[6., 0.], direction_xy=[1., 0.])
navigation.path_context = navigation.forward_context(value, orientation)
# The rover moves one metre. Its six-metre bearing endpoint moves too.
# Repeated sensor refreshes must not cancel FollowPath or its live command.
value['orientation_target'] = {**orientation, 'xy': [7., 0.]}
if changed:
value['orientation_target'].update(xy=[1., 6.], direction_xy=[0., 1.])
result = navigation.plan(value)
assert result['controller_generation'] == (8 if changed else 7)
assert seen[0]['continuing'] is (not changed)
assert (seen[0]['command'] is not None) is (not changed)
@pytest.mark.parametrize('direction', [None, [0., 0.], [2., 0.], [True, 0.], [float('nan'), 0.], [1.]])
def test_orientation_direction_must_be_finite_unit_vector(bridge, direction):
navigation, _, value = bridge
value['orientation_target'] = dict(key='route-0-1', xy=[6., 0.], direction_xy=direction)
with pytest.raises(ValueError, match='orientation direction'):
navigation.plan(value)
@pytest.mark.parametrize('changed', [False, True])
def test_view_spin_is_not_restarted_by_translated_direction_endpoint(moving_bridge, changed):
navigation, value, _, _ = moving_bridge
identity = navigation._plan.__globals__['orientation_identity']
orientation = dict(key='route-0-1', xy=[6., 0.], direction_xy=[1., 0.])
navigation.action_key = ('spin', *identity(orientation))
calls = []
navigation.node.spin = lambda *args: calls.append(args)
value.update(translation_allowed=False,
orientation_target={**orientation, 'xy': [7., 0.]})
if changed:
value['orientation_target'].update(xy=[1., 6.], direction_xy=[0., 1.])
result = navigation.plan(value)
assert len(calls) == int(changed)
assert result['controller_generation'] == (8 if changed else 7)
@pytest.fixture
def rejected_extension(moving_bridge):
navigation, value, planned, seen = moving_bridge
path, _ = navigation.node.plan(value['pose'], [3., 0., 0.], 0.)
navigation.path, navigation.path_planned_at = path, time.monotonic()
navigation.node.plan = lambda *args: (None, 6)
return navigation, value, path, seen
def test_rejected_extension_preserves_live_action_and_admits_current_observation(rejected_extension):
navigation, value, path, seen = rejected_extension
accepted, stopped = [], []
navigation.control.accept = lambda *args, **kwargs: accepted.append((args, kwargs))
navigation.node.stop = lambda: stopped.append(True)
result = navigation.plan(value)
assert result['controller_goal'] == ('path', (3., 0.), 1.)
assert result['controller_generation'] == 7
assert result['refinement_result'] == dict(status='aborted', goal_xy=[4., .2],
executing_goal_xy=[3., 0.])
assert 'planning_result' not in result and 'action_result' not in result
assert result['status'] == 'path' and result['speed_mps'] == .4
assert navigation.path is path and not seen and not stopped
observed = navigation.terrain.observe(value)
assert accepted[0][0][0] is value
assert accepted[0][0][2] is observed['terrain']
assert accepted[0][1]['collision_terrain'] is observed['collision_terrain']
# Completion stays terminal; the rejection must not resurrect FollowPath.
navigation.node.terminal.set_result(SimpleNamespace(status=4))
value['goal'] = [3., 0., 0.]
done = navigation.plan(value)
assert done['action_result']['status'] == 'succeeded'
assert done['speed_mps'] == 0. and not seen
@pytest.mark.parametrize('condition', [
'same-goal', 'leg', 'direction', 'limit', 'recovery', 'unbound', 'placement',
'same-placement', 'discrete', 'completed', 'aborted', 'no-command',
'stale-command', 'short-path', 'cancelled-planning'])
def test_rejected_extension_cannot_preserve_invalid_or_unrelated_action(rejected_extension, condition):
navigation, value, _, seen = rejected_extension
if condition == 'same-goal': value['goal'] = [3., 0., 0.]
elif condition == 'leg': value['orientation_target']['key'] = 'route-1-2'
elif condition == 'direction': value['orientation_target']['xy'] = [20., 4.]
elif condition == 'limit': value['max_speed_mps'] = .3
elif condition == 'recovery': value['recovery_orientation'] = True
elif condition == 'unbound': value['orientation_target'] = None
elif condition in {'placement', 'same-placement'}:
value['arrival_target'] = [20., 0.]
if condition == 'same-placement':
navigation.path_context = navigation.forward_context(value, value['orientation_target'])
elif condition == 'discrete': value['continuous'] = False
elif condition in {'completed', 'aborted'}:
def plan(*args):
navigation.node.terminal.set_result(SimpleNamespace(status=4 if condition == 'completed' else 6))
return None, 6
navigation.node.plan = plan
elif condition == 'no-command': navigation.node.native_command = lambda: None
elif condition == 'stale-command': navigation.node.native_command = lambda: (time.monotonic()-1., .4, .02)
elif condition == 'short-path': navigation.path.poses = navigation.path.poses[:1]
else: navigation.node.plan = lambda *args: (None, 5)
navigation.path_planned_at = float('-inf')
stopped = []
navigation.node.stop = lambda: stopped.append(navigation.native_command())
result = navigation.plan(value)
assert result['status'] == 'blocked' and result['speed_mps'] == result['yaw_rate_rps'] == 0.
assert result['diagnostic']['failure'] == 'no-path'
assert 'refinement_result' not in result and not seen
assert stopped == [None] and navigation.command_generation == 8
def test_continued_path_uses_live_collision_gate_after_refinement_failure(rejected_extension):
from navigation.continuous_control import ContinuousControl
from navigation.support_policy import SupportPolicy
navigation, value, _, _ = rejected_extension
observed = navigation.terrain.observe(value)
value['points'] = observed['terrain'][:, :3]
gate = ContinuousControl(navigation.monitor, SupportPolicy(navigation.monitor),
lambda _: None, lambda *_: None, navigation.native_command, native_only=True, body_top_m=1.)
navigation.control = gate
navigation.plan(value)
tick = dict(pose=value['pose'], pose_age_seconds=0., perception_age_seconds=0.,
enabled=True, observation_id=value['observation_id'], speed_mps=0.)
assert gate.tick(tick)['speed_mps'] > 0.
gate.observe(dict(geometry_age_seconds=0., range_sequence=[1, 2],
points=np.r_[value['points'], [[.525, 0., .5]]]))
result = gate.tick(tick)
assert result['speed_mps'] == result['yaw_rate_rps'] == 0.
assert result['reason'] == 'obstacle'
+68
View File
@@ -282,3 +282,71 @@ def test_component_chain_cannot_reverse_a_one_way_edge():
'edge_ids':list(reversed(segment['edge_ids']))}
with pytest.raises(ValueError,match='oriented graph chain'):
blocked_route_piece(inputs['routing'],broken,[[1.,0.,0.]],[3.,0.])
def test_advisory_joint_preserves_local_passage_intent_for_revalidation():
from k1link.simulation.ai_polygon.route_mission import RoutedMission
*_,inputs,_=fixture()
inputs['routing']['blocked_edges']=['0','1','2']
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
behavior={'max_speed_mps':1.})
mission=RoutedMission(inputs)
mission.route_observation([0,0,0,0,0,0,1],0.)
mission.goal=[.5,4.8,0.]
before=list(mission.goal)
mission.advance_segment([0.,4.,0.,0.,0.,0.,1.],5.)
assert mission.segment_index==1
assert mission.goal==before
# It remains an intent. The subsequent selector can revoke it immediately.
chosen=[]
def reject(target,prior,excluded):
chosen.append(prior)
return None
goal,intent=mission.update([0.,4.,0.,0.,0.,0.,1.],5.1,reject)
assert before in chosen
assert goal is None and intent['state']=='no-road'
def test_advisory_joint_is_never_an_exact_arrival_destination():
from k1link.simulation.ai_polygon.route_mission import RoutedMission
*_,inputs,_=fixture()
inputs['routing']['blocked_edges']=['0','1','2']
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
behavior={'max_speed_mps':1.})
mission=RoutedMission(inputs)
pose=[0.,0.,0.,0.,0.,0.,1.]
mission.route_observation(pose,0.)
assert not mission.can_query_arrival(pose)
# A declared final destination still requires exact whole-body arrival.
mission.segment_index=len(mission.leg['segments'])-1
mission.route_observation(pose,0.)
assert mission.can_query_arrival(pose)
@pytest.mark.parametrize("offset", [-3.,0.,3.])
def test_advisory_joint_is_a_direction_not_lateral_attraction(offset):
from k1link.simulation.ai_polygon.route_mission import RoutedMission
*_,inputs,_=fixture()
inputs['routing']['blocked_edges']=['0','1','2']
inputs.update(sensors={'schema_version':'missioncore.simulation-sensor-rig/v4'},
behavior={'max_speed_mps':1.})
mission=RoutedMission(inputs)
mission.route_observation([0.,0.,0.,0.,0.,0.,1.],0.)
# The actual open passage can pass a map joint on either side. Neither
# the goal selector nor the stopped view acquisition should face the joint.
for t,y in enumerate([2.,4.,5.,6.],start=10):
pose=[offset,y,0.,0.,0.,0.,1.]
mission.route_observation(pose,float(t*4))
direction=np.array(mission.route_target)-pose[:2]
assert direction[0] == pytest.approx(0.) and direction[1] > 3.5
assert mission.orientation_target()['xy'] == mission.route_target
assert mission.arrival_target() == [0.,5.]
assert mission.segment_index == 0 # direction is not a transition receipt
assert not mission.can_query_arrival(pose)
# A required return anchor and final mission destination retain exact XY.
mission.leg['segments'][0]['return_to_anchor']=True
mission.route_observation(pose,60.)
assert mission.route_target == [0.,5.]
mission.segment_index=len(mission.leg['segments'])-1
mission.route_observation(pose,61.)
assert mission.route_target == mission.leg['goal_xy']