AntonioJun commited on
Commit
4485aaa
·
verified ·
1 Parent(s): 9b812c9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .pytest_cache/.gitignore +2 -0
  3. .pytest_cache/CACHEDIR.TAG +4 -0
  4. .pytest_cache/README.md +8 -0
  5. .pytest_cache/v/cache/lastfailed +1 -0
  6. .pytest_cache/v/cache/nodeids +39 -0
  7. .ruff_cache/.gitignore +2 -0
  8. .ruff_cache/0.15.22/10040187112636103012 +0 -0
  9. .ruff_cache/0.15.22/11617920927074839860 +0 -0
  10. .ruff_cache/0.15.22/12280106218009661074 +0 -0
  11. .ruff_cache/0.15.22/15929140425585584679 +0 -0
  12. .ruff_cache/CACHEDIR.TAG +1 -0
  13. __pycache__/geometric.cpython-311.pyc +0 -0
  14. data/caches/segvggt/42897538.npz +3 -0
  15. data/caches/segvggt/42897564.npz +3 -0
  16. data/caches/segvggt/42897688.npz +3 -0
  17. data/caches/segvggt/42898486.npz +3 -0
  18. data/spatial codes/41069025.json +0 -0
  19. data/spatial codes/41069043.json +0 -0
  20. data/spatial codes/41125700.json +0 -0
  21. data/spatial codes/41159525.json +0 -0
  22. data/spatial codes/41159572.json +0 -0
  23. data/spatial codes/41254432.json +0 -0
  24. data/spatial codes/42445981.json +0 -0
  25. data/spatial codes/42445984.json +0 -0
  26. data/spatial codes/42446056.json +0 -0
  27. data/spatial codes/42446103.json +0 -0
  28. data/spatial codes/42446517.json +0 -0
  29. data/spatial codes/42446541.json +0 -0
  30. data/spatial codes/42897538.json +0 -0
  31. encoder/__pycache__/config.cpython-311.pyc +0 -0
  32. encoder/__pycache__/geometric.cpython-311.pyc +3 -0
  33. encoder/config.py.orig +69 -0
  34. encoder/geometric.py +1507 -0
  35. results/symbolic/.ipynb_checkpoints/_summary-checkpoint.json +16 -0
  36. results/symbolic/41069025/0.json +16 -0
  37. results/symbolic/41069025/1.json +16 -0
  38. results/symbolic/41069025/1100.json +20 -0
  39. results/symbolic/41069025/1101.json +20 -0
  40. results/symbolic/41069025/1102.json +20 -0
  41. results/symbolic/41069025/1236.json +19 -0
  42. results/symbolic/41069025/1237.json +19 -0
  43. results/symbolic/41069025/1238.json +19 -0
  44. results/symbolic/41069025/167.json +16 -0
  45. results/symbolic/41069025/168.json +16 -0
  46. results/symbolic/41069025/169.json +16 -0
  47. results/symbolic/41069025/530.json +16 -0
  48. results/symbolic/41069025/680.json +16 -0
  49. results/symbolic/41069025/681.json +16 -0
  50. results/symbolic/41069025/682.json +16 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ encoder/__pycache__/geometric.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
.pytest_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Created by pytest automatically.
2
+ *
.pytest_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
2
+ # This file is a cache directory tag created by pytest.
3
+ # For information about cache directory tags, see:
4
+ # https://bford.info/cachedir/spec.html
.pytest_cache/README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # pytest cache directory #
2
+
3
+ This directory contains data from the pytest's cache plugin,
4
+ which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
5
+
6
+ **Do not** commit this to version control.
7
+
8
+ See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
.pytest_cache/v/cache/lastfailed ADDED
@@ -0,0 +1 @@
 
 
1
+ {}
.pytest_cache/v/cache/nodeids ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ "tests/encoder_tests/test_adapters.py::test_adapt_segvggt_reads_flat_npz",
3
+ "tests/encoder_tests/test_adapters.py::test_adapt_segvggt_requires_cache_or_video",
4
+ "tests/encoder_tests/test_adapters.py::test_validate_normalizes_canonical_geometry",
5
+ "tests/encoder_tests/test_adapters.py::test_validate_rejects_invalid_geometry[scene0-TypeError]",
6
+ "tests/encoder_tests/test_adapters.py::test_validate_rejects_invalid_geometry[scene1-ValueError]",
7
+ "tests/encoder_tests/test_adapters.py::test_validate_rejects_invalid_geometry[scene2-ValueError]",
8
+ "tests/encoder_tests/test_config.py::test_cache_and_code_paths_are_flat",
9
+ "tests/encoder_tests/test_config.py::test_video_path_rejects_unknown_dataset",
10
+ "tests/encoder_tests/test_config.py::test_video_path_requires_unique_match",
11
+ "tests/encoder_tests/test_config.py::test_video_path_searches_dataset_folders",
12
+ "tests/encoder_tests/test_geometric.py::test_dump_spatial_code",
13
+ "tests/encoder_tests/test_geometric.py::test_exact_math_is_integrated_into_geometric_module",
14
+ "tests/encoder_tests/test_geometric.py::test_raw_bundle_dispatches_to_integrated_exact_path",
15
+ "tests/encoder_tests/test_launch.py::test_scenes_deduplicates_manifest_in_order",
16
+ "tests/encoder_tests/test_launch.py::test_visible_gpus_falls_back_to_nvidia_smi",
17
+ "tests/encoder_tests/test_launch.py::test_visible_gpus_uses_environment",
18
+ "tests/encoder_tests/test_render.py::test_build_spatial_code_uses_cached_geometry",
19
+ "tests/encoder_tests/test_render.py::test_write_spatial_code_uses_scene_json",
20
+ "tests/encoder_tests/test_run.py::test_cache_or_load_builds_and_writes_cache",
21
+ "tests/encoder_tests/test_run.py::test_cache_or_load_reads_flat_cache",
22
+ "tests/encoder_tests/test_schema.py::test_dumped_json_preserves_schema",
23
+ "tests/encoder_tests/test_schema.py::test_spatial_code_matches_reference_schema",
24
+ "tests/symbolic_tests/test_launch.py::test_error_analysis_rejects_non_numeric_question_type",
25
+ "tests/symbolic_tests/test_launch.py::test_error_analysis_summarizes_numeric_errors",
26
+ "tests/symbolic_tests/test_launch.py::test_mca_answer_breakdown_distinguishes_outcomes",
27
+ "tests/symbolic_tests/test_launch.py::test_scenes_with_spatial_codes_returns_sorted_stems",
28
+ "tests/symbolic_tests/test_run.py::test_fetch_spatial_code_reads_flat_json",
29
+ "tests/symbolic_tests/test_run.py::test_fetch_spatial_code_reports_missing_file",
30
+ "tests/symbolic_tests/test_run.py::test_find_workspace_root_uses_spatial_codes_folder",
31
+ "tests/symbolic_tests/test_run.py::test_real_questions_for_scene_filters_jsonl",
32
+ "tests/symbolic_tests/test_run.py::test_write_scene_results_uses_one_file_per_question",
33
+ "tests/symbolic_tests/test_solver.py::test_direct_numeric_answers",
34
+ "tests/symbolic_tests/test_solver.py::test_direction_answers_use_floor_coordinates",
35
+ "tests/symbolic_tests/test_solver.py::test_dispatch_returns_none_for_unknown_or_missing_data",
36
+ "tests/symbolic_tests/test_solver.py::test_multiple_choice_distance_and_order_answers",
37
+ "tests/symbolic_tests/test_solver.py::test_route_planning_chains_turns",
38
+ "tests/symbolic_tests/test_solver.py::test_unit_parsers_accept_strings_and_numbers"
39
+ ]
.ruff_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Automatically created by ruff.
2
+ *
.ruff_cache/0.15.22/10040187112636103012 ADDED
Binary file (340 Bytes). View file
 
.ruff_cache/0.15.22/11617920927074839860 ADDED
Binary file (524 Bytes). View file
 
.ruff_cache/0.15.22/12280106218009661074 ADDED
Binary file (220 Bytes). View file
 
.ruff_cache/0.15.22/15929140425585584679 ADDED
Binary file (396 Bytes). View file
 
.ruff_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
__pycache__/geometric.cpython-311.pyc ADDED
Binary file (23.3 kB). View file
 
data/caches/segvggt/42897538.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13514665184cdc839ce2047d51d8f43be345fb613e7e1c89a3d3937d196b3183
3
+ size 18458363
data/caches/segvggt/42897564.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07c43f33272380c2ce02ef19610083e0b9d05f6e1bb16e81c34967770b7eab3f
3
+ size 18458727
data/caches/segvggt/42897688.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e14ff49e05a35db2573c829b7cfd4d9f4b04059bbe9743ca688270a97099434
3
+ size 19440297
data/caches/segvggt/42898486.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:61722187eea321a8ab79b69566dc21bb9a2d7d08903bd62a71587b94d0eb176a
3
+ size 18812771
data/spatial codes/41069025.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/41069043.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/41125700.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/41159525.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/41159572.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/41254432.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42445981.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42445984.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42446056.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42446103.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42446517.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42446541.json ADDED
The diff for this file is too large to render. See raw diff
 
data/spatial codes/42897538.json ADDED
The diff for this file is too large to render. See raw diff
 
encoder/__pycache__/config.cpython-311.pyc ADDED
Binary file (5.48 kB). View file
 
