Files

1215 lines
60 KiB
Python

"""Installed provider adapters executed in shared composition dependency order."""
import hashlib
import http.client
import json
import math
import time
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from pathlib import Path
import numpy as np
from inference_preview import InferencePreview
from navigation.footprint import Footprint
from navigation.observed_goals import ObservedGoals
from k1link.simulation.ai_polygon.camera_optics import TaskViewIntent
from k1link.simulation.ai_polygon.composition import compose
from k1link.simulation.ai_polygon.contracts import Decision
from k1link.simulation.ai_polygon.detection_range import detection_proximity
from k1link.simulation.ai_polygon.driving_profiles import permitted_surface
from k1link.simulation.ai_polygon.evidence_arrays import save_arrays
from k1link.simulation.ai_polygon.inference import ModelInference
from k1link.simulation.ai_polygon.mission_policy import OBSERVED_ARRIVAL_GOAL_RADIUS_M
from k1link.simulation.ai_polygon.route_graph import build_route
from k1link.simulation.ai_polygon.route_mission import RoutedMission, mission_for_inputs
from k1link.simulation.ai_polygon.run_inputs import (
MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA, resolve_run_inputs,
)
from k1link.simulation.ai_polygon.run_robot import resolve_run_robot
from k1link.simulation.ai_polygon.source_projection import source_for_rig
def project(points, calibration, source):
if hasattr(source, "project"):
return source.project(points, calibration)
rotation = np.asarray(calibration["rotation"], dtype=np.float64).reshape(3, 3)
local = (points - np.asarray(calibration["origin"])) @ rotation
front = local[:, 0] > 0.1
depth = np.maximum(local[:, 0], 0.1)
fx, fy, cx, cy = calibration["intrinsics"]
u = cx - fx * local[:, 1] / depth
v = cy - fy * local[:, 2] / depth
visible = front & source.visible(u, v)
return local, u, v, visible
def current_body_destination(result, pose, target, seconds, inputs_sha256, geometry=None):
"""A fresh body-placement plan does not consume the older visual goal.
This recognizes an already admitted command, never grants motion. Both
destination and swept support must belong to this exact range transaction;
semantic memory keeps its independent evidence/expiry policy on the server.
"""
arrival = result.get("arrival") or {}
destination = arrival.get("destination") or {}
selected = result.get("arrival_goal") or {}
support = result.get("diagnostic", {}).get("motion_support") or {}
observation = dict(
pose=list(pose), simulation_time_seconds=seconds, execution_inputs_sha256=inputs_sha256
)
goal = selected.get("goal", [])
intermediate = selected.get("kind") == "observed-approach"
in_region = (
(
geometry is not None
and target is not None
and len(goal) == 3
and math.dist(goal[:2], pose[:2])
<= max(geometry["length_m"], geometry["width_m"]) + 1e-6
and 0.4 < math.dist(goal[:2], target) < math.dist(pose[:2], target)
and arrival.get("positive_surface_required") is True
)
if intermediate
else target is not None and len(goal) == 3 and math.dist(goal[:2], target) <= 0.4
)
return bool(
result.get("status") == "path"
and target is not None
and selected.get("target_xy") == target
and len(goal) == 3
and np.isfinite(goal).all()
and in_region
and arrival.get("observation") == {**observation, "target_xy": target}
and all(destination.get(k) is True for k in ("admitted", "collision_free", "support_known"))
and support.get("admitted") is True
and support.get("observation") == observation
)
def surface_candidates(surface, points, pose, calibration, target, excluded, *, source, geometry):
"""Current measured, full-width visual candidates; no inferred terrain."""
source.validate_surface(surface)
local, u, v, visible = project(points, calibration, source)
semantic = np.zeros(len(points), dtype=bool)
semantic[visible] = surface[source.indices(u[visible], v[visible])]
ground_z = pose[2] - geometry["body_contact_height_m"]
distance = np.linalg.norm(points[:, :2] - np.asarray(pose[:2]), axis=1)
slope = np.abs(points[:, 2] - ground_z) / np.maximum(distance, 0.1)
good = (
visible
& semantic
& (distance >= (0.4 if target is not None else 1.2))
& (distance <= 3.5)
& (slope <= np.tan(np.radians(geometry["max_slope_degrees"])))
& (np.ones(len(points), dtype=bool) if hasattr(source, "project") else (local[:, 2] < 0))
)
candidates = points[good]
# A pixel at the centre is insufficient for a metre-wide chassis. Require
# visual surface support on both sides, at the same candidate ground level.
if len(candidates):
delta = candidates[:, :2] - np.asarray(pose[:2])
perpendicular = np.column_stack((-delta[:, 1], delta[:, 0]))
perpendicular /= np.maximum(np.linalg.norm(perpendicular, axis=1)[:, None], 0.1)
supported = np.ones(len(candidates), dtype=bool)
for side in (-(geometry["width_m"] / 2), (geometry["width_m"] / 2)):
edge = candidates.copy()
edge[:, :2] += perpendicular * side
_, eu, ev, in_view = project(edge, calibration, source)
ok = np.zeros(len(edge), dtype=bool)
ok[in_view] = surface[source.indices(eu[in_view], ev[in_view])]
supported &= ok
for failed in excluded:
supported &= np.linalg.norm(candidates[:, :2] - np.asarray(failed[:2]), axis=1) > 0.6
good[np.flatnonzero(good)[~supported]] = False
candidates = points[good]
return local, distance, good
def visual_goal(
surface,
points,
pose,
calibration,
prior=None,
target=None,
excluded=(),
*,
source,
geometry,
candidate_mask=None,
):
"""Project semantic surface candidates into range; CMU owns path search."""
local, distance, good = surface_candidates(
surface, points, pose, calibration, target, excluded, source=source, geometry=geometry
)
if candidate_mask is not None:
good &= candidate_mask(points)
if prior is not None and not candidate_mask(np.asarray([prior]))[0]:
prior = None
candidates = points[good]
if len(candidates) < 8:
return None
if target is not None:
target = np.asarray(target)
if (
prior is not None
and np.linalg.norm(np.asarray(prior[:2]) - target) <= OBSERVED_ARRIVAL_GOAL_RADIUS_M
):
direction = target - pose[:2]
remaining = np.linalg.norm(direction)
lateral = np.array([-direction[1], direction[0]]) / max(remaining, 0.1)
footprint = np.tile(prior, (3, 1))
footprint[:, :2] += (
np.array([-(geometry["width_m"] / 2), 0, (geometry["width_m"] / 2)])[:, None]
* lateral
)
_, pu, pv, in_view = project(footprint, calibration, source)
# The measured camera projection defines its blind strip; a fixed
# 0.8 m cutoff forgot goals that disappeared around 0.95 m. Retain
# only a previously observed goal inside the task arrival region. Any visible
# non-drivable part invalidates it; live CMU range/collision checks
# remain mandatory before every motion command.
if 0.35 < remaining <= 3.5 and not in_view.all():
if surface[source.indices(pu[in_view], pv[in_view])].all():
return prior
return None
near_target = np.linalg.norm(candidates[:, :2] - target, axis=1) <= 0.25
if near_target.sum() >= 3:
# Once the requested waypoint has observed semantic/range support,
# keep its XY identity. A moving pixel median can slide laterally
# past the arrival radius, leaving CMU chasing successive forward
# goals after the actual task waypoint is already behind the rover.
requested = np.array([*target.tolist(), float(np.median(candidates[near_target, 2]))])
direction = target - pose[:2]
lateral = np.array([-direction[1], direction[0]]) / max(np.linalg.norm(direction), 0.1)
footprint = np.tile(requested, (3, 1))
footprint[:, :2] += (
np.array([-(geometry["width_m"] / 2), 0, (geometry["width_m"] / 2)])[:, None]
* lateral
)
_, tu, tv, in_view = project(footprint, calibration, source)
if (
in_view.all()
and surface[source.indices(tu, tv)].all()
and (candidate_mask is None or candidate_mask(requested[None])[0])
):
return requested.tolist()
# The task admits a 0.4 m arrival radius. A directly observed,
# full-width-supported point within 0.25 m remains inside it even
# with CMU's 0.08 m stopping tolerance. Do not take an unconstrained
# neighbourhood median: that can move a goal outside the arrival
# region and strand it behind the camera's near boundary.
nearby = candidates[near_target]
return nearby[np.argmin(np.linalg.norm(nearby[:, :2] - target, axis=1))].tolist()
if prior is not None and target is not None:
remaining = np.linalg.norm(np.asarray(prior[:2]) - pose[:2])
# Finish an already observed close waypoint after it enters the camera's
# under-body blind strip. Current visual support is still required above;
# CMU's causal terrain memory and live collision monitor retain authority.
if 0.35 < remaining <= 0.8:
return prior
# Retain a still-observed waypoint until reached; never keep a stale visual
# goal after the supporting surface disappears or changes classification.
if (
prior is not None
and np.linalg.norm(np.asarray(prior[:2]) - pose[:2]) > 0.8
and np.linalg.norm(candidates[:, :2] - np.asarray(prior[:2]), axis=1).min() < 0.35
):
return prior
good_local = local[good]
score = np.abs(distance[good] - 2.3) + 2.0 * np.abs(
np.arctan2(good_local[:, 1], good_local[:, 0])
)
if target is not None:
remaining = np.linalg.norm(target - pose[:2])
target_distance = np.linalg.norm(candidates[:, :2] - target, axis=1)
progress = target_distance < remaining - 0.1
if not progress.any():
return None
score = target_distance + 0.2 * score
score[~progress] = np.inf
center = candidates[int(np.argmin(score))]
neighbors = candidates[np.linalg.norm(candidates[:, :2] - center[:2], axis=1) < 0.3]
median = np.median(neighbors, axis=0)
# A median of individually permitted points need not avoid a non-convex
# no-go region. Keep the already admitted observed centre in that case.
return (
median if candidate_mask is None or candidate_mask(median[None])[0] else center
).tolist()
def corner_approach(surface, points, pose, calibration, target, *, source, geometry):
"""A short declared-corner intent from the current observed road direction.
The near camera can see road just beyond a corner while its centre is in
the blind strip. This proposes that declared XY, not a new ground return.
Fresh P2 support/obstacle admission still owns every commanded sweep, and
actual arrival still needs the unchanged 72-contact receipt. Callers must
re-evaluate this evidence each frame and cap translation at 0.1 m/s.
"""
if target is None:
return None
delta = np.asarray(target) - np.asarray(pose[:2])
remaining = float(np.linalg.norm(delta))
if not 0.4 < remaining <= 1.2:
return None
direction = delta / remaining
lateral = np.array([-direction[1], direction[0]])
_, _, good = surface_candidates(
surface, points, pose, calibration, target, (), source=source, geometry=geometry
)
candidates = points[good]
if len(candidates) < 8:
return None
offsets = candidates[:, :2] - np.asarray(target)
along, across = offsets @ direction, np.abs(offsets @ lateral)
candidates = candidates[(along >= 0) & (along <= 1.5) & (across <= 0.12)]
if len(candidates) < 3:
return None
measured = candidates[np.argmin(np.linalg.norm(candidates[:, :2] - target, axis=1))]
goal = np.array([*target, measured[2]])
footprint = np.tile(goal, (3, 1))
footprint[:, :2] += (
np.array([-geometry["width_m"] / 2, 0, geometry["width_m"] / 2])[:, None] * lateral
)
_, u, v, visible = project(footprint, calibration, source)
x, y, z, w = pose[3:7]
yaw = math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
aligned = float(direction @ [math.cos(yaw), math.sin(yaw)]) >= math.cos(0.35)
# Only a forward near-field blind strip, never a point behind the rover,
# an unseen lateral turn, or a visibly forbidden centre/contact projection.
if visible[1] or not aligned or not surface[source.indices(u[visible], v[visible])].all():
return None
return {
"goal": goal.tolist(),
"observed_direction_point": measured.tolist(),
"max_speed_mps": 0.1,
"authority": "declared-corner-intent-only; no-ground-or-arrival-admission",
}
def recovery_goal(points, pose, calibration, prior=None, *, geometry):
"""A short straight retreat requires fresh support across its whole width.
This is admission of a task goal, not a replacement for CMU. Its obstacle
map, path selector and swept-body monitor still reject the actual command.
Missing returns, ledges, steep or discontinuous ground forbid retreat.
"""
points = np.asarray(points)
qx, qy, qz, qw = pose[3:]
yaw = math.atan2(2 * (qw * qz + qx * qy), 1 - 2 * (qy * qy + qz * qz))
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
local = (points[:, :2] - np.asarray(pose[:2])) @ axes
if prior is None:
distance = 0.65
else:
offset = (np.asarray(prior[:2]) - np.asarray(pose[:2])) @ axes
distance = -float(offset[0])
if not 0 < distance <= 0.8 or abs(offset[1]) > 0.1:
return None
ground = pose[2] - geometry["body_contact_height_m"]
heights = []
# 15 cm lateral reserve covers the small heading correction allowed during
# reverse. Never extrapolate through an unobserved cell behind either wheel.
for x in np.arange(
-(geometry["length_m"] / 2) - 0.1 - distance, -(geometry["length_m"] / 2), 0.15
):
for y in np.linspace(
-(geometry["width_m"] / 2) - 0.15, (geometry["width_m"] / 2) + 0.15, 9
):
near = np.linalg.norm(local - [x, y], axis=1) <= 0.18
if near.sum() < 3:
return None
z = points[near, 2]
if np.ptp(z) > 0.1 or abs(float(np.median(z)) - ground) > 0.1 + abs(x) * math.tan(
math.radians(25)
):
return None
heights.append([x, y, float(np.median(z))])
samples = np.asarray(heights)
design = np.column_stack((samples[:, :2], np.ones(len(samples))))
plane = np.linalg.lstsq(design, samples[:, 2], rcond=None)[0]
if np.linalg.norm(plane[:2]) > math.tan(math.radians(25)):
return None
if np.max(np.abs(samples[:, 2] - design @ plane)) > 0.05:
return None
if prior is not None:
return prior
xy = np.asarray(pose[:2]) + axes @ [-distance, 0]
return [*xy.tolist(), float(plane[2] - distance * plane[0])]
class NavigationClient:
def __init__(self):
self.connection = http.client.HTTPConnection("127.0.0.1", 18093, timeout=2)
def request(self, path, body=None):
entered = time.perf_counter()
encoded = None if body is None else json.dumps(body, allow_nan=False)
encoded_at = time.perf_counter()
self.connection.request(
"GET" if body is None else "POST",
path,
body=encoded,
headers={"Content-Type": "application/json"},
)
sent_at = time.perf_counter()
response = self.connection.getresponse()
headers_at = time.perf_counter()
raw = response.read(3_000_001)
if response.status != 200 or len(raw) > 3_000_000:
detail = ""
if len(raw) <= 1000:
with suppress(ValueError, AttributeError):
detail = str(json.loads(raw).get("error", ""))[:200]
raise RuntimeError("Local CMU navigation is unavailable: " + detail)
result = json.loads(raw)
if path == "/plan":
result.setdefault("diagnostic", {})["client_stage_ms"] = {
"encode": (encoded_at-entered)*1000,
"send": (sent_at-encoded_at)*1000,
"response_headers": (headers_at-sent_at)*1000,
"read_decode": (time.perf_counter()-headers_at)*1000,
}
return result
def close(self):
self.connection.close()
class ComposedInference:
experience = None
def __init__(self, root: Path, run, directory: Path, mission=None):
profile = json.loads((root / "models.worker-006.json").read_text())
self.graph = compose(root, run["request"].get("composition"))
self.segmenter_id = next(
n.module.module_id for n in self.graph.nodes if n.module.group == "segmentation"
)
mission_node = next(
n for n in self.graph.nodes if n.module.module_id == "simulation-waypoint-mission"
)
self.inputs = resolve_run_inputs(run, resolve_run_robot(run))
self.geometry = self.inputs["robot"]["geometry"]
self.source = source_for_rig(self.inputs["sensors"])
self.optics = None
self.task_view_intent = TaskViewIntent()
# Native Nav2 BackUp follows the current body axis. The legacy CMU
# controller also supports rear arcs; keep their intent limits distinct.
self.observed_goals = (
ObservedGoals(reverse_heading_tolerance=(.12 if any(
n.module.module_id == "simulation-nav2-navigation" for n in self.graph.nodes
) else math.pi/4)) if self.inputs["sensors"]["schema_version"] in
{MOUNTED_SENSOR_SCHEMA, CONTINUOUS_SENSOR_SCHEMA} else None
)
if "mounts" in self.inputs["sensors"]:
from k1link.simulation.ai_polygon.camera_optics import (
DualFisheye,
LensObservationViews,
ObservationViews,
)
self.optics = DualFisheye(self.inputs["sensors"]["mounts"]["insta360"])
self.single_lens = self.inputs["sensors"]["schema_version"] == MOUNTED_SENSOR_SCHEMA
self.observation_views = (
LensObservationViews() if self.single_lens else ObservationViews()
)
self.environment = self.inputs["behavior"]["environment"]
if self.environment != json.loads(mission_node.parameters_json)["environment"]:
raise ValueError("Behavior profile does not match composition")
self.models = ModelInference(
"http://127.0.0.1:18092",
Path(profile["labels"]),
"http://127.0.0.1:18091",
segmenter_id=self.segmenter_id,
source=self.source,
)
self.navigation = NavigationClient()
self.max_speed = self.inputs["behavior"]["max_speed_mps"]
self.goal = None
self.mission = mission or mission_for_inputs(self.inputs)
self.route_monitor = Footprint(self.geometry)
self.global_route = build_route(self.inputs)
self.navigation_evidence = {}
self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="simulation-module")
self.directory = directory
self.experience = None
if run.get("_spatial_experience_root") and run["world"].get("collider_sha256"):
from experience_adapter import ExperienceAdapter
self.experience = ExperienceAdapter(run, self.inputs, directory)
names = self.models.labels
if self.segmenter_id == "simulation-sam3-surfaces":
from k1link.simulation.ai_polygon.concept_surfaces import LABELS
names = LABELS
model_ids = {"simulation-segformer-ade": "segformer-b2-ade150",
"simulation-segformer-cityscapes": "segformer-b2-cityscapes19",
"simulation-mask2former-mapillary": "mask2former-mapillary65"}
if self.segmenter_id in model_ids:
model_id = model_ids[self.segmenter_id]
descriptor = next(m for m in profile["models"] if m["id"] == model_id)
config = Path(descriptor["checkpoint"]).with_name("config.json").read_bytes()
if hashlib.sha256(config).hexdigest() != descriptor["config_sha256"]:
raise ValueError("Surface taxonomy identity changed")
names = {int(k): v for k, v in json.loads(config)["id2label"].items()}
self.preview = InferencePreview(directory, self.graph, self.environment, names)
self.providers = {
"simulation-declared-route": lambda inputs: {"navigation.route": self.global_route},
"simulation-ddrnet-goose": lambda inputs: self.models.surface(
inputs["source.camera.rgb"]
),
"simulation-segformer-cityscapes": lambda inputs: self.models.surface(
inputs["source.camera.rgb"]
),
"simulation-segformer-ade": lambda inputs: self.models.surface(
inputs["source.camera.rgb"]
),
"simulation-mask2former-mapillary": lambda inputs: self.models.surface(
inputs["source.camera.rgb"]
),
"simulation-sam3-surfaces": lambda inputs: self.models.surface(
inputs["source.camera.rgb"]
),
"simulation-rf-detr": lambda inputs: {
"detection.boxes": self.models.detect(inputs["source.camera.rgb"])
},
"simulation-cmu-navigation": self.navigate,
"simulation-nav2-navigation": self.navigate,
"simulation-waypoint-mission": self.plan_mission,
}
if {node.module.module_id for node in self.graph.nodes} - set(self.providers):
raise ValueError("Composition contains an uninstalled executor")
# This preparation node has only immutable run inputs. Execute it once
# per episode/client, retaining its identity and output evidence. Do not
# put a cached constant through the camera's asynchronous work queue.
self.static_modules = {"simulation-declared-route"}
self.static_values = self.providers["simulation-declared-route"](
{"source.execution-inputs": self.inputs}
)
directory.mkdir(exist_ok=True, parents=True)
(directory.parent / "route-preparation.json").write_text(
json.dumps(
{
"execution_inputs_sha256": self.inputs["sha256"],
"module_sha256": next(
n.module.sha256
for n in self.graph.nodes
if n.module.module_id in self.static_modules
),
"outputs": self.static_values,
},
indent=2,
),
encoding="utf-8",
)
if self.global_route is not None:
(directory.parent / "global-route.json").write_text(
json.dumps(self.global_route, indent=2), encoding="utf-8"
)
(directory.parent / "composition.json").write_text(
json.dumps(
{
"sha256": self.graph.sha256,
"graph": self.graph.as_dict(),
"modules": [node.module.identity_document() for node in self.graph.nodes],
},
indent=2,
),
encoding="utf-8",
)
def ready(self):
self.models.ready()
self.navigation_ready()
def navigation_ready(self):
receipt = self.navigation.request("/ready")
if receipt.get("execution_inputs_sha256") != self.inputs["sha256"]:
raise ValueError("Navigation geometry differs from execution inputs")
def reset(self):
self.goal = self.goal_approach = None
self.body_goal_waypoint = self.body_goal_phase_key = None
self.task_view_intent = TaskViewIntent()
if self.observed_goals is not None:
self.observed_goals = ObservedGoals(
reverse_heading_tolerance=self.observed_goals.reverse_heading_tolerance)
self.mission.resume()
self.navigation.request("/reset", {})
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
try:
self.navigation_ready()
return
except (OSError, RuntimeError):
time.sleep(0.1)
raise RuntimeError("Navigation reset timed out")
def plan_mission(self, inputs):
if inputs["navigation.route"] != getattr(self.mission, "global_route", None):
raise ValueError("Mission route does not match composed route provider")
surface = permitted_surface(
inputs["segmentation.labels"],
inputs["segmentation.surface"],
self.environment,
self.segmenter_id,
self.models.labels,
)
prior_was_approach = getattr(self, "goal_approach", None) is not None
self.goal_approach = None
permissions = permitted_surface(
inputs["segmentation.labels"], np.ones_like(surface, dtype=bool),
self.environment, self.segmenter_id, self.models.labels,
)
crossing = inputs.get("source.crossing-mask")
if crossing is not None and self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces":
crossing = np.asarray(crossing, dtype=bool)
if crossing.shape != surface.shape or np.any(crossing & ~np.isin(inputs["segmentation.labels"], (0, 1, 2, 3))):
raise ValueError("Crossing admission exceeds ground surface classes")
if crossing.any() and not inputs.get("source.crossing-admission", {}).get("admitted"):
raise ValueError("Crossing ground requires manoeuvre admission")
permissions |= crossing
surface |= crossing
observed_goals = getattr(self, "observed_goals", None)
semantic_observation = inputs.get("source.semantic-observation")
if observed_goals is not None and semantic_observation is not None:
for sample in semantic_observation:
observed_goals.observe(sample["samples"], sample["captured_at"], sample["pose"],
frame_id=sample.get("frame_id"), capture_id=sample.get("capture_id"))
elif observed_goals is not None:
calibration = inputs["source.camera.calibration"]
points = inputs["source.lidar"]
_, u, v, visible = project(points, calibration, self.source)
classified = points[visible]
indices = self.source.indices(u[visible], v[visible])
allowed, confident = permissions[indices], surface[indices]
valid = inputs["segmentation.known"][indices] & (confident | ~allowed)
valid &= self.source.semantic_visible(classified, calibration)
observed_goals.observe(
np.column_stack((classified[valid], allowed[valid].astype(int))),
calibration["captured_at"], inputs["source.pose"],
)
def choose(target, prior, excluded):
calibration = inputs["source.camera.calibration"]
if observed_goals is not None:
# Every lens contributes to the same causal surface memory.
# 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())
if observed is None:
return None
goal, self.intent_captured_at = observed
return goal
# A declared blind-strip intent is not a previously measured point.
# Never feed it into visual_goal's causal observed-goal memory.
goal = visual_goal(
surface,
inputs["source.lidar"],
inputs["source.pose"],
inputs["source.camera.calibration"],
None if prior_was_approach else prior,
target,
excluded,
source=self.source,
geometry=self.geometry,
candidate_mask=self.mission.goals_permitted
if isinstance(self.mission, RoutedMission)
else None,
)
# Rejected task views revoke the cache immediately. A declared
# blind-strip corner approach below is not observed visual intent.
if calibration.get("view_role") == "task":
self.task_view_intent.remember(goal, target, calibration["captured_at"])
if not isinstance(self.mission, RoutedMission):
return goal
if goal is not None and self.mission.goal_permitted(goal):
return goal
approach = corner_approach(
surface,
inputs["source.lidar"],
inputs["source.pose"],
inputs["source.camera.calibration"],
target,
source=self.source,
geometry=self.geometry,
)
if approach is not None:
self.goal_approach = {
**approach,
"observation": {
"pose": list(inputs["source.pose"]),
"simulation_time_seconds": inputs["source.simulation-time"],
"execution_inputs_sha256": self.inputs["sha256"],
},
}
return approach["goal"]
return None
def maneuver(prior, excluded):
target = self.mission.arrival_target()
return observed_goals.maneuver(
inputs["source.lidar"], inputs["source.pose"], target, prior, excluded,
self.geometry, time.monotonic(), self.mission.goals_permitted
if isinstance(self.mission, RoutedMission) else None,
experience_cost=self.experience.costs if self.experience else None)
self.goal, intent = self.mission.update(
inputs["source.pose"],
inputs["source.simulation-time"],
choose,
lambda prior: recovery_goal(
inputs["source.lidar"],
inputs["source.pose"],
inputs["source.camera.calibration"],
prior,
geometry=self.geometry,
),
choose_maneuver=maneuver if (
observed_goals is not None
and self.inputs["sensors"]["schema_version"] == CONTINUOUS_SENSOR_SCHEMA
) else None,
)
if self.goal is None:
self.goal_approach = None
if self.goal_approach is not None:
intent["corner_approach"] = self.goal_approach
return {
"navigation.goal": self.goal,
"navigation.intent": intent,
"navigation.surface": surface,
"navigation.semantic-known": inputs["segmentation.known"] | (crossing if crossing is not None else False),
# Low confidence is not a semantic obstacle. Keep that gate in
# visual_goal, but persist only explicit profile exclusions in CMU.
"navigation.permissions": permissions,
}
def navigate(self, inputs):
surface, boxes = inputs["navigation.surface"], inputs["detection.boxes"]
points, pose = inputs["source.lidar"], inputs["source.pose"]
calibration = inputs["source.camera.calibration"]
intent = inputs["navigation.intent"]
orientation = self.mission.orientation_target()
recovering = self.mission.recovery.active
recovery_option = (self.mission.recovery.sequence, self.mission.recovery.option)
if recovering:
orientation = self.mission.recovery.orientation() if (
self.goal is not None or intent["state"] == "orienting") else None
arrival_target = self.mission.arrival_target()
arrival_candidate = not recovering and self.mission.arrival_candidate(pose)
# A near task goal may enter the camera blind strip before the rover's
# centre reaches its arrival radius. Ask CMU to admit a destination
# from measured range plus positively observed semantic memory.
nearby = bool(
not recovering and arrival_target is not None
and self.mission.can_query_arrival(pose)
and np.linalg.norm(np.asarray(pose[:2]) - arrival_target) <= 3.5
)
route_transition_query = bool(not recovering and arrival_target is not None
and isinstance(self.mission, RoutedMission)
and self.mission.can_query_route_transition(pose))
terminal_region = bool(
nearby
and math.dist(pose[:2], arrival_target)
<= 0.4 + math.hypot(self.geometry["length_m"], self.geometry["width_m"]) / 2
)
phase_key = (orientation["key"], tuple(arrival_target)) if orientation and nearby else None
if not terminal_region or getattr(self, "body_goal_phase_key", None) != phase_key:
self.body_goal_phase_key = None
terminal_approach = terminal_region and (
not intent.get("corner_approach") or self.body_goal_phase_key == phase_key
)
# A visually valid point near a corner is not an admissible body pose.
# Before the follower's footprint rejects that exact point (e.g. at a
# path edge), search the unchanged arrival region for a measured pose.
# Farther local traversal retains its existing camera-goal behaviour.
target_key = tuple(arrival_target) if arrival_target is not None else None
if (
getattr(self, "body_goal_waypoint", None) != target_key
or not nearby
or (not terminal_approach and not self.mission.retain_arrival_query(self.goal))
):
self.body_goal_waypoint = None
if nearby and (arrival_candidate or self.goal is None or terminal_approach):
self.body_goal_waypoint = target_key
body_goal_query = self.body_goal_waypoint is not None
fraction = float(surface[320:500, 100:412].mean())
reason, result = "uncertain", {"speed_mps": 0.0, "yaw_rate_rps": 0.0, "path": []}
detection_evidence = []
if len(points) >= 50:
local, u, v, visible = project(points, calibration, self.source)
detection_indices = set()
detection_views = inputs.get("source.detection-views", [
dict(calibration=calibration, boxes=boxes, surface=surface)])
for view in detection_views:
view_calibration = view["calibration"]
if "lens_depths" in view:
self.source.lens_depths = view["lens_depths"]
_, du, dv, seen = project(points, view_calibration, self.source)
ground_pixels = np.zeros(len(points), dtype=bool)
ground_pixels[seen] = view["surface"][self.source.indices(du[seen], dv[seen])]
objects = view.get("objects", [])
if objects and (len(objects) != len(view["boxes"]) or any(
tuple(item["box"]) != tuple(box)
for item, box in zip(objects, view["boxes"], strict=True))):
raise ValueError("Detection classes do not match their boxes")
for box_index, (x1, y1, x2, y2) in enumerate(view["boxes"]):
covered = (seen & (du >= self.source.width*x1) & (du <= self.source.width*x2)
& (dv >= self.source.height*y1) & (dv <= self.source.height*y2))
association = detection_proximity(
points, pose, ground_pixels, covered, calibration["body_contact_height_m"],
reverse=intent["state"] == "reversing")
detection_indices.update(association.pop("hazard_indices"))
detection_evidence.append({"box": [x1, y1, x2, y2],
**({"object": objects[box_index]} if objects else {}),
"view_yaw_degrees": view_calibration.get("view_yaw_degrees", 0), **association})
if hasattr(self.source, "lens_depths"):
self.source.lens_depths = inputs.get(
"source.camera.lens-depths", self.source.lens_depths)
if intent["state"] in {"stuck", "goal-reached", "unstable"}:
reason = intent["state"]
elif self.goal is None and not (arrival_candidate or body_goal_query or orientation or recovering):
reason = "no-road"
else:
# Label only directly observed returns using the same calibrated RGB
# crop as the policy. The terrain planner retains causal semantic
# barriers through the under-camera blind strip.
classified = points[visible]
allowed = inputs["navigation.permissions"][
self.source.indices(u[visible], v[visible])
]
confident = surface[self.source.indices(u[visible], v[visible])]
known = inputs["navigation.semantic-known"][
self.source.indices(u[visible], v[visible])
]
semantic_evidence = known & (confident | ~allowed)
if hasattr(self.source, "semantic_visible"):
semantic_evidence &= self.source.semantic_visible(classified, calibration)
samples = np.column_stack(
(classified[semantic_evidence], allowed[semantic_evidence].astype(int))
).tolist()
prepared = inputs.get("source.semantic-observation")
if prepared is not None:
samples = [] # Separate timestamped camera observations below.
result = self.navigation.request(
"/plan",
{
"execution_inputs_sha256": self.inputs["sha256"],
"orientation_target": orientation,
"recovery_orientation": recovering,
"translation_allowed": self.goal is not None or body_goal_query,
# Begin body placement before the task enters the near
# camera strip, for waypoint and routed missions alike.
# A camera candidate beyond the task must not become the
# terminal destination. The server still has to find and
# admit a body pose inside the unchanged arrival region.
"visual_goal_available": self.goal is not None and (
not terminal_approach or math.dist(self.goal[:2], arrival_target)
<= OBSERVED_ARRIVAL_GOAL_RADIUS_M),
"points": points.tolist(),
"detection_point_indices": sorted(detection_indices),
"detection_age_seconds": max(max(0, time.monotonic()
- view["calibration"].get("captured_at", time.monotonic()))
for view in detection_views),
"range_rays": {
key: value.tolist()
for key, value in inputs["source.range-rays"].items()
},
"semantic_points": samples,
**({
"continuous": True,
"geometry_age_seconds": max(0, time.monotonic()
- inputs["source.range-captured-at"]),
"observation_id": inputs["source.observation-id"],
"semantic_observations": [
{"samples": item["samples"],
"age_seconds": max(0, time.monotonic() - item["captured_at"]),
"frame_id": item["frame_id"],
"capture_id": item.get("capture_id", item["frame_id"])}
for item in prepared
],
} if prepared is not None else {}),
"pose": pose,
"body_contact_height_m": calibration["body_contact_height_m"],
"goal": self.goal
or [
*arrival_target,
pose[2] - calibration["body_contact_height_m"],
],
"simulation_time_seconds": inputs["source.simulation-time"],
"arrival_target": arrival_target
if arrival_candidate or body_goal_query
else None,
"route_transition_target": arrival_target
if route_transition_query 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),
"allow_reverse": intent["state"] == "reversing",
},
)
if getattr(self, "observed_goals", None) is not None:
self.observed_goals.observe_navigation(
result, pose, inputs["source.simulation-time"], self.inputs["sha256"],
inputs.get("source.range-captured-at", calibration.get("captured_at", -math.inf)))
self.mission.reject_local_plan(
result, pose, inputs["source.simulation-time"], self.inputs["sha256"])
self.mission.recovery.observe_navigation(
result, pose, inputs["source.simulation-time"],
recovery_option, self.inputs["sha256"],
)
arrival = result.get("arrival", {})
destination = arrival.get("destination", {})
if (
terminal_region
and body_goal_query
and destination.get("admitted") is True
and destination.get("collision_free") is True
and destination.get("support_known") is True
and arrival.get("observation")
== {
"pose": list(pose),
"target_xy": arrival_target,
"simulation_time_seconds": inputs["source.simulation-time"],
"execution_inputs_sha256": self.inputs["sha256"],
}
):
# Preserve the near-corner body-placement request across
# camera sectors. A survey's blind-strip direction must not
# erase an already observed destination and restart chasing
# the exact corner centre. This retains a planning phase,
# never its safety admission: CMU reassesses the destination
# and actual swept command on every new observation.
self.body_goal_phase_key = phase_key
if hasattr(self.mission, "regulate_command"):
requested = [result["speed_mps"], result["yaw_rate_rps"]]
velocity, angular, scale = self.mission.regulate_command(
pose, self.route_monitor, *requested
)
result.update(speed_mps=velocity, yaw_rate_rps=angular)
result["route_command"] = {
"requested": requested,
"output": [velocity, angular],
"scale": scale,
}
if scale == 0:
result.update(path=[], status="blocked")
result["route_guard"] = "swept-body-outside-corridor"
elif scale < 1:
result["route_guard"] = "limited-to-corridor"
# A locally blocked command or a required detour outside this
# corridor can propose an exclusion, but only with persistent
# fresh obstacle evidence bound to this observation.
revision = (
self.mission.observe_navigation(
result, points, pose, inputs["source.simulation-time"]
)
if hasattr(self.mission, "observe_navigation")
else None
)
if revision is not None:
# No command computed for an old intent may cross a route
# revision. Next observation acquires the new direction.
result.update(
speed_mps=0.0,
yaw_rate_rps=0.0,
path=[],
status="waiting-for-plan",
maneuver=None,
)
result["route_revision"] = revision
intent = self.mission.intent(self.mission.state)
self.goal = self.body_goal_waypoint = self.body_goal_phase_key = None
if hasattr(self.mission, "observe_maneuver"):
self.mission.observe_maneuver(
result.get("maneuver"), pose, inputs["source.simulation-time"]
)
if result.get("status") == "arrival-accepted":
receipt = result.get("arrival", {})
expected = {
"pose": list(pose),
"target_xy": arrival_target,
"simulation_time_seconds": inputs["source.simulation-time"],
"execution_inputs_sha256": self.inputs["sha256"],
}
if (
receipt.get("admitted") is not True
or receipt.get("observation") != expected
):
raise ValueError("Invalid or stale body arrival receipt")
committed = self.mission.confirm_arrival(
pose, inputs["source.simulation-time"], intent["waypoint"], admitted=True
)
if not committed:
raise ValueError("Arrival receipt does not match mission observation")
result["speed_mps"] = result["yaw_rate_rps"] = 0.0
intent = self.mission.intent(self.mission.state)
elif isinstance(self.mission, RoutedMission) and revision is None:
transition = self.mission.confirm_corridor_transition(
pose, inputs["source.simulation-time"],
result.get("route_support") or result.get("arrival") or {}
)
if transition is not None:
result.update(
speed_mps=0.0,
yaw_rate_rps=0.0,
path=[],
status="waiting-for-plan",
route_transition=transition,
maneuver=None,
)
self.goal = self.body_goal_waypoint = self.body_goal_phase_key = None
intent = self.mission.intent(self.mission.state)
reason = {
"path": "road",
"blocked": "obstacle",
"waiting-for-plan": "waiting",
"arrival-accepted": "waiting",
}.get(result["status"], "uncertain")
if (result["status"] == "blocked"
and result.get("diagnostic", {}).get("failure") == "no-permitted-goal"):
reason = "no-road"
if (
reason == "road"
and abs(result["speed_mps"]) + abs(result["yaw_rate_rps"]) < 1e-5
):
reason = "waiting"
elif reason == "road" and intent["state"] in {"replanning", "reversing"}:
reason = "replanning"
self.mission.observe_alignment(
result, pose, inputs["source.simulation-time"], self.inputs["sha256"])
body_direction_current = body_goal_query and current_body_destination(
result,
pose,
arrival_target,
inputs["source.simulation-time"],
self.inputs["sha256"],
self.geometry,
)
if isinstance(self.mission, RoutedMission):
selected_body_goal = (result.get("arrival_goal") or {}).get("goal", [])
if (result.get("arrival_goal") or {}).get("kind") == "observed-approach":
body_direction_current = body_direction_current and self.mission.goal_permitted(
selected_body_goal
)
self.mission.observe_body_approach(
selected_body_goal,
pose,
inputs["source.simulation-time"],
admitted=body_direction_current,
intermediate=(result.get("arrival_goal") or {}).get("kind") == "observed-approach",
)
if body_direction_current:
# The server replaced the visual intermediate goal with a freshly
# assessed whole-body destination and admitted this command's sweep.
# Only the intent dependency changes; the camera/range capture time
# and the independent command deadman remain unchanged.
self.intent_captured_at = calibration.get(
"captured_at", getattr(self, "intent_captured_at", None)
)
result["intent_source"] = "current-observed-body-destination"
elif (
calibration.get("view_role") == "survey"
and result["speed_mps"] == 0.0
and result.get("diagnostic", {}).get("arrival_approach", {}).get("phase") == "aligning"
):
# The stopped orientation proposal uses the declared mission
# direction and this transaction's range/support gates. It does
# not use the older local translation goal retained during survey.
self.intent_captured_at = calibration["captured_at"]
if self.experience is not None:
self.experience.observe(inputs, self.goal, result)
self.navigation_evidence = {
"mission": intent,
"environment": self.environment,
"detection_range": detection_evidence,
"navigation": {k: v for k, v in result.items() if k != "path"},
}
decision = Decision(
speed_mps=result["speed_mps"],
yaw_rate_rps=result["yaw_rate_rps"],
reason=intent["state"]
if intent["state"] in {"stuck", "goal-reached", "unstable"}
else reason,
road_fraction=fraction,
obstacle_count=len(boxes),
)
return {"motion.command": decision.model_dump(), "motion.path": result["path"]}
def infer_observation(self, rgb, observation, frame_id):
if self.optics is not None:
sources = observation["camera_sources"]
selected = self.observation_views.choose(observation["rectified_body_axes"])
calibration = dict(observation["calibration"])
body_axes = np.asarray(calibration["lens_axes"])[0] @ self.optics.lens_axes[0].T
calibration["rotation"] = (body_axes @ selected).reshape(-1).tolist()
calibration["view_role"] = (
"task" if np.array_equal(selected, observation["rectified_body_axes"]) else "survey"
)
calibration["captured_at"] = observation["captured_at"]
lens = None
if self.single_lens:
lens = int(np.argmax(self.optics.lens_axes[:, :, 0] @ selected[:, 0]))
calibration.update(
projection="single-lens-rectilinear/v1",
source_lens=lens,
origin=calibration["lens_origins"][lens],
)
observation["calibration"] = calibration
observation["rectified_body_axes"] = selected
rgb, observation["camera_valid"] = self.optics.rectify(
[sources["insta360_left"], sources["insta360_right"]],
selected,
[800, 600],
observation["calibration"]["intrinsics"],
lens=lens,
)
observation["inference_rgb"] = rgb
self.intent_captured_at = observation.get("captured_at")
self.source.validate_rgb(rgb)
self.source.lens_depths = observation.get("lens_depths")
values = {
**self.static_values,
"source.execution-inputs": self.inputs,
"source.camera.rgb": rgb,
"source.lidar": observation["points"],
"source.range-rays": observation.get("range_rays", {}),
"source.pose": observation["pose"],
"source.camera.calibration": observation["calibration"],
"source.simulation-time": observation["simulation_time_ns"] / 1e9,
}
timings = {}
pending = [n for n in self.graph.nodes if n.module.module_id not in self.static_modules]
def execute(node, inputs):
started = time.monotonic()
output = self.providers[node.module.module_id](inputs)
if set(output) != set(node.module.provides):
raise ValueError("Provider output does not match its composition contract")
return output, (time.monotonic() - started) * 1000
while pending:
ready = [node for node in pending if all(port in values for port, _ in node.inputs)]
if not ready:
raise ValueError("Unresolved composition input")
tasks = [
(
node,
self.pool.submit(
execute, node, {port: values[port] for port, _ in node.inputs}
),
)
for node in ready
]
for node, task in tasks:
output, elapsed = task.result()
values.update(output)
timings[node.module.module_id] = elapsed
pending.remove(node)
self.pending_archive = (rgb, values, observation, frame_id)
return (
values["motion.command"],
values["detection.boxes"],
{
"composition_sha256": self.graph.sha256,
"module_ms": timings,
"goal": self.goal,
"path": values["motion.path"],
"range_points": len(observation["points"]),
**(
{"intent_captured_at": self.intent_captured_at}
if self.intent_captured_at is not None
else {}
),
**self.navigation_evidence,
**({"spatial_goal": self.observed_goals.evidence}
if self.observed_goals is not None else {}),
},
)
def take_archive(self):
"""Transfer this frame to the single bounded evidence writer.
Frame arrays/results are owned by this packet and never reused by the
next inference. Only the writer touches preview state; optics' panorama
map is immutable and independent of its mutable rectification cache.
"""
packet, self.pending_archive = self.pending_archive, None
return lambda: self.archive_observation(packet)
def archive_observation(self, packet=None):
"""Persist the just-computed observation after command publication.
The writer owns at most one active and one queued frame. Shutdown joins
it before model teardown; any disk error stops the run's control path.
"""
if packet is None:
packet, self.pending_archive = self.pending_archive, None
rgb, values, observation, frame_id = packet
if self.optics is not None:
sources = observation["camera_sources"]
sources["insta360_panorama"] = self.optics.panorama(
[sources["insta360_left"], sources["insta360_right"]]
)
self.preview.publish(self.source.model_rgb(rgb), values, observation, frame_id)
from PIL import Image
for name, image in observation.get("camera_sources", {}).items():
Image.fromarray(image).save(self.directory / f"{frame_id:08d}.{name}.jpg", quality=90)
if "realsense_depth" in observation:
save_arrays(
self.directory / f"{frame_id:08d}.sensors.npz",
realsense_depth=observation["realsense_depth"],
lens_depths=np.stack(observation["lens_depths"]),
camera_valid=observation["camera_valid"],
calibration_json=json.dumps(observation["calibration"], sort_keys=True),
range_source_counts_json=json.dumps(
observation["range_source_counts"], sort_keys=True
),
)
Image.fromarray(values["segmentation.known"].astype(np.uint8) * 255).save(
self.directory / f"{frame_id:08d}.known.png", compress_level=1
)
Image.fromarray(values["segmentation.labels"]).save(
self.directory / f"{frame_id:08d}.labels.png", compress_level=1
)
Image.fromarray(values["segmentation.surface"].astype(np.uint8) * 255).save(
self.directory / f"{frame_id:08d}.surface.png", compress_level=1
)
save_arrays(
self.directory / f"{frame_id:08d}.range.npz",
points=observation["points"],
pose=observation["pose"],
origin=observation["calibration"]["origin"],
rotation=observation["calibration"]["rotation"],
intrinsics=observation["calibration"]["intrinsics"],
calibration_json=json.dumps(observation["calibration"], sort_keys=True),
body_contact_height_m=observation["calibration"]["body_contact_height_m"],
execution_inputs_sha256=self.inputs["sha256"],
sensor_rig_json=json.dumps(self.inputs["sensors"], sort_keys=True),
range_origins=observation["calibration"].get("range_origins", []),
ray_origins=observation.get("range_rays", {}).get("origins", []),
ray_ends=observation.get("range_rays", {}).get("ends", []),
ray_origin_indices=observation.get("range_rays", {}).get("origin_indices", []),
range_views_json=json.dumps({key: value.tolist() for key, value in
observation.get("range_rays", {}).items() if key.startswith("view_")},
allow_nan=False),
)
def close(self):
if self.experience is not None:
self.experience.close()
self.pool.shutdown(wait=True, cancel_futures=True)
self.models.close()
self.navigation.close()