"""Tests for encoder/geometric.py -- spatial-code schema construction and derivation.""" import json import re import numpy as np import geometric def test_dump_spatial_code(tmp_path): path = tmp_path / "scene.json" geometric.dump_spatial_code({"objects": {}, "appearance order": []}, path) assert path.exists() assert '"appearance order"' in path.read_text() def test_raw_bundle_dispatches_to_explicit_derivation(monkeypatch): expected = ( { "spatial code schema": geometric.EXPLICIT_SPATIAL_CODE_SCHEMA, "objects": {}, "room": {"floor area": "0.0 square meters"}, "closest classes distance meters from": {}, "appearance order": [], }, {}, {}, 1, np.array([0, 1, 0], dtype=np.float32), 0.0, ) seen = {} def fake(scene): seen["scene"] = scene return expected monkeypatch.setattr(geometric, "build_explicit_spatial_code", fake) raw = { "depth": np.ones((1, 2, 2), np.float32), "intr": np.eye(3, dtype=np.float32)[None], "c2w": np.eye(4, dtype=np.float32)[None], "conf": None, "ftimes": np.array([0.0], np.float32), "per": {"chair": {}}, } scene = {"raw_inputs": raw} assert geometric.build_spatial_code(scene) is expected assert seen["scene"] is scene def test_explicit_is_a_derivation_of_compact(monkeypatch): """build_explicit_spatial_code() must always build compact FIRST and derive from it -- not measure geometry independently.""" compact_expected = ( { "spatial code schema": geometric.COMPACT_SPATIAL_CODE_SCHEMA, "objects": {}, "room": {}, }, {}, {}, 1, np.array([0, 1, 0], dtype=np.float32), None, ) seen = {} def fake_compact(scene): seen["scene"] = scene return compact_expected monkeypatch.setattr(geometric, "build_compact_spatial_code", fake_compact) scene = {"raw_inputs": None} code, *_ = geometric.build_explicit_spatial_code(scene) assert seen["scene"] is scene assert code["objects"] == {} def test_exact_math_is_integrated_into_geometric_module(): assert callable(geometric.build_explicit_spatial_code) assert callable(geometric.dump_spatial_code) assert not hasattr(geometric, "_reference") def test_position_reader_accepts_current_and_legacy_formatting(): assert geometric.pos3( { "position": { "x coordinate": "1.25 meters", "y coordinate": "-2.0 meters", "height above floor": "0.5 meters", } } ) == [1.25, -2.0, 0.5] assert geometric.pos3( { "position": { "floor_x_meters": 1.25, "floor_y_meters": -2.0, "height_above_floor_meters": 0.5, } } ) == [1.25, -2.0, 0.5] def test_floor_level_v1_v2_math_is_shared(monkeypatch): points = np.array([[0, 0, z] for z in [0, 0, 0, 1, 10]], np.float32) gravity = np.array([0, 0, 1], np.float32) monkeypatch.delenv("VSI_CODE_V2", raising=False) v1 = geometric._floor_level(points, gravity) monkeypatch.setenv("VSI_CODE_V2", "1") v2 = geometric._floor_level(points, gravity) assert 0 <= v1 < 0.2 assert v2 == 0.0 METERS = re.compile(r"^-?\d+(?:\.\d+)? meters$") SQUARE_METERS = re.compile(r"^\d+(?:\.\d+)? square meters$") def _schema_instance(x, y, z, size, first_time=0.0): pts = np.array( [ [x - size / 2, y, z], [x + size / 2, y, z], [x, y - size / 2, z], [x, y + size / 2, z], ], dtype=np.float32, ) return { "pts": pts, "best_pts": pts, "n": len(pts), "nframes": 1, "first_time": first_time, "frames": {0}, } def _schema_scene(): chair = _schema_instance(0.0, 0.0, 0.5, 0.8, first_time=0.0) table = _schema_instance(1.0, 0.0, 0.7, 1.2, first_time=1.0) floor = np.array( [[x, y, 0.0] for x in np.linspace(-1, 2, 5) for y in np.linspace(-1, 1, 5)], dtype=np.float32, ) return { "instances": {"chair": [chair], "table": [table]}, "stats": {"chair": {"peak": 1}, "table": {"peak": 3}}, "scene_pts": np.concatenate([chair["pts"], table["pts"], floor], axis=0), "cameras": None, } def test_spatial_code_matches_reference_schema(): code, *_ = geometric.build_spatial_code(_schema_scene()) assert list(code) == [ "spatial code schema", "objects", "room", "closest classes distance meters from", "appearance order", ] assert code["spatial code schema"] == geometric.EXPLICIT_SPATIAL_CODE_SCHEMA assert code["appearance order"] == ["chair", "table"] assert SQUARE_METERS.match(code["room"]["floor area"]) for class_data in code["objects"].values(): assert set(class_data) == {"count", "instances"} assert class_data["count"] == len(class_data["instances"]) for instance in class_data["instances"]: assert set(instance) == {"position", "longest dimension"} assert set(instance["position"]) == { "x coordinate", "y coordinate", "height above floor", } assert all(METERS.match(value) for value in instance["position"].values()) assert METERS.match(instance["longest dimension"]) assert code["objects"]["table"]["count"] == 1 chair_to_table = code["closest classes distance meters from"]["chair"]["table"] assert set(chair_to_table) == {"distance", "closeness rank"} assert METERS.match(chair_to_table["distance"]) assert chair_to_table["closeness rank"] == 1 def test_dumped_json_preserves_schema(tmp_path): code, *_ = geometric.build_spatial_code(_schema_scene()) path = tmp_path / "scene.json" geometric.dump_spatial_code(code, path) assert json.loads(path.read_text()) == code def test_compact_spatial_code_exposes_only_reusable_primitives(): code, *_ = geometric.build_spatial_code(_schema_scene(), "compact") assert list(code) == ["spatial code schema", "objects", "room"] assert set(code["objects"]) == {"chair", "table"} assert len(code["objects"]["chair"]) == 1 instance = code["objects"]["chair"][0] assert set(instance) == {"3D oriented bounding box", "first visible time"} box = instance["3D oriented bounding box"] assert set(box) == { "3D oriented bounding box center coordinates", "3D oriented bounding box dimensions", "3D oriented bounding box orientation unit vectors", } assert len(box["3D oriented bounding box center coordinates"]) == 3 assert len(box["3D oriented bounding box dimensions"]) == 3 orientation = np.asarray( box["3D oriented bounding box orientation unit vectors"], dtype=np.float64 ) np.testing.assert_allclose(orientation @ orientation.T, np.eye(3), atol=0.02) assert instance["first visible time"] == 0.0 polygons = code["room"]["floor boundary polygons"] assert len(polygons) == 1 assert len(polygons[0]["outer boundary coordinates"]) >= 3 for hole in polygons[0]["interior hole boundary coordinates"]: assert len(hole) >= 3 assert all(len(coordinate) == 2 for coordinate in hole) assert "closest classes distance meters from" not in code assert "appearance order" not in code def test_explicit_spatial_code_remains_the_default(): default, *_ = geometric.build_spatial_code(_schema_scene()) code, *_ = geometric.build_spatial_code(_schema_scene(), "explicit") assert default == code def test_compact_spatial_code_merges_revisit_instances_and_keeps_earliest_time(): scene = _schema_scene() revisit = dict(scene["instances"]["chair"][0]) revisit.update({"frames": {1}, "first_time": -1.0}) scene["instances"]["chair"].append(revisit) scene["stats"]["chair"] = {"raw": 2, "merged": 2, "peak": 1} code, instances, *_ = geometric.build_spatial_code(scene, "compact") assert len(instances["chair"]) == 1 assert len(code["objects"]["chair"]) == 1 assert code["objects"]["chair"][0]["first visible time"] == -1.0 def test_compact_oriented_box_uses_accumulated_instance_points(): xs = np.linspace(-2.0, 2.0, 80) points = np.stack([xs, np.zeros_like(xs), np.full_like(xs, 0.5)], axis=1) instance = { "pts": points.astype(np.float32), "best_pts": points[38:42].astype(np.float32), "conf": None, } box = geometric._compact_oriented_box( instance, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0.0, ) assert max(box["3D oriented bounding box dimensions"]) > 3.5 def test_compact_floor_boundaries_preserve_disconnected_regions(): first = np.array( [[x, y, 0.0] for x in np.linspace(0, 1, 11) for y in np.linspace(0, 1, 11)] ) second = np.array( [[x, y, 0.0] for x in np.linspace(5, 6, 11) for y in np.linspace(0, 1, 11)] ) polygons = geometric._compact_floor_boundary_polygons( np.concatenate([first, second]), np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0]), ) assert len(polygons) == 2 assert all(len(polygon["outer boundary coordinates"]) >= 3 for polygon in polygons) def test_compact_spatial_code_suppresses_co_visible_duplicate_tracks(): points = np.array( [[x, y, z] for x in (-0.5, 0.5) for y in (-0.5, 0.5) for z in (0.0, 1.0)], dtype=np.float32, ) first = { "pts": points, "best_pts": points, "observations": [points], "frames": {0}, "n": len(points), "nframes": 1, "first_time": 0.0, } second = dict(first) second.update({"pts": points + 0.01, "best_pts": points + 0.01}) scene = { "instances": {"chair": [first, second]}, "stats": {"chair": {"raw": 2, "merged": 2, "peak": 2}}, "scene_pts": np.concatenate([points, points + 0.01]), "cameras": None, } code, instances, *_ = geometric.build_spatial_code(scene, "compact") assert len(instances["chair"]) == 1 assert len(code["objects"]["chair"]) == 1 def test_compact_oriented_box_combines_observation_extents_by_consensus(): narrow_x = np.linspace(-1.0, 1.0, 80) wide_x = np.linspace(-2.0, 2.0, 80) narrow = np.stack( [narrow_x, np.zeros_like(narrow_x), np.full_like(narrow_x, 0.5)], axis=1 ).astype(np.float32) wide = np.stack( [wide_x, np.zeros_like(wide_x), np.full_like(wide_x, 0.5)], axis=1 ).astype(np.float32) instance = { "pts": np.concatenate([narrow, wide]), "best_pts": narrow, "observations": [narrow, wide], "conf": None, } box = geometric._compact_oriented_box( instance, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0.0, ) # The LONGEST axis recovers the fullest observed extent (the wide view's full 4.0 span), # not the cross-observation consensus -- a partial view underestimates true length, so the # object is at least as long as the fullest clean view saw (see _compact_oriented_box's # length-axis decoupling). Width/depth stay on the robust consensus. assert 3.9 < max(box["3D oriented bounding box dimensions"]) <= 4.0 def test_compact_instances_keep_peak_co_visible_hypotheses_by_evidence(): scene = _schema_scene() weak = _schema_instance(4.0, 0.0, 0.5, 0.8, first_time=-1.0) weak.update({"n": 4, "nframes": 1, "frames": {2}}) strong = scene["instances"]["chair"][0] strong.update({"n": 40, "nframes": 3, "frames": {0, 1, 2}}) scene["instances"]["chair"] = [weak, strong] scene["stats"]["chair"] = {"raw": 2, "merged": 2, "peak": 1} code, instances, *_ = geometric.build_spatial_code(scene, "compact") assert len(instances["chair"]) == 1 assert instances["chair"][0]["nframes"] == 3 assert instances["chair"][0]["first_time"] == -1.0 assert len(code["objects"]["chair"]) == 1 def test_compact_oriented_box_rejects_one_inconsistent_observation(): ordinary = np.stack( [ np.linspace(-1.0, 1.0, 80), np.zeros(80), np.full(80, 0.5), ], axis=1, ).astype(np.float32) outlier = ordinary.copy() outlier[:, 0] *= 20 instance = { "pts": np.concatenate([ordinary] * 4 + [outlier]), "best_pts": ordinary, "observations": [ordinary] * 4 + [outlier], "conf": None, } box = geometric._compact_oriented_box( instance, np.array([1.0, 0.0, 0.0]), np.array([0.0, 1.0, 0.0]), np.array([0.0, 0.0, 1.0]), 0.0, ) assert max(box["3D oriented bounding box dimensions"]) < 3.0