encoder/__pycache__/geometric.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:529ea59de21a2857e00ae338ace5011123a1689190749f6febf3dcdcfc34e2ae
3
+ size 102537
encoder/config.py.orig ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration and path helpers for the VSI spatial-code encoder."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from pathlib import Path
6
+
7
+ MODEL = os.environ.get("VSI_GEOMETRY_MODEL", "segvggt")
8
+ FPS = float(os.environ.get("VSI_FPS", "6"))
9
+
10
+ DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/workspace/data"))
11
+ VSI_ROOT = Path(os.environ.get("VSI_ROOT", DATA_ROOT / "VSI-Bench"))
12
+ JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
13
+ CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", DATA_ROOT / "caches"))
14
+ CODES_ROOT = Path(os.environ.get("VSI_CODES", DATA_ROOT / "spatial codes"))
15
+ SEGVGGT_ROOT = Path(os.environ.get("VSI_SEGVGGT_ROOT", "/root/models/SegVGGT"))
16
+ SEGVGGT_CHECKPOINT = Path(os.environ.get(
17
+ "VSI_SEGVGGT_CHECKPOINT", SEGVGGT_ROOT / "checkpoint/segvggt_scannet200.pt"))
18
+
19
+ VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
20
+
21
+ ADAPTERS = {
22
+ "da3_sam3": "adapt_da3_sam3",
23
+ "segvggt": "adapt_segvggt",
24
+ }
25
+
26
+
27
+ def video_path(scene: str, dataset: str | None = None) -> str:
28
+ """Return the unique MP4 for ``scene`` from the VSI-Bench dataset folders."""
29
+ scene = str(scene)
30
+ datasets = (dataset,) if dataset else VIDEO_DATASETS
31
+ matches: list[Path] = []
32
+ for name in datasets:
33
+ if name not in VIDEO_DATASETS:
34
+ raise ValueError(f"unknown VSI dataset {name!r}; expected one of {VIDEO_DATASETS}")
35
+ candidate = VSI_ROOT / name / f"{scene}.mp4"
36
+ if candidate.is_file():
37
+ matches.append(candidate)
38
+ if not matches:
39
+ searched = ", ".join(str(VSI_ROOT / d / f"{scene}.mp4") for d in datasets)
40
+ raise FileNotFoundError(f"video for scene {scene!r} not found; searched: {searched}")
41
+ if len(matches) > 1:
42
+ raise RuntimeError(f"scene {scene!r} exists in multiple datasets: {matches}")
43
+ return str(matches[0])
44
+
45
+
46
+ def model_cache_dir(model: str | None = None) -> str:
47
+ """Flat cache directory for one model. Scene IDs are filenames, never folders."""
48
+ return str(CACHE_ROOT / (model or MODEL))
49
+
50
+
51
+ def cache_file(scene: str, model: str | None = None) -> str:
52
+ """Canonical cached model output used by the encoder."""
53
+ return str(Path(model_cache_dir(model)) / f"{scene}.pkl.gz")
54
+
55
+
56
+ def segvggt_cache_file(scene: str, model: str | None = None) -> str:
57
+ return str(Path(model_cache_dir(model or "segvggt")) / f"{scene}.npz")
58
+
59
+
60
+ def da3_cache_file(scene: str, model: str | None = None) -> str:
61
+ return str(Path(model_cache_dir(model or "da3_sam3")) / f"{scene}.da3.npz")
62
+
63
+
64
+ def sam3_cache_file(scene: str, model: str | None = None) -> str:
65
+ return str(Path(model_cache_dir(model or "da3_sam3")) / f"{scene}.sam3.pkl.gz")
66
+
67
+
68
+ def spatial_code_path(scene: str) -> str:
69
+ return str(CODES_ROOT / f"{scene}.json")
encoder/geometric.py ADDED
@@ -0,0 +1,1507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Geometric assembler (runs in the pipeline venv). Imported by encoder/render.py.
2
+
3
+ Pure math/assembly -- builds the per-instance spatial code (object positions/sizes, pairwise
4
+ distances, closeness ranks, room outline, camera trajectory, appearance order) FROM
5
+ already-computed depth/pose/masks. Does NOT run DA3 or SAM3, and does not call cache_or_load()
6
+ -- that's run.py's job entirely (the only file that calls the actual model-inference functions).
7
+ Callers may provide raw depth/intr/c2w/conf/ftimes/per inputs or canonical world-space
8
+ geometry. Both paths emit the same compact spatial-code schema.
9
+
10
+ Formerly this file called into perceptual.py (as a dynamically-loaded `pl` module) for its own
11
+ geometry helpers -- build_instances, room_gravity, compute_floor_area, answer_closest_distance,
12
+ to_spatial_code, and everything else in this file below _room_outline(). Those functions are
13
+ now merged in directly, verbatim, since they were never DA3/SAM3 calls -- they're geometric
14
+ computations over already-extracted depth/masks, which is exactly this file's job.
15
+ perceptual.py's OTHER half (the actual model-calling functions) moved to run.py instead;
16
+ perceptual.py itself no longer exists.
17
+
18
+ The spatial code is the sole spatial representation the downstream VLM sees; no answer engine
19
+ is computed here (the harness runs the model).
20
+ """
21
+
22
+ import os
23
+ import json
24
+ import numpy as np
25
+ import cv2
26
+
27
+
28
+ # ==========================================================================================
29
+ # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
30
+ # affect only the math below (build_instances/backproject_frame/etc.), never model inference.
31
+ # ==========================================================================================
32
+
33
+ SCHEMA = [
34
+ "x",
35
+ "y",
36
+ "z",
37
+ "e1",
38
+ "e2",
39
+ "e3",
40
+ "px",
41
+ "pz",
42
+ "size_median",
43
+ "size_IQR",
44
+ "time",
45
+ "n",
46
+ ] # legacy row schema, see to_labeled()
47
+ KD_WORKERS = 4 # KD-tree query threads. Queries here are on small capped (<=4000 pt) clouds, so scipy's
48
+ # workers=-1 ("use all cores") is pathological on a many-core box: it spawns one thread
49
+ # per core (e.g. 256) per tiny query and the thread-spawn overhead dwarfs the work.
50
+ MIN_INSTANCE_PTS = (
51
+ 1 # bare geometry floor only: need >=1 valid depth pixel to place a 3D point.
52
+ )
53
+ # NO quality filtering / dedup -- count = exactly SAM3's tracked masklets (honest)
54
+ FLOOR_BAND = (
55
+ 0.15 # m above the floor to count as floor-level (LEGACY -- currently unreferenced;
56
+ )
57
+ # compute_floor_area now uses the RANSAC gravity plane directly instead)
58
+ # ---- geometry-cleanup levers (improve abs_distance etc.; env-tunable) ----
59
+ # DEPTH_COHERENCE (Tukey-fence bleed removal): SAFE + helpful everywhere -> default ON.
60
+ # ablation: ARKit abs_distance 0.757->0.729 (no harm), ScanNet++ d755 0.443->0.486 (helps).
61
+ # CONF_PCT (per-frame confidence percentile): noisy-dataset ONLY -> default OFF.
62
+ # helps ScanNet++ distance more (~0.56) but DESTROYS clean ARKit (0.757->0.429). Opt in via VSI_CONF_PCT=55.
63
+ CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0"))
64
+ DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
65
+ # cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
66
+ # -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
67
+ DEPTH_EDGE_REFINE = os.environ.get("VSI_DEPTH_EDGE_REFINE", "0") == "1"
68
+ # MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
69
+ # depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
70
+ MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
71
+
72
+
73
+ # ==========================================================================================
74
+ # ROOM/OBJECT GEOMETRY -- gravity, floor basis, per-instance spatial-code records. Merged in
75
+ # from perceptual.py, verbatim.
76
+ # ==========================================================================================
77
+
78
+
79
+ def to_labeled(objects, floor_area):
80
+ """LEGACY per-class summary (kept for --format array-compat). Superseded by to_spatial_code."""
81
+ out = {"objects": {}}
82
+ for cls, row in objects.items():
83
+ d = dict(zip(SCHEMA, row))
84
+ out["objects"][cls] = {
85
+ "count": int(d["n"]),
86
+ "centroid_meters": {"x": d["x"], "y": d["y"], "z": d["z"]},
87
+ "longest_dimension_meters": {
88
+ "median": d["size_median"],
89
+ "iqr": d["size_IQR"],
90
+ },
91
+ "centroid_spread": {
92
+ "eigenvalues": [d["e1"], d["e2"], d["e3"]],
93
+ "principal_axis_xz": [d["px"], d["pz"]],
94
+ },
95
+ "first_seen_seconds": d["time"],
96
+ }
97
+ out["room"] = {"floor_area_square_meters": floor_area}
98
+ return out
99
+
100
+
101
+ def room_up_axis(instances, c2w):
102
+ """up axis = smallest-extent axis of all object points; sign from gravity (floor->camera).
103
+ Floor = densest horizontal slab; cameras are always above it, which fixes the sign.
104
+ Returns (axis_index, signed_unit_vector)."""
105
+ P = np.concatenate([i["pts"] for v in instances.values() for i in v], 0)
106
+ ext = np.percentile(P, 98, 0) - np.percentile(P, 2, 0)
107
+ up = int(np.argmin(ext))
108
+ h, edges = np.histogram(P[:, up], bins=80)
109
+ floor = 0.5 * (edges[h.argmax()] + edges[h.argmax() + 1]) # densest slab = floor
110
+ cam_up = c2w[:, :3, 3][:, up].mean()
111
+ e = np.zeros(3, np.float32)
112
+ e[up] = 1.0 if cam_up > floor else -1.0
113
+ return up, e
114
+
115
+
116
+ def room_gravity(
117
+ depth, intr, c2w, conf, conf_pct=40, stride=12, fstride=15, iters=300, thr=0.05
118
+ ):
119
+ """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
120
+ the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
121
+ Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis)."""
122
+ P = []
123
+ for f in range(0, len(depth), fstride):
124
+ Hd, Wd = depth[f].shape
125
+ ys, xs = np.mgrid[0:Hd:stride, 0:Wd:stride]
126
+ ys = ys.ravel()
127
+ xs = xs.ravel()
128
+ z = depth[f][ys, xs]
129
+ ok = (z > 0) & np.isfinite(z)
130
+ if conf is not None and conf_pct > 0:
131
+ ok &= conf[f][ys, xs] >= np.percentile(conf[f], conf_pct)
132
+ ys, xs, z = ys[ok], xs[ok], z[ok]
133
+ if not len(z):
134
+ continue
135
+ K = intr[f]
136
+ Xc = np.stack(
137
+ [(xs - K[0, 2]) * z / K[0, 0], (ys - K[1, 2]) * z / K[1, 1], z], 1
138
+ )
139
+ P.append((c2w[f][:3, :3] @ Xc.T).T + c2w[f][:3, 3])
140
+ P = np.concatenate(P).astype(np.float64) if P else np.zeros((0, 3))
141
+ cam = c2w[:, :3, 3].mean(0)
142
+ if len(P) < 100: # fallback to axis-extent
143
+ ext = np.percentile(P, 98, 0) - np.percentile(P, 2, 0) if len(P) else np.ones(3)
144
+ ax = int(np.argmin(ext))
145
+ g = np.zeros(3)
146
+ g[ax] = 1.0
147
+ return g, ax
148
+ rng = np.random.RandomState(0)
149
+ best = None
150
+ best_score = -1
151
+ for _ in range(iters):
152
+ a, b, c = P[rng.choice(len(P), 3, False)]
153
+ nrm = np.cross(b - a, c - a)
154
+ ln = np.linalg.norm(nrm)
155
+ if ln < 1e-6:
156
+ continue
157
+ nrm /= ln
158
+ d = -nrm @ a
159
+ side = P @ nrm + d
160
+ ninl = int((np.abs(side) < thr).sum())
161
+ if ninl < 50:
162
+ continue
163
+ score = ninl * max(
164
+ np.mean(side > thr), np.mean(side < -thr)
165
+ ) # big + one-sided = floor
166
+ if score > best_score:
167
+ best_score = score
168
+ best = (nrm, d)
169
+ if best is None:
170
+ ext = np.percentile(P, 98, 0) - np.percentile(P, 2, 0)
171
+ ax = int(np.argmin(ext))
172
+ g = np.zeros(3)
173
+ g[ax] = 1.0
174
+ return g, ax
175
+ nrm, d = best
176
+ if (cam @ nrm + d) < 0:
177
+ nrm = -nrm # orient toward cameras (up)
178
+ return nrm.astype(np.float32), int(np.argmax(np.abs(nrm)))
179
+
180
+
181
+ def pos3(rec):
182
+ """[floor_x, floor_y, height_above_floor] from a spatial-code instance record's named position."""
183
+ p = rec.get("position") or {}
184
+ return [
185
+ p.get("floor_x_meters", 0.0),
186
+ p.get("floor_y_meters", 0.0),
187
+ p.get("height_above_floor_meters", 0.0),
188
+ ]
189
+
190
+
191
+ def _floor_basis(up_vec):
192
+ """Orthonormal floor basis (u, v horizontal; g = up) from the gravity vector. u is the OLD
193
+ floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
194
+ differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
195
+ rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
196
+ all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too."""
197
+ g = np.asarray(up_vec, np.float64)
198
+ g = g / (np.linalg.norm(g) + 1e-12)
199
+ up_ax = int(np.argmax(np.abs(g)))
200
+ floor_axes = [
201
+ a for a in range(3) if a != up_ax
202
+ ] # the two world axes the old frame used
203
+ e0 = np.zeros(3)
204
+ e0[floor_axes[0]] = 1.0 # old floor_x world axis
205
+ u = e0 - (e0 @ g) * g
206
+ u = u / (np.linalg.norm(u) + 1e-12) # project it into the gravity plane
207
+ v = np.cross(g, u)
208
+ if v[floor_axes[1]] < 0:
209
+ v = -v # keep floor_y sign aligned with the old axis
210
+ return u, v, g
211
+
212
+
213
+ def _object_records(insts, count, u, v, g, floor_level):
214
+ """Up to `count` instances, strongest-evidence first (most observed points = best-segmented,
215
+ closest, most geometry). `count` (peak co-visibility) decides HOW MANY; total observed points
216
+ decide WHICH -- no threshold. Positions are projected onto the shared gravity floor basis
217
+ (u, v horizontal; g up; height 0 = floor_level) and emitted directly in THE final spatial
218
+ code shape: unit-strings ("1.4 meters"), spaced keys ("x coordinate"), and exactly two
219
+ fields per instance (position + longest dimension) -- there is no separate raw form.
220
+
221
+ Deliberately does NOT report a per-instance first_seen_seconds: the reported instances are
222
+ chosen by STRONGEST evidence (most points/frames), but the class's true first appearance can
223
+ come from a weaker, earlier masklet that never makes this cut (confirmed empirically -- e.g. a
224
+ brief early detection with few points, superseded here by a longer later observation of
225
+ presumably the same object). A per-instance timestamp here would silently describe a DIFFERENT
226
+ detection than the class-level "first seen" a reader would assume it means. appearance_order
227
+ (built below in build_spatial_code() from min(first_time) over ALL detected masklets, not just
228
+ the reported ones) is the sole reliable source for first-appearance timing."""
229
+ ranked = sorted(insts, key=lambda i: (i["n"], i.get("nframes", 0)), reverse=True)[
230
+ : max(count, 1)
231
+ ]
232
+ recs = []
233
+ for it in ranked:
234
+ c = np.asarray(it["centroid"], np.float64)
235
+ recs.append(
236
+ {
237
+ "position": {
238
+ "x coordinate": f"{round(float(c @ u), 2)} meters",
239
+ "y coordinate": f"{round(float(c @ v), 2)} meters",
240
+ "height above floor": f"{round(float(c @ g - floor_level), 2)} meters",
241
+ },
242
+ "longest dimension": f"{round(float(it['size']), 2)} meters",
243
+ }
244
+ )
245
+ return recs
246
+
247
+
248
+ def to_spatial_code(instances, stats, floor_area, up_axis, up_vec, floor_level):
249
+ """Per-instance spatial code, emitted directly in THE final shape: class -> {count (peak
250
+ co-visibility), instances:[{position, longest dimension}]} plus room -> {"floor area"}.
251
+ Positions are projected onto the GRAVITY floor plane (u, v horizontal via _floor_basis -- the
252
+ SAME frame as compute_floor_area); "height above floor" is along gravity with 0 = on the
253
+ floor. floor_level is the gravity-height of the floor. (up_axis is retained for signature
254
+ compatibility; the frame now derives from up_vec.)"""
255
+ u, v, g = _floor_basis(up_vec)
256
+ out = {"objects": {}}
257
+ for cls, insts in instances.items():
258
+ cnt = int(stats[cls]["peak"])
259
+ out["objects"][cls] = {
260
+ "count": cnt,
261
+ "instances": _object_records(insts, cnt, u, v, g, floor_level),
262
+ }
263
+ out["room"] = {"floor area": f"{floor_area} square meters"}
264
+ return out
265
+
266
+
267
+ # ==========================================================================================
268
+ # DETERMINISTIC ANSWER LAYER (parameter-free; validated on VSI GT). Reads the in-memory
269
+ # instances (pos for direction/route, point clouds for distance). Merged in from
270
+ # perceptual.py, verbatim.
271
+ # ==========================================================================================
272
+
273
+
274
+ def _find_cls(name, classes):
275
+ name = name.strip().lower()
276
+ for c in classes:
277
+ if c == name or c.replace(" ", "") == name.replace(" ", ""):
278
+ return c
279
+ for c in classes:
280
+ if name in c or c in name:
281
+ return c
282
+ return None
283
+
284
+
285
+ def _rep(insts):
286
+ """representative instance = most observed points (best-segmented, validated 8/8 on direction)."""
287
+ return max(insts, key=lambda i: i["n"])
288
+
289
+
290
+ def answer_rel_direction(pA, pB, pC, up_vec, up_ax, mode="hard"):
291
+ """Standing at A facing B, where is C? front/back=dot(C-A,fwd); left/right=dot(C-A, up x fwd).
292
+ Right-handed world (OpenCV cam frame + det+1 c2w) makes up x fwd = left a fixed identity.
293
+ Projection uses the gravity VECTOR (v-(v.g)g), so a tilted floor (ScanNet++) is handled; for an
294
+ axis-aligned up this reduces to zeroing that axis (ARKit unchanged)."""
295
+ g = np.asarray(up_vec, np.float64)
296
+ g = g / (np.linalg.norm(g) + 1e-12)
297
+
298
+ def fl(v):
299
+ w = v.astype(np.float64)
300
+ return w - (w @ g) * g
301
+
302
+ fwd = fl(pB - pA)
303
+ n = np.linalg.norm(fwd)
304
+ if n < 1e-6:
305
+ return None
306
+ fwd /= n
307
+ left = np.cross(g, fwd)
308
+ left /= np.linalg.norm(left) + 1e-9
309
+ d = fl(pC - pA)
310
+ f = float(d @ fwd)
311
+ lateral = float(d @ left)
312
+ if mode == "medium":
313
+ if abs(np.degrees(np.arctan2(lateral, f))) >= 135:
314
+ return "back"
315
+ return "left" if lateral > 0 else "right"
316
+ return f"{'front' if f > 0 else 'back'}-{'left' if lateral > 0 else 'right'}"
317
+
318
+
319
+ def _classify_turn(h_in, h_out, up_vec, up_ax):
320
+ """rotation h_in->h_out in floor plane -> turn left/right/back (135deg = VSI's own 'back' cutoff)."""
321
+ g = np.asarray(up_vec, np.float64)
322
+ g = g / (np.linalg.norm(g) + 1e-12)
323
+
324
+ def fl(v):
325
+ w = v.astype(np.float64)
326
+ return w - (w @ g) * g
327
+
328
+ a, b = fl(h_in), fl(h_out)
329
+ na, nb = np.linalg.norm(a), np.linalg.norm(b)
330
+ if na < 1e-6 or nb < 1e-6:
331
+ return None
332
+ a /= na
333
+ b /= nb
334
+ ang = np.degrees(np.arctan2(float(up_vec @ np.cross(a, b)), float(a @ b)))
335
+ if abs(ang) >= 135:
336
+ return "turn back"
337
+ return "turn left" if ang > 0 else "turn right"
338
+
339
+
340
+ def answer_route(ql, cents, up_vec, up_ax):
341
+ """Chain the turn primitive over the waypoint sequence -> ordered ['turn left/right/back', ...]."""
342
+ import re as _re
343
+
344
+ m = _re.search(r"beginning at the (.+?) (?:and )?facing the (.+?)\.", ql)
345
+ if not m:
346
+ return None
347
+
348
+ def position(name):
349
+ class_name = _find_cls(name, cents)
350
+ return cents[class_name] if class_name else None
351
+
352
+ steps_txt = ql.split(":", 1)[1] if ":" in ql else ql
353
+ steps = _re.findall(
354
+ r"\d+\.\s*(\[please fill in\]|Go forward until the [^0-9\[]+?)(?=\s*\d+\.|$)",
355
+ steps_txt,
356
+ )
357
+ cur_pos = position(m.group(1).strip())
358
+ if cur_pos is None:
359
+ return None
360
+ fac = position(m.group(2).strip())
361
+ cur_head = (fac - cur_pos) if fac is not None else None
362
+ turns = []
363
+ i = 0
364
+ while i < len(steps):
365
+ s = steps[i].strip()
366
+ if s.startswith("Go forward"):
367
+ tp = position(_re.sub(r"^Go forward until the ", "", s).strip().rstrip("."))
368
+ if tp is not None:
369
+ cur_head = tp - cur_pos
370
+ cur_pos = tp
371
+ else:
372
+ nxt = next(
373
+ (
374
+ _re.sub(r"^Go forward until the ", "", steps[j].strip())
375
+ .strip()
376
+ .rstrip(".")
377
+ for j in range(i + 1, len(steps))
378
+ if steps[j].strip().startswith("Go forward")
379
+ ),
380
+ None,
381
+ )
382
+ tp = position(nxt) if nxt else None
383
+ if tp is None or cur_head is None:
384
+ turns.append(None)
385
+ else:
386
+ turns.append(_classify_turn(cur_head, tp - cur_pos, up_vec, up_ax))
387
+ cur_head = tp - cur_pos
388
+ i += 1
389
+ return turns
390
+
391
+
392
+ # ==========================================================================================
393
+ # POINT-CLOUD CLEANING + DISTANCE ANSWERS -- outlier removal, closest-distance queries. Merged
394
+ # in from perceptual.py, verbatim.
395
+ # ==========================================================================================
396
+
397
+
398
+ def _sor(pts, k=16, std=2.0, cap=4000):
399
+ """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
400
+ mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
401
+ k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob)."""
402
+ from scipy.spatial import cKDTree
403
+
404
+ if len(pts) < k + 2:
405
+ return pts
406
+ rs = np.random.RandomState(0)
407
+ P = pts if len(pts) <= cap else pts[rs.choice(len(pts), cap, False)]
408
+ d, _ = cKDTree(P).query(P, k=k + 1, workers=KD_WORKERS)
409
+ md = d[:, 1:].mean(1)
410
+ return P[md <= md.mean() + std * md.std()]
411
+
412
+
413
+ def _main_cluster(pts):
414
+ """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
415
+ object forms a disconnected component (a gap separates two objects); the true object is the largest one.
416
+ Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance."""
417
+ from scipy.spatial import cKDTree
418
+
419
+ if len(pts) < 30:
420
+ return pts
421
+ tree = cKDTree(pts)
422
+ nn, _ = tree.query(pts, k=2)
423
+ eps = 3.0 * float(np.median(nn[:, 1])) # 3x median NN gap (data-derived)
424
+ pairs = tree.query_pairs(eps, output_type="ndarray")
425
+ if len(pairs) == 0:
426
+ return pts
427
+ parent = np.arange(len(pts))
428
+
429
+ def find(x):
430
+ r = x
431
+ while parent[r] != r:
432
+ r = parent[r]
433
+ while parent[x] != r:
434
+ parent[x], x = r, parent[x]
435
+ return r
436
+
437
+ for a, b in pairs:
438
+ ra, rb = find(int(a)), find(int(b))
439
+ if ra != rb:
440
+ parent[ra] = rb
441
+ roots = np.array([find(i) for i in range(len(pts))])
442
+ v, cnt = np.unique(roots, return_counts=True)
443
+ return pts[roots == v[cnt.argmax()]]
444
+
445
+
446
+ def _clean(inst, cap=4000):
447
+ """Outlier removal self-calibrated from the pipeline's OWN per-object signals -- no universal constant,
448
+ no benchmark knob. Cached on the instance so the O(classes^2) distance table cleans each object once.
449
+ (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
450
+ object's OWN median confidence (data-derived cut);
451
+ (2) statistical density outlier removal on the survivors;
452
+ (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster."""
453
+ if inst.get("_cleanpts") is not None:
454
+ return inst["_cleanpts"]
455
+ pts = inst["pts"]
456
+ conf = inst.get("conf")
457
+ rs = np.random.RandomState(0)
458
+ if len(pts) > cap:
459
+ idx = rs.choice(len(pts), cap, False)
460
+ pts = pts[idx]
461
+ conf = conf[idx] if conf is not None else None
462
+ if conf is not None and len(conf) > 20: # self-calibrating: object's OWN median
463
+ keep = conf >= np.median(conf)
464
+ if keep.sum() >= 10:
465
+ pts = pts[keep]
466
+ pts = _sor(pts, cap=cap) # density outlier removal on the survivors
467
+ # NOTE: spatial de-bleeding (_main_cluster) was tried and REVERTED -- "largest cluster = the object" is
468
+ # not guaranteed; when an object's near edge splits off it drops the true closest part (overshoot). You
469
+ # cannot post-hoc recover the true object from a bleeding mask in 3D -- that needs better SOURCE masks.
470
+ inst["_cleanpts"] = pts
471
+ return pts
472
+
473
+
474
+ def answer_closest_distance(instsA, instsB, k=4000):
475
+ """Closest distance between the two objects' point clouds ('closest point of each object'). Points are
476
+ cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
477
+ KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
478
+ boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring."""
479
+ A = _clean(_rep(instsA), cap=k)
480
+ B = _clean(_rep(instsB), cap=k)
481
+ if len(A) == 0 or len(B) == 0:
482
+ return float("inf")
483
+ from scipy.spatial import cKDTree
484
+
485
+ if len(A) <= len(B):
486
+ d, _ = cKDTree(A).query(B, k=1, workers=KD_WORKERS)
487
+ else:
488
+ d, _ = cKDTree(B).query(A, k=1, workers=KD_WORKERS)
489
+ return float(d.min())
490
+
491
+
492
+ def answer_rel_distance(anchor_insts, option_insts):
493
+ """'which option is closest to the anchor?' -> index of the option with min closest-point distance."""
494
+ dists = [
495
+ answer_closest_distance(anchor_insts, oi) if oi is not None else float("inf")
496
+ for oi in option_insts
497
+ ]
498
+ return int(np.argmin(dists)), dists
499
+
500
+
501
+ # ==========================================================================================
502
+ # MASK/DEPTH CLEANUP + BACK-PROJECTION -- per-frame refinement before points enter an
503
+ # instance's point cloud. Merged in from perceptual.py, verbatim.
504
+ # ==========================================================================================
505
+
506
+
507
+ def depth_edges(depth_f, valid_f):
508
+ """Per-frame depth-DISCONTINUITY map: gradient magnitude above median + 3*MAD over the valid pixels.
509
+ The threshold is data-derived (robust, universal statistical cut -- NOT benchmark-tuned). These edges are
510
+ where mask-bleed crosses onto an adjacent object at a different depth."""
511
+ if valid_f.sum() < 100:
512
+ return np.zeros_like(depth_f, bool)
513
+ d = np.where(valid_f, depth_f, np.median(depth_f[valid_f]))
514
+ gy, gx = np.gradient(d)
515
+ grad = np.hypot(gx, gy)
516
+ g = grad[valid_f]
517
+ med = np.median(g)
518
+ mad = np.median(np.abs(g - med)) + 1e-9
519
+ return (grad > med + 3.0 * 1.4826 * mad) & valid_f
520
+
521
+
522
+ try:
523
+ _GUIDED = (
524
+ cv2.ximgproc.guidedFilter
525
+ ) # opencv-contrib; appearance-guided boundary snap
526
+ except AttributeError:
527
+ _GUIDED = None
528
+
529
+
530
+ def refine_mask(mask, rgb):
531
+ """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
532
+ bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
533
+ cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
534
+ variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode."""
535
+ if mask.shape[:2] != rgb.shape[:2]:
536
+ mask = cv2.resize(
537
+ mask.astype(np.uint8),
538
+ (rgb.shape[1], rgb.shape[0]),
539
+ interpolation=cv2.INTER_NEAREST,
540
+ ).astype(bool)
541
+ a = int(mask.sum())
542
+ if a < 60: # too small to refine meaningfully -> 1px erode as before
543
+ me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
544
+ return me if me.any() else mask
545
+ if _GUIDED is not None:
546
+ r = max(
547
+ 4, int(round(0.02 * float(np.hypot(*mask.shape[:2]))))
548
+ ) # radius ~2% of frame diagonal
549
+ eps = (
550
+ float(np.var(rgb.astype(np.float32) / 255.0)) * 0.01 + 1e-6
551
+ ) # smoothness ~ image color variance
552
+ soft = _GUIDED(rgb, mask.astype(np.float32), r, eps)
553
+ out = soft > 0.5
554
+ return out if out.sum() >= 0.4 * a else mask # majority guard: don't over-carve
555
+ # fallback (base opencv, no ximgproc): grabCut seeded FG=mask, PR_FG=dilated ring, BG=far exterior
556
+ try:
557
+ gc = np.full(mask.shape[:2], cv2.GC_PR_BGD, np.uint8)
558
+ dil = cv2.dilate(mask.astype(np.uint8), np.ones((15, 15), np.uint8), 1).astype(
559
+ bool
560
+ )
561
+ er = cv2.erode(mask.astype(np.uint8), np.ones((5, 5), np.uint8), 1).astype(bool)
562
+ gc[dil] = cv2.GC_PR_FGD
563
+ gc[er] = cv2.GC_FGD
564
+ bgm = np.zeros((1, 65), np.float64)
565
+ fgm = np.zeros((1, 65), np.float64)
566
+ cv2.grabCut(rgb, gc, None, bgm, fgm, 3, cv2.GC_INIT_WITH_MASK)
567
+ out = (gc == cv2.GC_FGD) | (gc == cv2.GC_PR_FGD)
568
+ return out if 0.4 * a <= out.sum() <= 1.5 * a else mask
569
+ except Exception:
570
+ me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
571
+ return me if me.any() else mask
572
+
573
+
574
+ def backproject_frame(
575
+ depth_f,
576
+ K,
577
+ c2w_f,
578
+ mask_f,
579
+ conf_f=None,
580
+ conf_thr=0.0,
581
+ valid_f=None,
582
+ return_conf=False,
583
+ edges_f=None,
584
+ ):
585
+ """Return (M,3) world points for the masked pixels of one frame (c2w_f = cam->world 4x4).
586
+ valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
587
+ return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
588
+ edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
589
+ (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection)."""
590
+ Hd, Wd = depth_f.shape
591
+ empty = (
592
+ (np.empty((0, 3), np.float32), np.empty((0,), np.float32))
593
+ if return_conf
594
+ else np.empty((0, 3), np.float32)
595
+ )
596
+ if mask_f.shape != (Hd, Wd):
597
+ mask_f = cv2.resize(
598
+ mask_f.astype(np.uint8), (Wd, Hd), interpolation=cv2.INTER_NEAREST
599
+ ).astype(bool)
600
+ if valid_f is None:
601
+ valid_f = np.isfinite(depth_f) & (depth_f > 0)
602
+ m = mask_f & valid_f
603
+ if conf_f is not None and conf_thr > 0:
604
+ m &= conf_f >= conf_thr
605
+ if (
606
+ edges_f is not None and m.sum() >= 30
607
+ ): # keep the largest depth-coherent piece of the mask
608
+ from scipy import ndimage
609
+
610
+ lab, nlab = ndimage.label(m & ~edges_f)
611
+ if nlab >= 1:
612
+ sizes = np.bincount(lab.ravel())
613
+ sizes[0] = 0
614
+ big = int(sizes.argmax())
615
+ if (
616
+ sizes[big] >= 0.5 * m.sum()
617
+ ): # object is the MAJORITY piece (bleed is a minority)
618
+ m = lab == big
619
+ if not m.any():
620
+ return empty
621
+ ys, xs = np.nonzero(m)
622
+ z = depth_f[ys, xs]
623
+ if DEPTH_COHERENCE and len(z) >= 8:
624
+ # an object is a coherent depth surface; floor/background BLEED pixels are depth outliers.
625
+ # Drop them via the standard Tukey fence (1.5*IQR) on the masked region's depths -- parameter-free.
626
+ q1, q3 = np.percentile(z, [25, 75])
627
+ iqr = q3 - q1
628
+ keep = (z >= q1 - 1.5 * iqr) & (z <= q3 + 1.5 * iqr)
629
+ if keep.sum() >= 1:
630
+ ys, xs, z = ys[keep], xs[keep], z[keep]
631
+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]
632
+ Xc = np.stack([(xs - cx) * z / fx, (ys - cy) * z / fy, z], axis=1) # camera coords
633
+ Xw = (c2w_f[:3, :3] @ Xc.T).T + c2w_f[:3, 3] # -> world
634
+ if return_conf:
635
+ cw = (
636
+ conf_f[ys, xs].astype(np.float32)
637
+ if conf_f is not None
638
+ else np.ones(len(ys), np.float32)
639
+ )
640
+ return Xw.astype(np.float32), cw
641
+ return Xw.astype(np.float32)
642
+
643
+
644
+ # ==========================================================================================
645
+ # INSTANCE BUILDING -- oriented extent, 3D box-overlap re-identification, and the main
646
+ # build_instances() driver that turns per-frame masks into per-class 3D instances. Merged in
647
+ # from perceptual.py, verbatim.
648
+ # ==========================================================================================
649
+
650
+
651
+ def robust_centroid_extent(pts, up_axis=None):
652
+ """median centroid + ORIENTED robust extent.
653
+ If up_axis is given: YAW-ONLY oriented extent -- rotation is found by 2D PCA on the
654
+ floor-projected points only, with the up axis left untouched. This matches VSI-Bench's
655
+ own annotation convention for indoor scans (ScanNet/ARKitScenes OrientedBoundingBox
656
+ objects follow a Manhattan-world assumption: rotated only around the vertical axis,
657
+ never tilted). Unconstrained 3D PCA (the previous behavior) can chase noise on the
658
+ vertical axis for flat/elongated objects and drift away from the true yaw.
659
+ If up_axis is None (unknown at the call site): falls back to unconstrained 3D PCA.
660
+ Either way: parameter-free, rotation-invariant in-plane, p2..p98 robust extent."""
661
+ c = np.median(pts, axis=0)
662
+ X = pts - c
663
+ if len(X) > 5000: # PCA on a sample (deterministic)
664
+ X = X[np.random.RandomState(0).choice(len(X), 5000, False)]
665
+ if up_axis is not None:
666
+ floor_axes = [i for i in range(3) if i != up_axis]
667
+ F = X[:, floor_axes]
668
+ try:
669
+ _, _, Vt2 = np.linalg.svd(F - F.mean(0), full_matrices=False)
670
+ proj_floor = F @ Vt2.T # (N,2) along the object's own floor-plane axes
671
+ except np.linalg.LinAlgError:
672
+ proj_floor = F
673
+ up_col = X[:, up_axis : up_axis + 1] # up axis untouched (yaw-only)
674
+ proj = np.concatenate([proj_floor, up_col], axis=1)
675
+ else:
676
+ try:
677
+ _, _, Vt = np.linalg.svd(X - X.mean(0), full_matrices=False)
678
+ proj = X @ Vt.T # coordinates along principal axes
679
+ except np.linalg.LinAlgError:
680
+ proj = X
681
+ lo = np.percentile(proj, 2, axis=0)
682
+ hi = np.percentile(proj, 98, axis=0)
683
+ ext = np.maximum(hi - lo, 0.0)
684
+ dims = np.sort(ext)[::-1] # the object's 3 oriented side lengths, longest first
685
+ return c.astype(np.float32), float(dims[0]), dims
686
+
687
+
688
+ def _aabb(pts):
689
+ """robust (p2..p98) axis-aligned 3D box of an instance's world points."""
690
+ return np.percentile(pts, 2, axis=0), np.percentile(pts, 98, axis=0)
691
+
692
+
693
+ def merge_by_box_overlap(insts, up_axis=None):
694
+ """Parameter-free 3D re-identification, with a temporal-exclusion gate.
695
+
696
+ SAM3 (a 2D tracker) emits a NEW masklet each time the camera revisits an object, so one
697
+ physical object -> several masklets at the same 3D location. We fuse two same-class masklets
698
+ iff BOTH:
699
+ (a) their measured 3D boxes overlap (or one centroid is inside the other) -- same volume, and
700
+ (b) they NEVER appear in the same frame -- temporal exclusion.
701
+ (b) is the key parameter-free invariant: two masklets co-visible in one frame were tracked by
702
+ SAM3 as distinct objects in that frame, so they ARE distinct (e.g. two chairs around a table);
703
+ we must never merge them, even if depth noise makes their boxes overlap. A revisit-duplicate,
704
+ by contrast, lives in DISJOINT frames. Both tests are exact/measured -- NO tuned threshold.
705
+ """
706
+ n = len(insts)
707
+ if n <= 1:
708
+ return insts
709
+ # Precompute the FULL pairwise box-match as one vectorized boolean matrix. With the per-frame
710
+ # batched detector a class can have 100+ raw instances; the old O(n^3) loop called np.all-based
711
+ # box_match millions of times. Here every pairwise test is one broadcast -> O(1) lookups below.
712
+ lo = np.stack([_aabb(i["pts"])[0] for i in insts]).astype(np.float32) # (n,3)
713
+ hi = np.stack([_aabb(i["pts"])[1] for i in insts]).astype(np.float32) # (n,3)
714
+ cents = np.stack([i["centroid"] for i in insts]).astype(np.float32) # (n,3)
715
+ overlap = (hi[:, None, :] >= lo[None, :, :]).all(-1) & (
716
+ hi[None, :, :] >= lo[:, None, :]
717
+ ).all(-1)
718
+ ins = (cents[:, None, :] >= lo[None, :, :]).all(-1) & (
719
+ cents[:, None, :] <= hi[None, :, :]
720
+ ).all(-1)
721
+ match = (
722
+ overlap | ins | ins.T
723
+ ) # box_match[i,j]: same 3D volume (identical semantics to old code)
724
+ # group-level agglomeration: merge two groups only if their COMBINED frame sets are disjoint
725
+ # (so no two co-visible masklets ever land in one object) AND some cross-pair shares a 3D volume.
726
+ groups = [
727
+ {"members": [i], "frames": set(insts[i].get("frames", set()))} for i in range(n)
728
+ ]
729
+ changed = True
730
+ while changed:
731
+ changed = False
732
+ for a in range(len(groups)):
733
+ for b in range(a + 1, len(groups)):
734
+ if (
735
+ groups[a]["frames"] & groups[b]["frames"]
736
+ ): # co-visible -> distinct objects
737
+ continue
738
+ if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
739
+ groups[a]["members"] += groups[b]["members"]
740
+ groups[a]["frames"] |= groups[b]["frames"]
741
+ groups.pop(b)
742
+ changed = True
743
+ break
744
+ if changed:
745
+ break
746
+ merged = []
747
+ for g in groups:
748
+ idxs = g["members"]
749
+ pts = np.concatenate([insts[k]["pts"] for k in idxs], 0)
750
+ cpts = np.concatenate(
751
+ [
752
+ insts[k].get("conf", np.ones(len(insts[k]["pts"]), np.float32))
753
+ for k in idxs
754
+ ],
755
+ 0,
756
+ )
757
+ best = max(
758
+ (insts[k]["best_pts"] for k in idxs), key=len
759
+ ) # largest single obs in the group
760
+ c, longest, dims = robust_centroid_extent(
761
+ best, up_axis
762
+ ) # size+pos+3 oriented dims from best view (#2/#4)
763
+ merged.append(
764
+ {
765
+ "centroid": c,
766
+ "size": longest,
767
+ "dims": dims,
768
+ "first_time": min(insts[k]["first_time"] for k in idxs),
769
+ "pts": pts,
770
+ "conf": cpts,
771
+ "best_pts": best,
772
+ "n": sum(insts[k]["n"] for k in idxs),
773
+ "nframes": len(g["frames"]),
774
+ }
775
+ ) # track persistence (evidence strength)
776
+ return merged
777
+
778
+
779
+ def build_instances(
780
+ per_class, depth, intr, c2w, conf, frame_times, frame_paths=None, up_axis=None
781
+ ):
782
+ """-> {class: [ {centroid(3), size(longest dim), first_time, npts} ]}
783
+ up_axis: if known (from room_gravity, computed BEFORE this call), threads through to
784
+ robust_centroid_extent for yaw-only oriented sizing. If None, size falls back to
785
+ unconstrained 3D PCA."""
786
+ out = {}
787
+ stats = {}
788
+ nframes = len(depth)
789
+ # precompute each frame's valid-depth mask ONCE (was recomputed per mask -> per class).
790
+ valid = {}
791
+ edges = {}
792
+ rgb = {}
793
+ used_frames = {fi for frames in per_class.values() for fi in frames if fi < nframes}
794
+ for fi in used_frames:
795
+ valid[fi] = np.isfinite(depth[fi]) & (depth[fi] > 0)
796
+ edges[fi] = depth_edges(depth[fi], valid[fi]) if DEPTH_EDGE_REFINE else None
797
+ if MASK_REFINE and frame_paths and fi < len(frame_paths):
798
+ im = cv2.imread(frame_paths[fi]) # BGR; guidedFilter/grabCut want 3ch uint8
799
+ rgb[fi] = (
800
+ cv2.resize(im, (depth[fi].shape[1], depth[fi].shape[0]))
801
+ if im is not None
802
+ else None
803
+ )
804
+ for cls, frames in per_class.items():
805
+ # peak co-visibility: max distinct masklets SAM3 tracks SIMULTANEOUSLY in any one frame.
806
+ # geometry-free, parameter-free, immune to revisit over-count; provable lower bound on count.
807
+ peak = max((len(objs) for objs in frames.values()), default=0)
808
+ # gather world points + first-seen time + frame set per obj_id (SAM3 track id = masklet)
809
+ pts_by_id, conf_by_id, first_t, frames_by_id = {}, {}, {}, {}
810
+ # px_by_id: (fidx, frame_time, mask_pixel_count) per obj_id, for appearance-order timing.
811
+ # VSI-Bench's own GT defines "first appearance" as the timestamp where an object's pixel
812
+ # count crosses a threshold (paper appendix B.1) -- NOT the first frame with any pixel at
813
+ # all. A single stray mask-bleed/false-positive pixel would otherwise register as "first
814
+ # seen" far too early. The threshold is self-calibrated per instance (that instance's OWN
815
+ # median observed pixel count across its frames), same convention as _clean's median cut.
816
+ px_by_id = {}
817
+ for fidx, objs in frames.items():
818
+ if fidx >= nframes: # guard: SAM3 frame idx vs DA3 frames
819
+ continue
820
+ for oid, mask in objs.items():
821
+ if MASK_REFINE and rgb.get(fidx) is not None:
822
+ me = (
823
+ mask
824
+ if os.environ.get("VSI_NO_REFINE") == "1"
825
+ else refine_mask(mask, rgb[fidx])
826
+ ) # appearance-guided boundary snap (clips same-depth bleed)
827
+ else:
828
+ # erode 1px to drop mask-edge / background depth bleed
829
+ me = cv2.erode(
830
+ mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1
831
+ ).astype(bool)
832
+ if not me.any():
833
+ me = mask
834
+ conf_f = conf[fidx] if conf is not None else None
835
+ conf_thr = (
836
+ np.percentile(conf_f, CONF_PCT)
837
+ if (conf_f is not None and CONF_PCT > 0)
838
+ else 0.0
839
+ )
840
+ Xw, cw = backproject_frame(
841
+ depth[fidx],
842
+ intr[fidx],
843
+ c2w[fidx],
844
+ me,
845
+ conf_f,
846
+ conf_thr=conf_thr,
847
+ valid_f=valid.get(fidx),
848
+ return_conf=True,
849
+ edges_f=edges.get(fidx),
850
+ )
851
+ if len(Xw):
852
+ pts_by_id.setdefault(oid, []).append(Xw)
853
+ conf_by_id.setdefault(oid, []).append(
854
+ cw
855
+ ) # per-point DA3 confidence (for _clean)
856
+ frames_by_id.setdefault(oid, set()).add(
857
+ fidx
858
+ ) # for co-occurrence gate
859
+ t = frame_times[fidx]
860
+ px_by_id.setdefault(oid, []).append((fidx, t, int(me.sum())))
861
+ # appearance_order timing: per instance, first frame at/above its OWN median pixel count
862
+ for oid, obs in px_by_id.items():
863
+ counts = [c for _, _, c in obs]
864
+ thresh = float(np.median(counts))
865
+ crossing = [t for _, t, c in obs if c >= thresh]
866
+ first_t[oid] = min(crossing) if crossing else min(t for _, t, c in obs)
867
+ insts = []
868
+ for oid, plist in pts_by_id.items():
869
+ pts = np.concatenate(plist, 0)
870
+ cpts = np.concatenate(conf_by_id[oid], 0)
871
+ if len(pts) < MIN_INSTANCE_PTS:
872
+ continue
873
+ best = max(
874
+ plist, key=len
875
+ ) # #2/#4: largest single-frame observation (closest/most pixels)
876
+ bc, bsize, bdims = robust_centroid_extent(
877
+ best, up_axis
878
+ ) # size + position + 3 oriented dims from best view
879
+ insts.append(
880
+ {
881
+ "centroid": bc,
882
+ "size": bsize,
883
+ "dims": bdims,
884
+ "first_time": first_t[oid],
885
+ "pts": pts,
886
+ "conf": cpts,
887
+ "best_pts": best,
888
+ "n": len(pts),
889
+ "frames": frames_by_id[oid],
890
+ }
891
+ )
892
+ raw = len(insts)
893
+ # 3D re-ID: fuse same-class masklets that occupy the same measured 3D volume (parameter-free).
894
+ insts = merge_by_box_overlap(insts, up_axis)
895
+ if insts:
896
+ out[cls] = insts
897
+ stats[cls] = {"raw": raw, "merged": len(insts), "peak": peak}
898
+ return out, stats
899
+
900
+
901
+ # ==========================================================================================
902
+ # PER-CLASS SUMMARY + FLOOR AREA -- legacy array-schema row builder, and the room-scale floor
903
+ # area calculation. Merged in from perceptual.py, verbatim.
904
+ # ==========================================================================================
905
+
906
+
907
+ # ---- Per-class spatial code (legacy array-schema row) -------------------------------------
908
+ def class_spatial_code(insts, peak=0):
909
+ cents = np.stack([i["centroid"] for i in insts], 0) # (n,3)
910
+ sizes = np.array([i["size"] for i in insts], np.float32)
911
+ n = len(insts) # merged centroids (for spatial stats)
912
+ count = peak if peak else n # reported count = peak co-visibility
913
+ x, y, z = cents.mean(0)
914
+ if n == 1:
915
+ e1 = e2 = e3 = px = pz = 0.0
916
+ size_iqr = 0.0
917
+ else:
918
+ cov = np.cov(cents.T) # 3x3
919
+ vals, vecs = np.linalg.eigh(cov) # ascending
920
+ order = np.argsort(vals)[::-1]
921
+ vals = np.clip(vals[order], 0, None)
922
+ vecs = vecs[:, order]
923
+ e1, e2, e3 = vals.tolist()
924
+ pv = vecs[:, 0] # principal eigenvector
925
+ px, pz = float(pv[0]), float(pv[2])
926
+ q1, q3 = np.percentile(sizes, [25, 75])
927
+ size_iqr = float(q3 - q1)
928
+ size_median = float(np.median(sizes))
929
+ first_time = float(min(i["first_time"] for i in insts))
930
+ row = [x, y, z, e1, e2, e3, px, pz, size_median, size_iqr, first_time, count]
931
+ row = [
932
+ (lambda r: 0.0 if r == 0 else r)(round(float(v), 1)) for v in row
933
+ ] # kill -0.0
934
+ row[-1] = int(count)
935
+ return row
936
+
937
+
938
+ # ---- floor_area (full-scene min-Y points -> XZ convex hull) -------------------------------
939
+ def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
940
+ pts = []
941
+ for f in range(depth.shape[0]):
942
+ Hd, Wd = depth[f].shape
943
+ ys, xs = np.mgrid[0:Hd:stride, 0:Wd:stride]
944
+ ys = ys.ravel()
945
+ xs = xs.ravel()
946
+ z = depth[f][ys, xs]
947
+ ok = np.isfinite(z) & (z > 0)
948
+ if sky is not None:
949
+ ok &= ~sky[f][ys, xs].astype(bool)
950
+ if conf is not None:
951
+ ok &= conf[f][ys, xs] >= np.percentile(conf[f], 40)
952
+ ys, xs, z = ys[ok], xs[ok], z[ok]
953
+ if not len(z):
954
+ continue
955
+ K = intr[f]
956
+ fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]
957
+ Xc = np.stack([(xs - cx) * z / fx, (ys - cy) * z / fy, z], 1)
958
+ Xw = (c2w[f][:3, :3] @ Xc.T).T + c2w[f][:3, 3]
959
+ pts.append(Xw.astype(np.float32))
960
+ if not pts:
961
+ return 0.0
962
+ P = np.concatenate(pts, 0)
963
+ if up_vec is not None:
964
+ # VSI-faithful: area in the plane orthogonal to GRAVITY (RANSAC floor normal), like the
965
+ # benchmark's gravity-aligned GT meshes. Build an orthonormal in-plane basis (u, v).
966
+ g = np.asarray(up_vec, np.float64)
967
+ g /= np.linalg.norm(g) + 1e-12
968
+ a = np.array([1.0, 0.0, 0.0]) if abs(g[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
969
+ u = np.cross(g, a)
970
+ u /= np.linalg.norm(u)
971
+ v = np.cross(g, u)
972
+ F_full = np.stack([P @ u, P @ v], 1)
973
+ else:
974
+ up = int(
975
+ np.argmin(P.max(0) - P.min(0))
976
+ ) # legacy: vertical = smallest-extent axis
977
+ floor_axes = [i for i in range(3) if i != up]
978
+ F_full = P[:, floor_axes]
979
+ # VSI-Bench room-size definition = alpha-shape of the floor-plane point cloud (confirmed in their
980
+ # paper appendix). VSI does not publish the alpha value they use for their own GT mesh, so alpha=2
981
+ # here is NOT a matched/verified constant -- it was chosen empirically for this pipeline's own
982
+ # (sparser) reconstructed point density. This is the one disclosed benchmark-adjacent tuned constant
983
+ # in the whole file; everything else is exact/derived or a generic, non-tuned statistical convention.
984
+ # (Falls back to enclosed-fill below if the alphashape package isn't available.)
985
+ F = F_full
986
+ lo = np.percentile(F, 0.5, 0)
987
+ hi = np.percentile(F, 99.5, 0) # gentle clip (preserve room extent)
988
+ F = F[
989
+ (F[:, 0] >= lo[0])
990
+ & (F[:, 0] <= hi[0])
991
+ & (F[:, 1] >= lo[1])
992
+ & (F[:, 1] <= hi[1])
993
+ ]
994
+ if len(F) < 10:
995
+ return 0.0
996
+ try:
997
+ import alphashape
998
+
999
+ idx = np.random.RandomState(0).choice(len(F), min(10000, len(F)))
1000
+ return round(
1001
+ float(alphashape.alphashape(F[idx], alpha=2).area), 1
1002
+ ) # alpha=2 tuned for recon density
1003
+ except Exception:
1004
+ from scipy import ndimage
1005
+
1006
+ res = 0.10
1007
+ ai = ((F[:, 0] - F[:, 0].min()) / res).astype(int)
1008
+ bi = ((F[:, 1] - F[:, 1].min()) / res).astype(int)
1009
+ grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
1010
+ grid[ai + 1, bi + 1] = 1
1011
+ grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1012
+ grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1013
+ return round(float(grid.sum()) * res * res, 1)
1014
+
1015
+
1016
+ # ---------------------------------------------------------------------------
1017
+
1018
+ # ==========================================================================================
1019
+ # SPATIAL CODE ASSEMBLY -- the top-level entry point this whole file exists for:
1020
+ # build_spatial_code() calls everything above to turn already-computed depth/pose/masks into
1021
+ # the final spatial code dict. Room outline + JSON writer. This section was already in
1022
+ # geometric.py before the perceptual.py merge; build_spatial_code() below is updated to call
1023
+ # the geometry functions above DIRECTLY (no `pl.` prefix -- they're plain local functions now
1024
+ # that everything is in one file), same logic, unchanged otherwise.
1025
+ # ==========================================================================================
1026
+
1027
+
1028
+ def _room_outline(depth, intr, c2w, conf, bu, bv):
1029
+ """(Currently unemitted -- the one spatial code shape has no room outline field; this
1030
+ math is kept intact for reuse.) Room floor-boundary polygon from the SAME grid as
1031
+ compute_floor_area: floor points
1032
+ projected onto the shared gravity plane (bu, bv), 10cm grid, close 7x7, fill holes,
1033
+ largest contour, 0.2m polygon simplification. Same (bu, bv) as objects/camera, so the
1034
+ outline, object positions, and floor_area all live in one consistent frame."""
1035
+ from scipy import ndimage
1036
+
1037
+ pts, stride = [], 8
1038
+ for f in range(0, depth.shape[0], 3):
1039
+ Hd, Wd = depth[f].shape
1040
+ ys, xs = np.mgrid[0:Hd:stride, 0:Wd:stride]
1041
+ ys = ys.ravel()
1042
+ xs = xs.ravel()
1043
+ z = depth[f][ys, xs]
1044
+ ok = np.isfinite(z) & (z > 0)
1045
+ if conf is not None:
1046
+ ok &= conf[f][ys, xs] >= np.percentile(conf[f], 40)
1047
+ ys, xs, z = ys[ok], xs[ok], z[ok]
1048
+ if not len(z):
1049
+ continue
1050
+ K = intr[f]
1051
+ Xc = np.stack(
1052
+ [(xs - K[0, 2]) * z / K[0, 0], (ys - K[1, 2]) * z / K[1, 1], z], 1
1053
+ )
1054
+ pts.append(((c2w[f][:3, :3] @ Xc.T).T + c2w[f][:3, 3]).astype(np.float32))
1055
+ if not pts:
1056
+ return []
1057
+ Pw = np.concatenate(pts, 0)
1058
+ P = np.stack(
1059
+ [Pw @ bu, Pw @ bv], 1
1060
+ ) # gravity-plane projection (same bu,bv as objects/area)
1061
+ lo = np.percentile(P, 0.5, 0)
1062
+ hi = np.percentile(P, 99.5, 0)
1063
+ P = P[
1064
+ (P[:, 0] >= lo[0])
1065
+ & (P[:, 0] <= hi[0])
1066
+ & (P[:, 1] >= lo[1])
1067
+ & (P[:, 1] <= hi[1])
1068
+ ]
1069
+ if len(P) < 10:
1070
+ return []
1071
+ res = 0.10
1072
+ x0, y0 = P[:, 0].min(), P[:, 1].min()
1073
+ ai = ((P[:, 0] - x0) / res).astype(int)
1074
+ bi = ((P[:, 1] - y0) / res).astype(int)
1075
+ grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
1076
+ grid[ai + 1, bi + 1] = 1
1077
+ grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1078
+ grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1079
+ cs, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1080
+ if not cs:
1081
+ return []
1082
+ poly = cv2.approxPolyDP(max(cs, key=cv2.contourArea), 0.2 / res, True)[:, 0, :]
1083
+ # cv2 contour points are (col=bi, row=ai) -> (floor_y, floor_x)
1084
+ return [
1085
+ {
1086
+ "floor_x_meters": round(float((r - 1) * res + x0), 1),
1087
+ "floor_y_meters": round(float((c - 1) * res + y0), 1),
1088
+ }
1089
+ for c, r in poly
1090
+ ]
1091
+
1092
+
1093
+ def build_spatial_code_raw(depth, intr, c2w, conf, ftimes, per):
1094
+ """Builds THE spatial code -- the one and only shape a spatial code has, everywhere
1095
+ (on disk, in prompts, in this pipeline): unit-strings ("1.4 meters"), spaced keys
1096
+ ("x coordinate"), per-instance position + longest dimension only, room "floor area",
1097
+ "closest classes distance meters from" (rooted per class, distance + closeness rank),
1098
+ and a flat earliest-first "appearance order" list of class names. There is no separate
1099
+ raw/rendered split and no schema flag -- the old v1/v2 branching (VSI_CODE_V2) and the
1100
+ raw intermediate form (floor_x_meters keys, bounding_box, dimensions_meters,
1101
+ seen_in_video_frames, camera_trajectory, room.outline) are gone; every underlying VALUE
1102
+ that survives is computed by exactly the same math as before, only the emitted fields
1103
+ and their formatting changed."""
1104
+ # emission-time class rename: VSI's questions say 'coat rack' while their annotations
1105
+ # (and hence the SAM3 prompt + caches) say 'coat hanger' -- same object, their naming
1106
+ # seam. The model sees questions, so emitted codes follow the question vocabulary.
1107
+ _ALIAS = {"coat hanger": "coat rack"}
1108
+ per = {_ALIAS.get(k, k): v for k, v in per.items()}
1109
+ inst, stats = build_instances(per, depth, intr, c2w, conf, ftimes)
1110
+ up_vec, up_ax = room_gravity(
1111
+ depth, intr, c2w, conf
1112
+ ) # gravity = RANSAC floor normal (VSI-faithful)
1113
+ bu, bv, bg = _floor_basis(
1114
+ up_vec
1115
+ ) # shared gravity floor frame (bu,bv horizontal, bg up)
1116
+ P = np.concatenate([i["pts"] for cl in inst.values() for i in cl], 0)
1117
+ # floor = robust bottom of observed geometry along gravity (low percentile).
1118
+ floor_level = float(np.percentile(P @ bg, 2))
1119
+ fa = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
1120
+ code = to_spatial_code(inst, stats, fa, up_ax, up_vec, floor_level)
1121
+ cls = list(inst.keys())
1122
+ class_first = {c: min(i["first_time"] for i in v) for c, v in inst.items()}
1123
+
1124
+ # Keyed dict + integer ranks (not a sorted list): each question option becomes ONE
1125
+ # direct key access, and "which is closest" = min over small integers -- the filtered
1126
+ # list-scan and decimal comparison were the observed failure modes even on GT data.
1127
+ # 2-decimal distances: 0.1m rounding costs up to ~17% relative error on sub-meter
1128
+ # answers, which fails the strictest MRA thresholds even with perfect values.
1129
+ ccf = {}
1130
+ for a in cls:
1131
+ ds = sorted(
1132
+ (round(answer_closest_distance(inst[a], inst[b]), 2), b)
1133
+ for b in cls
1134
+ if b != a
1135
+ )
1136
+ ccf[a] = {
1137
+ b: {"distance": f"{d} meters", "closeness rank": i + 1}
1138
+ for i, (d, b) in enumerate(ds)
1139
+ }
1140
+ code["closest classes distance meters from"] = ccf
1141
+
1142
+ # Class names only, no first_seen_seconds value -- a reader only ever needs the ORDER
1143
+ # (which appearance order already sorts for them), never the raw timestamp; showing the
1144
+ # timestamp invited re-deriving/re-sorting instead of just reading the given order (observed
1145
+ # empirically), and it duplicated per-instance timing that lives nowhere else in the code now.
1146
+ code["appearance order"] = [
1147
+ c for c, t in sorted(class_first.items(), key=lambda kv: kv[1])
1148
+ ]
1149
+ return code, inst, stats, up_ax, up_vec, fa
1150
+
1151
+
1152
+ def dump_spatial_code(code, path):
1153
+ """Save a spatial_code.json exactly like json.dump(code, f, indent=1), EXCEPT
1154
+ "appearance order" is written as one compact line instead of one line per entry -- it's a
1155
+ single ordered sequence meant to be scanned, not structured data meant to be read field by
1156
+ field like the rest of the code. Every writer of spatial_code.json should go through this
1157
+ (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart."""
1158
+ body = dict(code)
1159
+ ao = body.pop("appearance order", None)
1160
+ text = json.dumps(body, indent=1).rstrip()
1161
+ if ao is not None:
1162
+ assert text.endswith("}")
1163
+ text = text[:-1].rstrip() + ',\n "appearance order": ' + json.dumps(ao) + "\n}"
1164
+ with open(path, "w") as f:
1165
+ f.write(text)
1166
+
1167
+
1168
+ # Canonical world-space fallback used by SegVGGT and similar adapters.
1169
+ def _canonical_room_gravity(P, cameras=None, iters=300, thr=0.05):
1170
+ """Robust UP vector = normal of the RANSAC floor plane, oriented toward the cameras."""
1171
+ P = np.asarray(P, np.float64)
1172
+ P = P[np.isfinite(P).all(1)]
1173
+ if len(P) > 100000:
1174
+ P = P[np.random.RandomState(0).choice(len(P), 100000, False)]
1175
+ cam = (
1176
+ np.asarray(cameras, np.float64).mean(0)
1177
+ if cameras is not None and len(cameras)
1178
+ else None
1179
+ )
1180
+ if len(P) < 100:
1181
+ ext = np.percentile(P, 98, 0) - np.percentile(P, 2, 0) if len(P) else np.ones(3)
1182
+ ax = int(np.argmin(ext))
1183
+ g = np.zeros(3)
1184
+ g[ax] = 1.0
1185
+ return (g, ax)
1186
+ rng = np.random.RandomState(0)
1187
+ best = None
1188
+ best_score = -1
1189
+ for _ in range(iters):
1190
+ a, b, c = P[rng.choice(len(P), 3, False)]
1191
+ nrm = np.cross(b - a, c - a)
1192
+ ln = np.linalg.norm(nrm)
1193
+ if ln < 1e-06:
1194
+ continue
1195
+ nrm /= ln
1196
+ d = -nrm @ a
1197
+ side = P @ nrm + d
1198
+ ninl = int((np.abs(side) < thr).sum())
1199
+ if ninl < 50:
1200
+ continue
1201
+ score = ninl * max(np.mean(side > thr), np.mean(side < -thr))
1202
+ if score > best_score:
1203
+ best_score = score
1204
+ best = (nrm, d)
1205
+ if best is None:
1206
+ ext = np.percentile(P, 98, 0) - np.percentile(P, 2, 0)
1207
+ ax = int(np.argmin(ext))
1208
+ g = np.zeros(3)
1209
+ g[ax] = 1.0
1210
+ return (g, ax)
1211
+ nrm, d = best
1212
+ if cam is not None and cam @ nrm + d < 0:
1213
+ nrm = -nrm
1214
+ return (nrm.astype(np.float32), int(np.argmax(np.abs(nrm))))
1215
+
1216
+
1217
+ def _canonical_floor_basis(up_vec):
1218
+ """Orthonormal floor basis (u, v horizontal; g = up), unchanged from the old file."""
1219
+ g = np.asarray(up_vec, np.float64)
1220
+ g = g / (np.linalg.norm(g) + 1e-12)
1221
+ up_ax = int(np.argmax(np.abs(g)))
1222
+ floor_axes = [a for a in range(3) if a != up_ax]
1223
+ e0 = np.zeros(3)
1224
+ e0[floor_axes[0]] = 1.0
1225
+ u = e0 - e0 @ g * g
1226
+ u = u / (np.linalg.norm(u) + 1e-12)
1227
+ v = np.cross(g, u)
1228
+ if v[floor_axes[1]] < 0:
1229
+ v = -v
1230
+ return (u, v, g)
1231
+
1232
+
1233
+ def _canonical_robust_centroid_extent(pts, up_axis=None):
1234
+ c = np.median(pts, axis=0)
1235
+ X = pts - c
1236
+ if len(X) > 5000:
1237
+ X = X[np.random.RandomState(0).choice(len(X), 5000, False)]
1238
+ if up_axis is not None:
1239
+ floor_axes = [i for i in range(3) if i != up_axis]
1240
+ F = X[:, floor_axes]
1241
+ try:
1242
+ _, _, Vt2 = np.linalg.svd(F - F.mean(0), full_matrices=False)
1243
+ proj_floor = F @ Vt2.T
1244
+ except np.linalg.LinAlgError:
1245
+ proj_floor = F
1246
+ proj = np.concatenate([proj_floor, X[:, up_axis : up_axis + 1]], 1)
1247
+ else:
1248
+ try:
1249
+ _, _, Vt = np.linalg.svd(X - X.mean(0), full_matrices=False)
1250
+ proj = X @ Vt.T
1251
+ except np.linalg.LinAlgError:
1252
+ proj = X
1253
+ ext = np.maximum(np.percentile(proj, 98, 0) - np.percentile(proj, 2, 0), 0.0)
1254
+ dims = np.sort(ext)[::-1]
1255
+ return (c.astype(np.float32), float(dims[0]), dims)
1256
+
1257
+
1258
+ def _canonical_aabb(pts):
1259
+ return (np.percentile(pts, 2, 0), np.percentile(pts, 98, 0))
1260
+
1261
+
1262
+ def _canonical_merge_by_box_overlap(insts, up_axis=None):
1263
+ """Parameter-free 3D re-identification with temporal exclusion, unchanged."""
1264
+ n = len(insts)
1265
+ if n <= 1:
1266
+ return insts
1267
+ lo = np.stack([_canonical_aabb(i["pts"])[0] for i in insts])
1268
+ hi = np.stack([_canonical_aabb(i["pts"])[1] for i in insts])
1269
+ cents = np.stack([i["centroid"] for i in insts])
1270
+ overlap = (hi[:, None] >= lo[None]).all(-1) & (hi[None] >= lo[:, None]).all(-1)
1271
+ ins = (cents[:, None] >= lo[None]).all(-1) & (cents[:, None] <= hi[None]).all(-1)
1272
+ match = overlap | ins | ins.T
1273
+ groups = [
1274
+ {"members": [i], "frames": set(insts[i].get("frames", ()))} for i in range(n)
1275
+ ]
1276
+ changed = True
1277
+ while changed:
1278
+ changed = False
1279
+ for a in range(len(groups)):
1280
+ for b in range(a + 1, len(groups)):
1281
+ if groups[a]["frames"] & groups[b]["frames"]:
1282
+ continue
1283
+ if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
1284
+ groups[a]["members"] += groups[b]["members"]
1285
+ groups[a]["frames"] |= groups[b]["frames"]
1286
+ groups.pop(b)
1287
+ changed = True
1288
+ break
1289
+ if changed:
1290
+ break
1291
+ out = []
1292
+ for g in groups:
1293
+ ii = g["members"]
1294
+ pts = np.concatenate([insts[k]["pts"] for k in ii], 0)
1295
+ best = max((insts[k]["best_pts"] for k in ii), key=len)
1296
+ c, size, dims = _canonical_robust_centroid_extent(best, up_axis)
1297
+ confs = [insts[k].get("conf") for k in ii]
1298
+ conf = (
1299
+ np.concatenate([x for x in confs if x is not None], 0)
1300
+ if any((x is not None for x in confs))
1301
+ else None
1302
+ )
1303
+ out.append(
1304
+ {
1305
+ "centroid": c,
1306
+ "size": size,
1307
+ "dims": dims,
1308
+ "pts": pts,
1309
+ "best_pts": best,
1310
+ "conf": conf,
1311
+ "frames": g["frames"],
1312
+ "nframes": len(g["frames"]),
1313
+ "n": sum((insts[k]["n"] for k in ii)),
1314
+ "first_time": min((insts[k]["first_time"] for k in ii)),
1315
+ }
1316
+ )
1317
+ return out
1318
+
1319
+
1320
+ def _canonical_sor(pts, k=16, std=2.0, cap=4000):
1321
+ from scipy.spatial import cKDTree
1322
+
1323
+ if len(pts) < k + 2:
1324
+ return pts
1325
+ P = (
1326
+ pts
1327
+ if len(pts) <= cap
1328
+ else pts[np.random.RandomState(0).choice(len(pts), cap, False)]
1329
+ )
1330
+ d, _ = cKDTree(P).query(P, k=k + 1, workers=KD_WORKERS)
1331
+ md = d[:, 1:].mean(1)
1332
+ return P[md <= md.mean() + std * md.std()]
1333
+
1334
+
1335
+ def _canonical_clean(inst, cap=4000):
1336
+ if inst.get("_cleanpts") is not None:
1337
+ return inst["_cleanpts"]
1338
+ pts, conf = (inst["pts"], inst.get("conf"))
1339
+ if len(pts) > cap:
1340
+ idx = np.random.RandomState(0).choice(len(pts), cap, False)
1341
+ pts = pts[idx]
1342
+ if conf is not None:
1343
+ conf = conf[idx]
1344
+ if conf is not None and len(conf) > 20:
1345
+ keep = conf >= np.median(conf)
1346
+ if keep.sum() >= 10:
1347
+ pts = pts[keep]
1348
+ inst["_cleanpts"] = _canonical_sor(pts, cap=cap)
1349
+ return inst["_cleanpts"]
1350
+
1351
+
1352
+ def _canonical_rep(insts):
1353
+ return max(insts, key=lambda i: (i.get("n", len(i["pts"])), i.get("nframes", 0)))
1354
+
1355
+
1356
+ def _canonical_answer_closest_distance(instsA, instsB, k=4000):
1357
+ from scipy.spatial import cKDTree
1358
+
1359
+ A, B = (
1360
+ _canonical_clean(_canonical_rep(instsA), k),
1361
+ _canonical_clean(_canonical_rep(instsB), k),
1362
+ )
1363
+ if not len(A) or not len(B):
1364
+ return float("inf")
1365
+ d, _ = (
1366
+ cKDTree(A).query(B, workers=KD_WORKERS)
1367
+ if len(A) <= len(B)
1368
+ else cKDTree(B).query(A, workers=KD_WORKERS)
1369
+ )
1370
+ return float(d.min())
1371
+
1372
+
1373
+ def _canonical_compute_floor_area(P, up_vec):
1374
+ P = np.asarray(P, np.float32)
1375
+ P = P[np.isfinite(P).all(1)]
1376
+ if not len(P):
1377
+ return 0.0
1378
+ g = np.asarray(up_vec, np.float64)
1379
+ g /= np.linalg.norm(g) + 1e-12
1380
+ a = np.array([1.0, 0.0, 0.0]) if abs(g[0]) < 0.9 else np.array([0.0, 1.0, 0.0])
1381
+ u = np.cross(g, a)
1382
+ u /= np.linalg.norm(u)
1383
+ v = np.cross(g, u)
1384
+ F = np.stack([P @ u, P @ v], 1)
1385
+ lo, hi = (np.percentile(F, 0.5, 0), np.percentile(F, 99.5, 0))
1386
+ F = F[
1387
+ (F[:, 0] >= lo[0])
1388
+ & (F[:, 0] <= hi[0])
1389
+ & (F[:, 1] >= lo[1])
1390
+ & (F[:, 1] <= hi[1])
1391
+ ]
1392
+ if len(F) < 10:
1393
+ return 0.0
1394
+ try:
1395
+ import alphashape
1396
+
1397
+ idx = np.random.RandomState(0).choice(len(F), min(10000, len(F)))
1398
+ return round(float(alphashape.alphashape(F[idx], alpha=2).area), 1)
1399
+ except Exception:
1400
+ from scipy import ndimage
1401
+
1402
+ res = 0.1
1403
+ ai = ((F[:, 0] - F[:, 0].min()) / res).astype(int)
1404
+ bi = ((F[:, 1] - F[:, 1].min()) / res).astype(int)
1405
+ grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
1406
+ grid[ai + 1, bi + 1] = 1
1407
+ grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1408
+ grid = ndimage.binary_fill_holes(grid)
1409
+ return round(float(grid.sum()) * res * res, 1)
1410
+
1411
+
1412
+ def _canonical_object_records(insts, count, u, v, g, floor_level):
1413
+ ranked = sorted(insts, key=lambda i: (i["n"], i.get("nframes", 0)), reverse=True)[
1414
+ : max(count, 1)
1415
+ ]
1416
+ return [
1417
+ {
1418
+ "position": {
1419
+ "x coordinate": f"{round(float(i['centroid'] @ u), 2)} meters",
1420
+ "y coordinate": f"{round(float(i['centroid'] @ v), 2)} meters",
1421
+ "height above floor": f"{round(float(i['centroid'] @ g - floor_level), 2)} meters",
1422
+ },
1423
+ "longest dimension": f"{round(float(i['size']), 2)} meters",
1424
+ }
1425
+ for i in ranked
1426
+ ]
1427
+
1428
+
1429
+ # ==========================================================================================
1430
+ # MODEL-AGNOSTIC ENTRY POINT
1431
+ # ==========================================================================================
1432
+
1433
+
1434
+ def build_spatial_code(scene):
1435
+ """Build the unchanged compact spatial-code schema.
1436
+
1437
+ Raw depth/pose/confidence/mask bundles use the exact reference path above. Canonical
1438
+ world-space bundles (for SegVGGT and models with different native outputs) use the same
1439
+ downstream formulas wherever equivalent inputs exist.
1440
+ """
1441
+ raw_inputs = scene.get("raw_inputs")
1442
+ if raw_inputs is not None:
1443
+ return build_spatial_code_raw(
1444
+ raw_inputs["depth"],
1445
+ raw_inputs["intr"],
1446
+ raw_inputs["c2w"],
1447
+ raw_inputs.get("conf"),
1448
+ raw_inputs["ftimes"],
1449
+ raw_inputs["per"],
1450
+ )
1451
+
1452
+ alias = {"coat hanger": "coat rack"}
1453
+ raw = {alias.get(k, k): v for k, v in scene["instances"].items()}
1454
+ stats = {alias.get(k, k): dict(v) for k, v in scene["stats"].items()}
1455
+ up_vec, up_ax = _canonical_room_gravity(scene["scene_pts"], scene.get("cameras"))
1456
+ u, v, g = _canonical_floor_basis(up_vec)
1457
+
1458
+ inst = {}
1459
+ for cls, items in raw.items():
1460
+ measured = []
1461
+ for item in items:
1462
+ centroid, size, dims = _canonical_robust_centroid_extent(
1463
+ item["best_pts"], up_ax
1464
+ )
1465
+ record = dict(item)
1466
+ record.update({"centroid": centroid, "size": size, "dims": dims})
1467
+ measured.append(record)
1468
+ inst[cls] = _canonical_merge_by_box_overlap(measured, up_ax)
1469
+ stats.setdefault(cls, {})
1470
+ stats[cls]["merged"] = len(inst[cls])
1471
+ stats[cls].setdefault("peak", len(inst[cls]))
1472
+
1473
+ all_points = np.concatenate(
1474
+ [i["pts"] for values in inst.values() for i in values], 0
1475
+ )
1476
+ floor_level = float(np.percentile(all_points @ g, 2))
1477
+ objects = {}
1478
+ for cls, items in inst.items():
1479
+ requested_count = max(0, int(stats[cls].get("peak", len(items))))
1480
+ emitted_count = min(requested_count, len(items))
1481
+ records = (
1482
+ _canonical_object_records(items, emitted_count, u, v, g, floor_level)
1483
+ if emitted_count
1484
+ else []
1485
+ )
1486
+ objects[cls] = {"count": len(records), "instances": records}
1487
+
1488
+ floor_area = _canonical_compute_floor_area(scene["scene_pts"], up_vec)
1489
+ code = {"objects": objects, "room": {"floor area": f"{floor_area} square meters"}}
1490
+ classes = list(inst)
1491
+ closest = {}
1492
+ for a in classes:
1493
+ distances = sorted(
1494
+ (round(_canonical_answer_closest_distance(inst[a], inst[b]), 2), b)
1495
+ for b in classes
1496
+ if b != a
1497
+ )
1498
+ closest[a] = {
1499
+ b: {"distance": f"{distance} meters", "closeness rank": rank + 1}
1500
+ for rank, (distance, b) in enumerate(distances)
1501
+ }
1502
+ code["closest classes distance meters from"] = closest
1503
+ first = {cls: min(i["first_time"] for i in values) for cls, values in inst.items()}
1504
+ code["appearance order"] = [
1505
+ cls for cls, _ in sorted(first.items(), key=lambda kv: kv[1])
1506
+ ]
1507
+ return code, inst, stats, up_ax, up_vec, floor_area
results/symbolic/.ipynb_checkpoints/_summary-checkpoint.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "scenes_run": [
3
+ "41069025"
4
+ ],
5
+ "scenes_skipped_no_questions": [],
6
+ "combined_aggregate": {
7
+ "overall": 5.333333333333333,
8
+ "object_counting_MRA:.5:.95:.05": 0.0,
9
+ "object_abs_distance_MRA:.5:.95:.05": 26.666666666666668,
10
+ "object_size_estimation_MRA:.5:.95:.05": 0.0,
11
+ "room_size_estimation_MRA:.5:.95:.05": 0.0,
12
+ "object_rel_direction_accuracy": 0.0,
13
+ "tabulated_keys": "overall, object_counting_MRA:.5:.95:.05, object_abs_distance_MRA:.5:.95:.05, object_size_estimation_MRA:.5:.95:.05, room_size_estimation_MRA:.5:.95:.05, object_rel_direction_accuracy",
14
+ "tabulated_results": "5.333, 0.000, 26.667, 0.000, 0.000, 0.000"
15
+ }
16
+ }
results/symbolic/41069025/0.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 0,
8
+ "question_type": "object_counting",
9
+ "question": "How many table(s) are in this room?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "4",
13
+ "answer_given": "1",
14
+ "answer_raw": "1",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/1.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1,
8
+ "question_type": "object_counting",
9
+ "question": "How many chair(s) are in this room?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "2",
13
+ "answer_given": "28",
14
+ "answer_raw": "28",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/1100.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1100,
8
+ "question_type": "object_rel_direction_medium",
9
+ "question": "If I am standing by the stove and facing the sofa, is the tv to my left, right, or back?\nAn object is to my back if I would have to turn at least 135 degrees in order to face it.",
10
+ "options": [
11
+ "A. back",
12
+ "B. right",
13
+ "C. left"
14
+ ],
15
+ "full_prompt": null,
16
+ "answer_expected": "C",
17
+ "answer_given": "B",
18
+ "answer_raw": "B",
19
+ "score": 0.0
20
+ }
results/symbolic/41069025/1101.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1101,
8
+ "question_type": "object_rel_direction_medium",
9
+ "question": "If I am standing by the stove and facing the tv, is the sofa to my left, right, or back?\nAn object is to my back if I would have to turn at least 135 degrees in order to face it.",
10
+ "options": [
11
+ "A. right",
12
+ "B. left",
13
+ "C. back"
14
+ ],
15
+ "full_prompt": null,
16
+ "answer_expected": "A",
17
+ "answer_given": "B",
18
+ "answer_raw": "B",
19
+ "score": 0.0
20
+ }
results/symbolic/41069025/1102.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1102,
8
+ "question_type": "object_rel_direction_medium",
9
+ "question": "If I am standing by the sofa and facing the stove, is the tv to my left, right, or back?\nAn object is to my back if I would have to turn at least 135 degrees in order to face it.",
10
+ "options": [
11
+ "A. back",
12
+ "B. right",
13
+ "C. left"
14
+ ],
15
+ "full_prompt": null,
16
+ "answer_expected": "B",
17
+ "answer_given": "C",
18
+ "answer_raw": "C",
19
+ "score": 0.0
20
+ }
results/symbolic/41069025/1236.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1236,
8
+ "question_type": "object_rel_direction_easy",
9
+ "question": "If I am standing by the stove and facing the sofa, is the tv to the left or the right of the sofa?",
10
+ "options": [
11
+ "A. left",
12
+ "B. right"
13
+ ],
14
+ "full_prompt": null,
15
+ "answer_expected": "A",
16
+ "answer_given": "B",
17
+ "answer_raw": "B",
18
+ "score": 0.0
19
+ }
results/symbolic/41069025/1237.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1237,
8
+ "question_type": "object_rel_direction_easy",
9
+ "question": "If I am standing by the stove and facing the tv, is the sofa to the left or the right of the tv?",
10
+ "options": [
11
+ "A. left",
12
+ "B. right"
13
+ ],
14
+ "full_prompt": null,
15
+ "answer_expected": "B",
16
+ "answer_given": "A",
17
+ "answer_raw": "A",
18
+ "score": 0.0
19
+ }
results/symbolic/41069025/1238.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 1238,
8
+ "question_type": "object_rel_direction_easy",
9
+ "question": "If I am standing by the sofa and facing the stove, is the tv to the left or the right of the stove?",
10
+ "options": [
11
+ "A. left",
12
+ "B. right"
13
+ ],
14
+ "full_prompt": null,
15
+ "answer_expected": "B",
16
+ "answer_given": "A",
17
+ "answer_raw": "A",
18
+ "score": 0.0
19
+ }
results/symbolic/41069025/167.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 167,
8
+ "question_type": "object_size_estimation",
9
+ "question": "What is the length of the longest dimension (length, width, or height) of the stove, measured in centimeters?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "62",
13
+ "answer_given": "24.0",
14
+ "answer_raw": "24.0",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/168.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 168,
8
+ "question_type": "object_size_estimation",
9
+ "question": "What is the length of the longest dimension (length, width, or height) of the sofa, measured in centimeters?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "173",
13
+ "answer_given": "11.0",
14
+ "answer_raw": "11.0",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/169.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 169,
8
+ "question_type": "object_size_estimation",
9
+ "question": "What is the length of the longest dimension (length, width, or height) of the tv, measured in centimeters?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "91",
13
+ "answer_given": "23.0",
14
+ "answer_raw": "23.0",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/530.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 530,
8
+ "question_type": "room_size_estimation",
9
+ "question": "What is the size of this room (in square meters)? \nIf multiple rooms are shown, estimate the size of the combined space.",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "26.4",
13
+ "answer_given": "3.5",
14
+ "answer_raw": "3.5",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/680.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 680,
8
+ "question_type": "object_abs_distance",
9
+ "question": "Measuring from the closest point of each object, what is the distance between the sofa and the stove (in meters)?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "2.9",
13
+ "answer_given": "0.93",
14
+ "answer_raw": "0.93",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/681.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 681,
8
+ "question_type": "object_abs_distance",
9
+ "question": "Measuring from the closest point of each object, what is the distance between the tv and the stove (in meters)?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "2.9",
13
+ "answer_given": "1.01",
14
+ "answer_raw": "1.01",
15
+ "score": 0.0
16
+ }
results/symbolic/41069025/682.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model": "symbolic",
3
+ "condition": "symbolic",
4
+ "number_of_frames": null,
5
+ "scene": "41069025",
6
+ "dataset": "arkitscenes",
7
+ "question_id": 682,
8
+ "question_type": "object_abs_distance",
9
+ "question": "Measuring from the closest point of each object, what is the distance between the tv and the sofa (in meters)?",
10
+ "options": null,
11
+ "full_prompt": null,
12
+ "answer_expected": "2.1",
13
+ "answer_given": "1.88",
14
+ "answer_raw": "1.88",
15
+ "score": 0.8
16
+ }