Files
NODEDC_MISSION_CORE/tests/test_simulation_observer_profiles.py
T

230 lines
9.4 KiB
Python

import importlib.util
import sys
from pathlib import Path
import numpy as np
import pytest
from k1link.simulation.ai_polygon.driving_profiles import permitted_surface
ROOT = Path(__file__).parents[1] / "simulation/ai-polygon"
sys.path.insert(0, str(ROOT))
from inference_preview import InferencePreview # noqa: E402 - Worker adapter source path above.
from observer_camera import ObserverCamera # noqa: E402
def test_operator_camera_never_mutates_sensor_and_free_view_does_not_follow_rover():
camera = ObserverCamera()
body = [1.0, 2.0, 0.4]
sensor = [1.4, 2.0, 1.0]
original = sensor.copy()
camera.update("follow", body, 0, sensor)
input = dict(session="a" * 32, sequence=1, orbit=[0.7, 0.2], move=[0, 0, 0], zoom=0)
first = camera.update("camera", body, 0, sensor, input)
again = camera.update("camera", body, 0, sensor, input)
assert first == again
assert first[0] == sensor and sensor == original
assert first[1][1] > 2 # Operator sees sideways, sensor input stays unchanged.
free = camera.update("overview", body, 0, sensor)
other = camera.update("overview", [100, 100, 0.4], 1, [100, 100, 1])
assert free == other
changed = camera.update(
"overview", body, 0, sensor, dict(input, session="b" * 32, move=[0, 3, 0])
)
assert changed[0] != free[0]
def test_coalesced_camera_totals_apply_once():
def run(sequences):
camera = ObserverCamera()
camera.update("follow", [0, 0, 0], 0, [0, 0, 1])
for seq in sequences:
result = camera.update(
"follow",
[0, 0, 0],
0,
[0, 0, 1],
dict(
session="a" * 32,
sequence=seq,
orbit=[seq * 0.1, 0],
move=[0, 0, 0],
zoom=seq * 0.01,
),
)
return result
assert np.allclose(run([1, 2, 3])[0], run([3, 3])[0])
def test_park_rejects_lawn_and_urban_rejects_carriageway_without_overriding_model_confidence():
labels = np.array([[6, 11, 52, 9, 13, 2]])
candidates = np.ones_like(labels, dtype=bool)
assert permitted_surface(
labels, candidates, "park", "simulation-segformer-ade", {}
).tolist() == [[True, True, True, False, True, False]]
assert permitted_surface(
labels, candidates, "urban", "simulation-segformer-ade", {}
).tolist() == [[False, True, True, False, False, False]]
candidates[0, 0] = False
assert not permitted_surface(labels, candidates, "park", "simulation-segformer-ade", {})[0, 0]
with pytest.raises(ValueError):
permitted_surface(labels, candidates, "unknown", "simulation-segformer-ade", {})
def test_semantic_barrier_survives_smooth_ground_and_expires():
spec = importlib.util.spec_from_file_location(
"semantic_surface", ROOT / "navigation/semantic_surface.py"
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
memory = module.SemanticSurface()
terrain = np.array([[1.01, 2.01, 0.0, 0.0], [2.0, 3.0, 0.0, 0.5]])
memory.observe([[1.01, 2.01, 0, 0]], 0)
assert memory.apply(terrain, 1)[0][0, 3] == 1
assert memory.apply(terrain, 31)[0][0, 3] == 0
memory.observe([[1.01, 2.01, 0, 1]], 32)
assert memory.apply(terrain, 32)[0][0, 3] == 0
assert memory.apply(terrain, 32)[0][1, 3] == 0.5 # Never erase geometric hazards.
def test_uncertain_path_is_not_a_persistent_obstacle_but_cannot_supply_a_goal():
from types import SimpleNamespace
from navigation_client import ComposedInference
from k1link.simulation.ai_polygon.mission_policy import WaypointMission
adapter = ComposedInference.__new__(ComposedInference)
adapter.environment = "park"
adapter.segmenter_id = "simulation-segformer-ade"
adapter.models = SimpleNamespace(labels={})
adapter.mission = WaypointMission([[2, 0]])
from k1link.simulation.ai_polygon.robots import select_robot
from k1link.simulation.ai_polygon.run_inputs import sensor_rig
from k1link.simulation.ai_polygon.source_projection import PinholeSource
robot = select_robot("dcd006-v020")
adapter.geometry = robot["physics"]
adapter.source = PinholeSource(sensor_rig(robot, 0.8))
labels = np.full((512, 512), 13, dtype=np.uint8)
labels[:, :100] = 9 # A lawn is still an explicit profile exclusion.
output = adapter.plan_mission(
{
"navigation.route": None,
"segmentation.known": np.zeros_like(labels, dtype=bool),
"segmentation.labels": labels,
"segmentation.surface": np.zeros_like(labels, dtype=bool),
"source.lidar": np.array([[x, y, 0] for x in [1.5, 2, 2.5] for y in [-0.2, 0, 0.2]]),
"source.pose": [0, 0, 0.37, 0, 0, 0, 1],
"source.simulation-time": 0,
"source.camera.calibration": {
"origin": [0.38, 0, 0.8],
"rotation": np.eye(3).reshape(-1).tolist(),
"intrinsics": [533, 533, 400, 300],
},
}
)
assert output["navigation.goal"] is None
assert not output["navigation.surface"].any()
assert output["navigation.permissions"][:, 100:].all()
assert not output["navigation.permissions"][:, :100].any()
def test_preview_contains_only_real_outputs_with_shared_frame_and_bounded_images(tmp_path):
import base64
import io
import json
from types import SimpleNamespace
from PIL import Image
directory = tmp_path / "camera"
directory.mkdir()
node = SimpleNamespace(
module=SimpleNamespace(
provides=("segmentation.labels", "navigation.surface", "detection.boxes")
),
inputs=(),
)
producer = InferencePreview(directory, SimpleNamespace(sha256="a" * 64, nodes=[node]), "park")
rgb = np.zeros((600, 800, 3), dtype=np.uint8)
values = {
"segmentation.labels": np.full((512, 512), 6, dtype=np.uint8),
"navigation.surface": np.ones((512, 512), dtype=bool),
"detection.boxes": [],
}
producer.publish(rgb, values, {"simulation_time_ns": 123456}, 7)
preview = json.loads((tmp_path / "inference-preview.json").read_text())
assert preview["frame_id"] == 7 and preview["simulation_time_ns"] == 123456
assert [p["id"] for p in preview["layers"]] == ["segmentation", "surface", "detection"]
for layer in preview["layers"]:
raw = base64.b64decode(layer["jpeg"])
assert len(raw) < 75000
assert Image.open(io.BytesIO(raw)).size == (400, 300)
producer.publish(rgb, values, {"simulation_time_ns": 123457}, 8)
assert json.loads((tmp_path / "inference-preview.json").read_text())["frame_id"] == 7
def test_operator_smoothing_converges_and_view_switch_does_not_fly_through_world():
from observer_camera import SmoothView
smoother = SmoothView()
start = [[0, 0, 0], [1, 0, 0], [0, 0, 1]]
goal = [[0, 10, 0], [1, 10, 0], [0, 0, 1]]
assert smoother.update("follow", start, 0) == start
middle = smoother.update("follow", goal, 0.04)
assert 0 < middle[0][1] < 10
settled = smoother.update("follow", goal, 1)
assert settled[0][1] == pytest.approx(10, abs=0.001)
assert smoother.update("camera", start, 1.1) == start
def test_preview_ports_follow_composition_not_incidental_values(tmp_path):
from types import SimpleNamespace
from k1link.simulation.ai_polygon.contracts import InferencePreview as PreviewContract
# This graph consumes only range/pose. Incidental segmentation is not an output.
node = SimpleNamespace(
module=SimpleNamespace(provides=("motion.command",)),
inputs=(("source.lidar", "source"), ("source.pose", "source")),
)
graph = SimpleNamespace(sha256="b" * 64, nodes=[node])
directory = tmp_path / "camera"
directory.mkdir()
values = {
"source.lidar": np.array([[10, 21, 3], [10, 22, 3]]),
"source.pose": [10, 20, 3, 0, 0, 2**-0.5, 2**-0.5],
"segmentation.labels": np.ones((512, 512)),
}
InferencePreview(directory, graph, "park").publish(
np.zeros((600, 800, 3), dtype=np.uint8), values, {"simulation_time_ns": 5}, 1
)
payload = PreviewContract.model_validate_json((tmp_path / "inference-preview.json").read_text())
assert [layer.id for layer in payload.layers] == ["lidar"]
layer = payload.layers[0]
assert layer.points == [(1, 0, 0), (2, 0, 0)]
assert layer.source_count == 2
assert layer.frame == "body-x-forward-y-left-z-up"
raw = payload.model_dump()
raw["layers"].append(dict(raw["layers"][0]))
with pytest.raises(ValueError, match="unique"):
PreviewContract.model_validate(raw)
# A new image-producing module can use its own ID without a UI/API enum edit.
image = {"id": "depth-confidence", "kind": "image", "label": "Depth", "jpeg": "YWJj"}
raw["layers"] = [image]
assert PreviewContract.model_validate(raw).layers[0].id == "depth-confidence"
raw["layers"] = [dict(image, kind="points3d")]
with pytest.raises(ValueError, match="Spatial"):
PreviewContract.model_validate(raw)
def test_lidar_display_sampling_never_mutates_inference_inputs():
from inference_preview import lidar
points = np.arange(9000, dtype=float).reshape(-1, 3)
original = points.copy()
result = lidar(None, {"source.lidar": points, "source.pose": [0, 0, 0, 0, 0, 0, 1]}, {})
assert len(result["points"]) <= 2048 and result["source_count"] == 3000
np.testing.assert_array_equal(points, original)