diff --git a/docs/sensor-fusion-architecture.md b/docs/sensor-fusion-architecture.md index 9a8646b..bb2faff 100644 --- a/docs/sensor-fusion-architecture.md +++ b/docs/sensor-fusion-architecture.md @@ -47,9 +47,12 @@ flowchart TD H["SensorRig calibration"] --> I["Fusion core"] F --> I I --> J["TrackCache"] + F --> Q["stochastic transient matcher"] + Q --> R["scene-ray / LOD cache"] G --> K["RGB surface claims"] J --> L["PointCloud PLY"] J --> M["CultCache RenderFrame document"] + R --> M K --> M M --> N["Spout sink / Aquarium GPU renderer"] N --> O["Spout2 sender texture"] @@ -62,6 +65,7 @@ flowchart TD - `localcast.sensor_fusion.adapters` owns driver-facing frame ingress. Its first concrete adapter is an FFmpeg raw BGR reader for the PS3 Eye DirectShow path. - `localcast.sensor_fusion.calibration_space` owns fixed-board common-space calibration: ChArUco corner observations plus intrinsics become `CameraModel.world_from_sensor` transforms in one room frame. - `localcast.sensor_fusion.surface_features` owns cross-view feature observations, descriptor matching, and triangulated surface tracks. It consumes calibrated cameras; it does not invent camera geometry. +- `localcast.sensor_fusion.stochastic_mapping` owns transient feature hypothesis sampling, image-pixel to scene-ray lowering, learned image-ray bias cells, and multi-LOD scene cache packets for later compute-shader reconciliation. - `localcast.sensor_fusion.camera_control` owns measurement-quality policy: luminance, clipping, contrast, and sharpness in; normalized exposure/gain/focus commands out. Driver adapters own translating those commands to OpenCV, DirectShow, vendor tools, or no-op mocks. - `localcast.sensor_fusion.dense_stereo` owns a debug CPU reference for dense calibrated RGB surface claims. It is useful for tests and shader parity, but the live million-splat path belongs to Aquarium/GPU compute. - `localcast.sensor_fusion.active_illumination` owns deliberate light pulses as calibration telemetry. A Tuya bulb is an optional local-network actuator, not a rendering authority; its pulse timestamps are evidence for camera exposure/depth response. @@ -83,6 +87,8 @@ For this project: sensor observation -> calibrated world ray -> triangulated marker claim +-> stochastic transient hypothesis +-> multi-LOD scene cache -> cached track -> render frame packet -> Aquarium brush/splat packet @@ -92,6 +98,8 @@ sensor observation The cache is not a bucket. `TrackCache` has a TTL and confidence update rule so the system can buffer and converge without pretending stale points are fresh. Later GPU buffers should mirror this shape: observation SoA, track SoA, brush packet SoA. +`visual-lod-cache.json` is the current CPU-authored shape for the next compute pass. It is not the final renderer. It groups stochastic/fused scene claims into multiple world-space voxel sizes, carrying center, radius, confidence, count, and source-time bounds so an Aquarium compute shader can reconcile fine and coarse claims without pulling the whole observation history through the renderer. + ## Test Boundaries The core can be tested without cameras: @@ -102,6 +110,7 @@ The core can be tested without cameras: - raw-frame adapter can be tested from an in-memory byte stream - fixed-board ChArUco observations solve camera poses into the expected common frame - matched surface descriptors triangulate to a known 3D point +- stochastic transient matches triangulate descriptor-consistent rays and lower them into a multi-LOD scene cache - adaptive camera control responds to overexposure without live hardware - dense stereo turns shifted textured camera pairs into calibrated RGB surface claims @@ -165,13 +174,14 @@ That lets the final stream compositor buffer point-cloud visuals until they alig 1. Capture ChArUco intrinsics for each camera with `scripts/charuco_calibration.py calibrate`. 2. Capture fixed-board observations from every camera and solve shared extrinsics with `scripts/solve_common_camera_space.py`. 3. Use `scripts/triangulate_surface_features.py` on calibrated image pairs to prove real cross-view surface tracks before promoting the matcher into the live producer. -4. Move dense matching from CPU block search to GPU-resident stereo/flow so the million-sample target is not murdered by Python loops. -5. If a Tuya light is available on the local network, run `scripts/pulse_tuya_light.py` with its local key and align pulse timestamps against camera brightness response. -6. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections. -7. Record an observation run from the two PS3 Eyes into typed CultCache docs. -8. Feed `RenderFramePacket` into Aquarium Engine. -9. Publish the render target as a Spout2 sender and receive it in OBS. -10. Replace compatibility JSON render-frame paths once no deadline script depends on them. +4. Replace the synthetic stochastic transient observations in `scripts/live_sensor_fusion.py` with real ORB/flow observations from PS3 Eye/Kiyo frames. +5. Move dense matching and LOD reconciliation from CPU block search/JSON to GPU-resident stereo/flow and compute-shader cache reduction so the million-sample target is not murdered by Python loops. +6. If a Tuya light is available on the local network, run `scripts/pulse_tuya_light.py` with its local key and align pulse timestamps against camera brightness response. +7. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections. +8. Record an observation run from the two PS3 Eyes into typed CultCache docs. +9. Feed `RenderFramePacket` and the multi-LOD scene cache into Aquarium Engine. +10. Publish the render target as a Spout2 sender and receive it in OBS. +11. Replace compatibility JSON render-frame paths once no deadline script depends on them. ## References diff --git a/localcast/sensor_fusion/__init__.py b/localcast/sensor_fusion/__init__.py index c375762..e36564c 100644 --- a/localcast/sensor_fusion/__init__.py +++ b/localcast/sensor_fusion/__init__.py @@ -37,6 +37,17 @@ from .surface_features import ( orb_surface_observations, triangulate_surface_tracks, ) +from .stochastic_mapping import ( + ImageRayBiasMap, + LODCell, + MultiLODSceneCache, + RayBiasSample, + SceneRay, + TransientMatchHypothesis, + multilod_cache_from_points, + pixel_scene_ray, + stochastic_transient_matches, +) from .audio_overlay import AudioVisualSyncStatus, overlay_audio_events from .media_artifacts import RemoteVideoArtifact, remote_video_artifact_for_present_time from .clap_calibration import ( @@ -90,6 +101,12 @@ __all__ = [ "FrameQuality", "SurfaceFeatureObservation", "SurfaceFeatureTrack", + "ImageRayBiasMap", + "LODCell", + "MultiLODSceneCache", + "RayBiasSample", + "SceneRay", + "TransientMatchHypothesis", "AudioVisualSyncStatus", "AudioTransientCandidate", "CameraMotionPeak", @@ -117,7 +134,10 @@ __all__ = [ "match_surface_features", "measure_frame_quality", "orb_surface_observations", + "multilod_cache_from_points", "overlay_audio_events", + "pixel_scene_ray", + "stochastic_transient_matches", "detect_audio_transients", "detect_camera_motion_peaks", "detect_clap_events", diff --git a/localcast/sensor_fusion/stochastic_mapping.py b/localcast/sensor_fusion/stochastic_mapping.py new file mode 100644 index 0000000..754d8d3 --- /dev/null +++ b/localcast/sensor_fusion/stochastic_mapping.py @@ -0,0 +1,310 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +import json +from pathlib import Path +from typing import Iterable, Sequence + +import numpy as np + +from .core import CameraModel, TriangulatedPoint, triangulate_dlt +from .surface_features import SurfaceFeatureObservation, descriptor_distance + + +@dataclass(frozen=True) +class SceneRay: + sensor_id: str + timestamp_ns: int + uv: np.ndarray + origin: np.ndarray + direction: np.ndarray + confidence: float + + +@dataclass(frozen=True) +class TransientMatchHypothesis: + stable_key: str + observations: tuple[SurfaceFeatureObservation, ...] + xyz: np.ndarray + confidence: float + reprojection_error_px: float + ray_disagreement_m: float + + +@dataclass(frozen=True) +class RayBiasSample: + sensor_id: str + uv: np.ndarray + residual_px: np.ndarray + confidence: float + + +@dataclass +class ImageRayBiasMap: + """Learns a smooth per-sensor image-space correction from reprojection residuals.""" + + cell_size_px: int = 64 + smoothing: float = 0.2 + _cells: dict[tuple[str, int, int], tuple[np.ndarray, float]] = field(default_factory=dict) + + def observe(self, sample: RayBiasSample) -> None: + key = self._key(sample.sensor_id, sample.uv) + previous = self._cells.get(key) + residual = np.asarray(sample.residual_px, dtype=np.float64) + confidence = max(0.0, min(1.0, float(sample.confidence))) + if previous is None: + self._cells[key] = (residual, confidence) + return + current, weight = previous + alpha = self.smoothing * confidence + updated = (1.0 - alpha) * current + alpha * residual + self._cells[key] = (updated, max(weight * 0.98, confidence)) + + def correct_uv(self, sensor_id: str, uv: np.ndarray) -> np.ndarray: + correction, _ = self._cells.get(self._key(sensor_id, uv), (np.zeros(2, dtype=np.float64), 0.0)) + return np.asarray(uv, dtype=np.float64) + correction + + def _key(self, sensor_id: str, uv: np.ndarray) -> tuple[str, int, int]: + point = np.asarray(uv, dtype=np.float64) + return (str(sensor_id), int(point[0] // self.cell_size_px), int(point[1] // self.cell_size_px)) + + def to_dict(self) -> dict: + return { + "cellSizePx": self.cell_size_px, + "smoothing": self.smoothing, + "cells": [ + { + "sensorId": sensor_id, + "cellX": cell_x, + "cellY": cell_y, + "residualPx": [float(value) for value in residual], + "confidence": float(confidence), + } + for (sensor_id, cell_x, cell_y), (residual, confidence) in sorted(self._cells.items()) + ], + } + + +@dataclass(frozen=True) +class LODCell: + level: int + cell: tuple[int, int, int] + center: tuple[float, float, float] + radius_m: float + confidence: float + count: int + source_time_min_ns: int + source_time_max_ns: int + + +@dataclass(frozen=True) +class MultiLODSceneCache: + schema: str + created_monotonic_ns: int + levels: tuple[float, ...] + cells: tuple[LODCell, ...] + + def to_dict(self) -> dict: + return { + "schema": self.schema, + "createdMonotonicNs": int(self.created_monotonic_ns), + "levels": [float(level) for level in self.levels], + "cells": [ + { + "level": cell.level, + "cell": list(cell.cell), + "center": list(cell.center), + "radiusM": cell.radius_m, + "confidence": cell.confidence, + "count": cell.count, + "sourceTimeMinNs": cell.source_time_min_ns, + "sourceTimeMaxNs": cell.source_time_max_ns, + } + for cell in self.cells + ], + } + + def write_json(self, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8") + + +def pixel_scene_ray(camera: CameraModel, uv: np.ndarray, timestamp_ns: int, confidence: float = 1.0) -> SceneRay: + point = np.asarray([float(uv[0]), float(uv[1]), 1.0], dtype=np.float64) + direction_sensor = np.linalg.inv(camera.camera_matrix) @ point + direction_sensor = direction_sensor / max(1.0e-12, np.linalg.norm(direction_sensor)) + rotation = camera.world_from_sensor[:3, :3] + direction_world = rotation @ direction_sensor + direction_world = direction_world / max(1.0e-12, np.linalg.norm(direction_world)) + return SceneRay( + sensor_id=camera.sensor_id, + timestamp_ns=int(timestamp_ns), + uv=np.asarray(uv, dtype=np.float64), + origin=camera.position_world.astype(np.float64), + direction=direction_world.astype(np.float64), + confidence=float(confidence), + ) + + +def stochastic_transient_matches( + observations: Sequence[SurfaceFeatureObservation], + cameras: dict[str, CameraModel], + *, + max_dt_ns: int = 25_000_000, + max_descriptor_distance: float = 48.0, + max_reprojection_error_px: float = 6.0, + samples_per_observation: int = 4, + seed: int = 0, +) -> tuple[TransientMatchHypothesis, ...]: + rng = np.random.default_rng(seed) + usable = [obs for obs in observations if obs.sensor_id in cameras] + hypotheses: list[TransientMatchHypothesis] = [] + for index, left in enumerate(usable): + candidates = [ + right + for right in usable + if right.sensor_id != left.sensor_id + and abs(right.timestamp_ns - left.timestamp_ns) <= max_dt_ns + and descriptor_distance(left.descriptor, right.descriptor) <= max_descriptor_distance + ] + if not candidates: + continue + rng.shuffle(candidates) + for right in candidates[: max(1, int(samples_per_observation))]: + hypothesis = triangulate_hypothesis( + left, + right, + cameras, + max_reprojection_error_px=max_reprojection_error_px, + max_descriptor_distance=max_descriptor_distance, + ) + if hypothesis is not None: + hypotheses.append(hypothesis) + return suppress_duplicate_hypotheses(hypotheses) + + +def triangulate_hypothesis( + left: SurfaceFeatureObservation, + right: SurfaceFeatureObservation, + cameras: dict[str, CameraModel], + *, + max_reprojection_error_px: float, + max_descriptor_distance: float, +) -> TransientMatchHypothesis | None: + cam_a = cameras[left.sensor_id] + cam_b = cameras[right.sensor_id] + try: + xyz = triangulate_dlt(cam_a.projection_matrix, left.uv, cam_b.projection_matrix, right.uv) + except ValueError: + return None + error_a = cam_a.reprojection_error(xyz, left.uv) + error_b = cam_b.reprojection_error(xyz, right.uv) + error = float((error_a + error_b) * 0.5) + if not np.isfinite(error) or error > max_reprojection_error_px: + return None + distance = descriptor_distance(left.descriptor, right.descriptor) + descriptor_score = 1.0 - min(1.0, distance / max(1.0e-9, max_descriptor_distance)) + error_score = 1.0 - min(1.0, error / max(1.0e-9, max_reprojection_error_px)) + ray_distance = closest_ray_distance( + pixel_scene_ray(cam_a, left.uv, left.timestamp_ns, left.confidence), + pixel_scene_ray(cam_b, right.uv, right.timestamp_ns, right.confidence), + ) + ray_score = 1.0 / (1.0 + ray_distance) + confidence = float(min(left.confidence, right.confidence) * (0.4 + 0.3 * descriptor_score + 0.2 * error_score + 0.1 * ray_score)) + return TransientMatchHypothesis( + stable_key=f"transient:{left.sensor_id}:{right.sensor_id}:{left.feature_id}:{right.feature_id}", + observations=(left, right), + xyz=xyz.astype(np.float64), + confidence=confidence, + reprojection_error_px=error, + ray_disagreement_m=float(ray_distance), + ) + + +def closest_ray_distance(left: SceneRay, right: SceneRay) -> float: + p1 = left.origin + d1 = left.direction + p2 = right.origin + d2 = right.direction + cross = np.cross(d1, d2) + denom = float(np.linalg.norm(cross)) + if denom <= 1.0e-9: + return float(np.linalg.norm(np.cross(p2 - p1, d1))) + return float(abs(np.dot(p2 - p1, cross)) / denom) + + +def suppress_duplicate_hypotheses(hypotheses: Iterable[TransientMatchHypothesis]) -> tuple[TransientMatchHypothesis, ...]: + best: dict[str, TransientMatchHypothesis] = {} + for hypothesis in hypotheses: + key = ":".join(sorted(obs.sensor_id for obs in hypothesis.observations)) + ":" + ":".join(sorted(obs.feature_id for obs in hypothesis.observations)) + current = best.get(key) + if current is None or hypothesis.confidence > current.confidence: + best[key] = hypothesis + return tuple(sorted(best.values(), key=lambda item: item.confidence, reverse=True)) + + +def learn_ray_bias_from_points( + cameras: dict[str, CameraModel], + points: Iterable[TriangulatedPoint], + bias_map: ImageRayBiasMap, +) -> ImageRayBiasMap: + for point in points: + for sensor_id in point.sensors: + camera = cameras.get(sensor_id) + if camera is None: + continue + projected = camera.project_world(point.xyz) + bias_map.observe( + RayBiasSample( + sensor_id=sensor_id, + uv=projected, + residual_px=np.zeros(2, dtype=np.float64), + confidence=point.confidence, + ) + ) + return bias_map + + +def multilod_cache_from_points( + points: Iterable[TriangulatedPoint | TransientMatchHypothesis], + *, + levels: tuple[float, ...] = (0.02, 0.08, 0.32), + created_monotonic_ns: int = 0, +) -> MultiLODSceneCache: + items = list(points) + cells: list[LODCell] = [] + for level_index, cell_size in enumerate(levels): + buckets: dict[tuple[int, int, int], list] = {} + for item in items: + xyz = np.asarray(item.xyz, dtype=np.float64) + key = tuple(int(np.floor(value / float(cell_size))) for value in xyz) + buckets.setdefault(key, []).append(item) + for key, bucket in buckets.items(): + weights = np.asarray([max(1.0e-6, float(item.confidence)) for item in bucket], dtype=np.float64) + positions = np.asarray([np.asarray(item.xyz, dtype=np.float64) for item in bucket], dtype=np.float64) + center = np.average(positions, axis=0, weights=weights) + timestamps = [item_timestamp_ns(item) for item in bucket] + cells.append( + LODCell( + level=level_index, + cell=key, + center=tuple(float(value) for value in center), + radius_m=float(cell_size) * 0.5, + confidence=float(np.mean(weights)), + count=len(bucket), + source_time_min_ns=min(timestamps), + source_time_max_ns=max(timestamps), + ) + ) + return MultiLODSceneCache( + schema="localcast.sensor_fusion.multilod_scene_cache.v1", + created_monotonic_ns=int(created_monotonic_ns), + levels=tuple(float(level) for level in levels), + cells=tuple(cells), + ) + + +def item_timestamp_ns(item: TriangulatedPoint | TransientMatchHypothesis) -> int: + if hasattr(item, "timestamp_ns"): + return int(getattr(item, "timestamp_ns")) + return int(max(obs.timestamp_ns for obs in item.observations)) diff --git a/scripts/live_sensor_fusion.py b/scripts/live_sensor_fusion.py index 5ac9dd9..9de860f 100644 --- a/scripts/live_sensor_fusion.py +++ b/scripts/live_sensor_fusion.py @@ -19,10 +19,13 @@ from localcast.sensor_fusion import ( RenderFramePacket, RenderPointPacket, SensorRig, + SurfaceFeatureObservation, dense_stereo_points, measure_frame_quality, + multilod_cache_from_points, put_live_render_frame, lower_points_to_render_frame, + stochastic_transient_matches, ) from localcast.sensor_fusion.camera_control import AdaptiveCameraController, OpenCvCameraSettingPort @@ -75,6 +78,41 @@ def synthetic_observations(rig: SensorRig, now_s: float, count: int) -> list[Obs return observations +def stochastic_surface_observations(observations: list[Observation2D]) -> list[SurfaceFeatureObservation]: + surface: list[SurfaceFeatureObservation] = [] + for obs in observations: + marker_hash = abs(hash(obs.marker_id)) % 255 + descriptor = np.full(32, marker_hash, dtype=np.uint8) + surface.append( + SurfaceFeatureObservation( + sensor_id=obs.sensor_id, + feature_id=obs.marker_id, + timestamp_ns=obs.timestamp_ns, + uv=obs.uv, + descriptor=descriptor, + confidence=obs.confidence, + ) + ) + return surface + + +def transient_match_render_points(matches, timestamp_ns: int) -> tuple[RenderPointPacket, ...]: + points: list[RenderPointPacket] = [] + for match in matches: + confidence = max(0.0, min(1.0, float(match.confidence))) + points.append( + render_point( + f"stochastic:{match.stable_key}", + match.xyz, + 0.018 + 0.020 * confidence, + (1.0, 0.88, 0.32, 0.35 + 0.55 * confidence), + confidence, + timestamp_ns, + ) + ) + return tuple(points) + + def reconstruction_targets(now_s: float, count: int) -> list[np.ndarray]: """Deadline stand-in for real detections: two people plus tracked room support.""" body_count = max(32, int(count * 0.55)) @@ -710,6 +748,8 @@ def main() -> None: parser.add_argument("--leap-height", type=int, default=240) parser.add_argument("--leap-fps", type=float, default=120.0) parser.add_argument("--leap-step", type=int, default=12) + parser.add_argument("--lod-cache", default=str(ROOT / "calibration" / "runs" / "visual-lod-cache.json")) + parser.add_argument("--no-stochastic-transients", action="store_true") args = parser.parse_args() left = camera("ps3eye_left", -0.25) @@ -723,6 +763,7 @@ def main() -> None: start = time.monotonic() frame_id = 0 cache_path = Path(args.cache) + lod_cache_path = Path(args.lod_cache) lock = acquire_runtime_lock(cache_path.with_suffix(".producer.lock")) if lock is None: return @@ -755,6 +796,19 @@ def main() -> None: break observations = synthetic_observations(rig, now, args.points) result = rig.fuse(observations) + transient_matches = () if args.no_stochastic_transients else stochastic_transient_matches( + stochastic_surface_observations(observations), + rig.cameras, + max_descriptor_distance=0.0, + max_reprojection_error_px=0.05, + samples_per_observation=2, + seed=frame_id, + ) + multilod_cache_from_points( + tuple(result.points) + tuple(transient_matches), + levels=(0.02, 0.08, 0.32), + created_monotonic_ns=time.monotonic_ns(), + ).write_json(lod_cache_path) frame = lower_points_to_render_frame( result.points, render_config, @@ -767,6 +821,7 @@ def main() -> None: if leap_sampler is not None and leap_sampler.last_timestamp_ns is not None: timestamp_ns = max(timestamp_ns, leap_sampler.last_timestamp_ns) support_points = dim_fusion_points(tuple(frame.points)) if not rgb_points else () + stochastic_points = transient_match_render_points(transient_matches, timestamp_ns) frame = RenderFramePacket( schema=frame.schema, frame_id=frame.frame_id, @@ -778,7 +833,7 @@ def main() -> None: spout_sender_name=frame.spout_sender_name, target_width=frame.target_width, target_height=frame.target_height, - points=leap_points + rgb_points + support_points, + points=leap_points + rgb_points + stochastic_points + support_points, ) put_live_render_frame(cache_path, frame) frame_id += 1 diff --git a/scripts/live_status.py b/scripts/live_status.py index c16bebd..dba6fc7 100644 --- a/scripts/live_status.py +++ b/scripts/live_status.py @@ -124,6 +124,7 @@ def main() -> None: "audio-phase-field.msgpack", "audio-mic-field.msgpack", "active-probes/active-probes.jsonl", + "visual-lod-cache.json", "stream-spout-status.json", "av-sync-status.json", ] diff --git a/state/map.yaml b/state/map.yaml index 4657a97..6dd5b2c 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -156,6 +156,9 @@ research: capture adapters, detection, triangulation, track caching, and point-cloud export as separate testable authorities. This follows the fractal-domain cache rule: semantic claims first, cached backend lowerings second. + Stochastic transient matching now lowers descriptor-consistent image + observations into scene-ray hypotheses and a multi-LOD world-space cache + for Aquarium compute-shader reconciliation. typed_visual_state: summary: docs/typed-visual-state.md key_decision: > diff --git a/tests/test_stochastic_mapping.py b/tests/test_stochastic_mapping.py new file mode 100644 index 0000000..193ece4 --- /dev/null +++ b/tests/test_stochastic_mapping.py @@ -0,0 +1,100 @@ +import tempfile +import unittest +from pathlib import Path + +import numpy as np + +from localcast.sensor_fusion.core import CameraModel, SensorRig, Observation2D +from localcast.sensor_fusion.stochastic_mapping import ( + ImageRayBiasMap, + RayBiasSample, + multilod_cache_from_points, + pixel_scene_ray, + stochastic_transient_matches, +) +from localcast.sensor_fusion.surface_features import SurfaceFeatureObservation + + +def camera(sensor_id, x): + return CameraModel( + sensor_id=sensor_id, + camera_matrix=np.array([[300.0, 0.0, 160.0], [0.0, 300.0, 120.0], [0.0, 0.0, 1.0]]), + dist_coeffs=np.zeros(5), + world_from_sensor=np.array( + [ + [1.0, 0.0, 0.0, x], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] + ), + width=320, + height=240, + ) + + +class StochasticMappingTests(unittest.TestCase): + def test_pixel_scene_ray_points_through_projected_target(self): + cam = camera("left", -0.25) + target = np.array([0.0, 0.0, 2.0]) + ray = pixel_scene_ray(cam, cam.project_world(target), 100, 0.9) + to_target = target - ray.origin + to_target /= np.linalg.norm(to_target) + + self.assertGreater(float(np.dot(ray.direction, to_target)), 0.999) + + def test_stochastic_transient_matches_triangulate_descriptor_consistent_features(self): + left = camera("left", -0.25) + right = camera("right", 0.25) + target = np.array([0.04, 0.02, 2.0]) + descriptor = np.array([1, 2, 3, 4], dtype=np.uint8) + observations = [ + SurfaceFeatureObservation("left", "a", 1000, left.project_world(target), descriptor, confidence=0.95), + SurfaceFeatureObservation("right", "b", 1200, right.project_world(target), descriptor.copy(), confidence=0.9), + ] + + matches = stochastic_transient_matches( + observations, + {"left": left, "right": right}, + max_descriptor_distance=0.0, + max_reprojection_error_px=0.01, + seed=4, + ) + + self.assertEqual(1, len(matches)) + np.testing.assert_allclose(target, matches[0].xyz, atol=1e-9) + self.assertGreater(matches[0].confidence, 0.7) + + def test_bias_map_applies_cell_correction(self): + bias = ImageRayBiasMap(cell_size_px=32, smoothing=1.0) + bias.observe(RayBiasSample("cam", np.array([45.0, 50.0]), np.array([1.5, -2.0]), 1.0)) + + corrected = bias.correct_uv("cam", np.array([40.0, 42.0])) + + np.testing.assert_allclose(corrected, np.array([41.5, 40.0])) + + def test_multilod_cache_groups_points_for_compute_reconciliation(self): + left = camera("left", -0.25) + right = camera("right", 0.25) + rig = SensorRig(cameras={"left": left, "right": right}) + points = rig.fuse( + [ + Observation2D("left", "a", 100, left.project_world(np.array([0.0, 0.0, 2.0])), 1.0), + Observation2D("right", "a", 100, right.project_world(np.array([0.0, 0.0, 2.0])), 1.0), + Observation2D("left", "b", 110, left.project_world(np.array([0.03, 0.0, 2.0])), 1.0), + Observation2D("right", "b", 110, right.project_world(np.array([0.03, 0.0, 2.0])), 1.0), + ] + ).points + + cache = multilod_cache_from_points(points, levels=(0.02, 0.10), created_monotonic_ns=999) + + self.assertEqual("localcast.sensor_fusion.multilod_scene_cache.v1", cache.schema) + self.assertTrue(any(cell.level == 1 and cell.count == 2 for cell in cache.cells)) + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "lod.json" + cache.write_json(path) + self.assertIn("multilod_scene_cache", path.read_text(encoding="utf-8")) + + +if __name__ == "__main__": + unittest.main()