File size: 13,076 Bytes
e8055cf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 | """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
|