"""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) def reset(self): super().reset() self.crossing = MarkedCrossing(self.geometry) 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["segmentation.surface"] values["navigation.surface"] = permitted allowed = permissions[indices] known = values["segmentation.known"][indices] & (permitted[indices] | ~allowed) known &= self.camera_source.semantic_pixels(u[visible], v[visible]) sample = { "samples": np.column_stack((points[visible][known], allowed[known].astype(int))).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): 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()] yaw = request["yaw_degrees"] if request else self.supplement_yaw if request and yaw == 0: front["recovery_view"] = request 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): # One bounded supplementary crop, never a full panorama inference. # Keep the same perspective distribution as the task view. A # down-looking crop requires separate model qualification. self.last_supplement = time.monotonic() self.last_recovery_view_request = request extra = self.perceive_view(observation, frame_id, yaw, detect=bool(request)) front["semantic_observations"].append(extra["samples"]) front["supplement"] = extra if request: self.recovery_detection_view = extra front["recovery_view"] = request extra = getattr(self, "recovery_detection_view", None) if extra and time.monotonic()-extra["observation"]["captured_at"] <= 2: front["detection_views"].append(extra) return front def navigate_latest(self, observation, perception, observation_id): camera = perception["observation"] recovery = self.mission.recovery recovery.observe_view(perception.get("recovery_view"), camera["pose"], 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.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"], 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"), }