Files
NODEDC_MISSION_CORE/simulation/ai-polygon/continuous_composition.py

217 lines
12 KiB
Python

"""Independent camera and range stages of the installed composition.
Neural results carry capture-pose/time and are projected once at that pose.
Navigation consumes the latest range packet and the observed semantic map.
Neither camera sector selection nor preview publication drives the controller.
"""
import math
import time
import numpy as np
from navigation_client import ComposedInference, permitted_surface, project
from urban_crossing import MarkedCrossing
from k1link.simulation.ai_polygon.camera_optics import axes
from k1link.simulation.ai_polygon.source_projection import source_for_rig
class ContinuousComposition(ComposedInference):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.camera_source = source_for_rig(self.inputs["sensors"])
self.supplement_yaw = None
self.recovery_view_request = None
self.recovery_detection_view = None
self.last_supplement = -math.inf
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, observation_range_m=max(
12., self.inputs["sensors"]["mounts"]["k1"]["range_m"][1]))
self.recovery_view_request = None
self.recovery_detection_view = None
def perceive_view(self, observation, frame_id, yaw, *, pitch=-20, detect=True):
started = time.monotonic()
selected = axes(yaw, pitch)
calibration = dict(observation["calibration"])
body_axes = np.asarray(calibration["lens_axes"])[0] @ self.optics.lens_axes[0].T
calibration.update(
rotation=(body_axes @ selected).reshape(-1).tolist(),
projection="dual-origin-rectilinear/v1", captured_at=observation["captured_at"],
view_role="task" if yaw == 0 and pitch == -20 else "supplement",
view_yaw_degrees=yaw, view_pitch_degrees=pitch,
)
sources = observation["camera_sources"]
rgb, valid = self.optics.rectify_forward(
[sources["insta360_left"], sources["insta360_right"]], selected,
[800, 600], calibration["intrinsics"],
)
view = {**observation, "calibration": calibration, "camera_valid": valid,
"inference_rgb": rgb, "rectified_body_axes": selected}
def timed(call):
begin = time.monotonic()
result = call(rgb)
return result, (time.monotonic() - begin) * 1000
segmentation = self.pool.submit(timed, self.models.surface)
detection = self.pool.submit(timed, self.models.detect_observations) if detect else None
values, segment_ms = segmentation.result()
objects, detector_ms = detection.result() if detection else ([], 0.0)
boxes = [tuple(item["box"]) for item in objects]
values = {**values, "detection.boxes": boxes, "detection.objects": objects,
"source.lidar": observation["points"], "source.pose": observation["pose"]}
self.camera_source.lens_depths = observation["lens_depths"]
points = observation["points"]
_, u, v, visible = project(points, calibration, self.camera_source)
indices = self.camera_source.indices(u[visible], v[visible])
crossing_mask=np.zeros((512,512),dtype=bool)
crossing={"state":"disabled","admitted":False}
if self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces":
crossing_mask,crossing=self.crossing.observe(values["segmentation.labels"],
points[visible],indices,observation["pose"],observation["captured_at"],
advance=(yaw == 0 and pitch == -20))
values["source.crossing-mask"]=crossing_mask
values["source.crossing-admission"]=crossing
permitted = permitted_surface(values["segmentation.labels"],
values["segmentation.surface"], self.environment,
self.segmenter_id, self.models.labels)
permissions = permitted_surface(values["segmentation.labels"],
np.ones_like(permitted, dtype=bool), self.environment,
self.segmenter_id, self.models.labels)
permissions |= crossing_mask
permitted |= crossing_mask
values["navigation.surface"] = permitted
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": samples.tolist(),
"captured_at": observation["captured_at"], "pose": observation["pose"],
"frame_id": f"{frame_id}:{yaw}:{pitch}", "capture_id": str(frame_id),
}
return dict(rgb=rgb, values=values, observation=view, frame_id=frame_id,
samples=sample, completed_at=time.monotonic(),
processing_ms=(time.monotonic() - started) * 1000,
module_ms={self.segmenter_id: segment_ms, "simulation-rf-detr": detector_ms})
def perceive(self, observation, frame_id, *, publish_front=None, latest_sensor=None):
request = getattr(self, "recovery_view_request", None)
front = self.perceive_view(observation, frame_id, 0)
front["semantic_observations"] = [front["samples"]]
front["detection_views"] = [front.copy()]
cached = getattr(self, "recovery_detection_view", None)
if cached and time.monotonic()-cached["observation"]["captured_at"] <= 2:
front["detection_views"].append(cached)
yaw = request["yaw_degrees"] if request else self.supplement_yaw
if request and yaw == 0:
front["recovery_view"] = request
front["recovery_observation"] = observation
yaw = None
changed = request and request != getattr(self, "last_recovery_view_request", None)
if yaw is not None and (changed or time.monotonic() - self.last_supplement >= 1):
# Publish the completed front before another neural pass. Never
# mutate a packet already visible to navigation/control threads.
if publish_front is not None and not publish_front(front):
return front
packet = latest_sensor() if latest_sensor is not None else (frame_id, observation)
if packet is None:
return front # Pause/reset invalidated this capture epoch.
extra_frame, extra_observation = packet
# A supplementary pass starts from the latest captured panorama;
# its pose/time must never be borrowed from the earlier front view.
self.last_supplement = time.monotonic()
self.last_recovery_view_request = request
extra = self.perceive_view(extra_observation, extra_frame, yaw, detect=bool(request))
front = {**front, "semantic_observations": [front["samples"], extra["samples"]],
"supplement": extra, "detection_views": [front["detection_views"][0]]}
if request:
self.recovery_detection_view = extra
front["recovery_view"] = request
front["recovery_observation"] = extra_observation
front["detection_views"].append(extra)
elif cached and time.monotonic()-cached["observation"]["captured_at"] <= 2:
front["detection_views"].append(cached)
return front
def navigate_latest(self, observation, perception, observation_id):
camera = perception["observation"]
recovery = self.mission.recovery
recovery_camera = perception.get("recovery_observation", camera)
recovery.observe_view(perception.get("recovery_view"), recovery_camera["pose"],
recovery_camera["simulation_time_ns"] / 1e9)
self.source.lens_depths = camera["lens_depths"]
values = {
**self.static_values, **perception["values"],
"source.execution-inputs": self.inputs,
"source.camera.rgb": perception["rgb"],
"source.camera.calibration": camera["calibration"],
"source.camera.lens-depths": camera["lens_depths"],
"source.lidar": observation["points"],
"source.range-rays": observation.get("range_rays", {}),
"source.pose": observation["pose"],
"source.simulation-time": observation["simulation_time_ns"] / 1e9,
"source.semantic-observation": perception["semantic_observations"],
"source.detection-views": [
dict(calibration=view["observation"]["calibration"],
lens_depths=view["observation"]["lens_depths"],
boxes=view["values"]["detection.boxes"],
objects=view["values"].get("detection.objects", []),
surface=view["values"]["navigation.surface"])
for view in perception["detection_views"]
],
"source.range-captured-at": observation["captured_at"],
"source.observation-id": observation_id,
}
started, cpu_started = time.monotonic(), time.thread_time()
values.update(self.plan_mission(values))
mission_ms = (time.monotonic() - started) * 1000
mission_cpu_ms = (time.thread_time() - cpu_started) * 1000
started, cpu_started = time.monotonic(), time.thread_time()
values.update(self.navigate(values))
navigation_ms = (time.monotonic() - started) * 1000
navigation_cpu_ms = (time.thread_time() - cpu_started) * 1000
target = getattr(self.mission, "perception_target", self.mission.orientation_target)()
self.supplement_yaw = None
self.recovery_view_request = recovery.view_request(
observation["pose"], observation["simulation_time_ns"] / 1e9) if recovery.active else None
if target is not None:
pose = observation["pose"]
qx, qy, qz, qw = pose[3:]
heading = math.atan2(2 * (qw*qz + qx*qy), 1 - 2 * (qy*qy + qz*qz))
delta = np.asarray(target["xy"]) - pose[:2]
yaw = math.atan2(delta[1], delta[0]) - heading
yaw = math.degrees(math.atan2(math.sin(yaw), math.cos(yaw)))
if abs(yaw) > 45:
self.supplement_yaw = round(yaw / 90) * 90
return values["motion.command"], {
**self.navigation_evidence, "goal": self.goal, "path": values["motion.path"],
"composition_sha256": self.graph.sha256,
"module_ms": {**perception["module_ms"], "simulation-waypoint-mission": mission_ms,
next(node.module.module_id for node in self.graph.nodes
if node.module.group == "motion"): navigation_ms},
"module_thread_ms": {"mission": mission_cpu_ms, "navigation": navigation_cpu_ms},
"perception_frame_id": perception["frame_id"],
"perception_captured_at": camera["captured_at"],
"range_points": len(observation["points"]),
"spatial_goal": self.observed_goals.evidence,
"crossing": values.get("source.crossing-admission"),
}