AntonioJun commited on
Commit
fe34cb1
·
verified ·
1 Parent(s): fc24aee

Remove old encoder before replacement

Browse files
encoder/.ipynb_checkpoints/geometric-checkpoint.py DELETED
@@ -1,2333 +0,0 @@
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 feed build_compact_spatial_code() (see its own docstring for how it handles
9
- that duality). The explicit schema is no longer built independently: it is a strict derivation
10
- of the compact schema (build_explicit_spatial_code() calls build_compact_spatial_code() first,
11
- then reads every explicit value directly off compact's own oriented boxes and floor polygons --
12
- positions/dimensions/counts/appearance-order are direct subsets, and the distance table is
13
- computed purely from compact's 3D oriented boxes). This guarantees the two schemas can never
14
- silently disagree about the same scene's geometry.
15
-
16
- Formerly this file called into perceptual.py (as a dynamically-loaded `pl` module) for its own
17
- geometry helpers -- build_instances, room_gravity, answer_closest_distance, and everything else
18
- in this file below _room_outline(). Those functions are now merged in directly, verbatim, since
19
- they were never DA3/SAM3 calls -- they're geometric computations over already-extracted
20
- depth/masks, which is exactly this file's job. perceptual.py's OTHER half (the actual
21
- model-calling functions) moved to run.py instead; perceptual.py itself no longer exists.
22
-
23
- The spatial code is the sole spatial representation the downstream VLM sees; no answer engine
24
- is computed here (the harness runs the model).
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import os
30
- import json
31
- import numpy as np
32
- import cv2
33
-
34
- # ==========================================================================================
35
- # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
36
- # affect only the math below (build_instances/backproject_frame/etc.), never model inference.
37
- # ==========================================================================================
38
-
39
- SCHEMA = [
40
- "x",
41
- "y",
42
- "z",
43
- "e1",
44
- "e2",
45
- "e3",
46
- "px",
47
- "pz",
48
- "size_median",
49
- "size_IQR",
50
- "time",
51
- "n",
52
- ] # legacy row schema, see to_labeled()
53
- KD_WORKERS = max(1, int(os.environ.get("VSI_KD_WORKERS", "4")))
54
- # Batch workers set VSI_KD_WORKERS from their per-process CPU budget. Keeping a
55
- # bounded default avoids pathological all-core thread spawning for small queries.
56
- MIN_INSTANCE_PTS = (
57
- 1 # bare geometry floor only: need >=1 valid depth pixel to place a 3D point.
58
- )
59
- # NO quality filtering / dedup -- count = exactly SAM3's tracked masklets (honest)
60
- FLOOR_BAND = (
61
- 0.15 # m above the floor to count as floor-level (LEGACY -- currently unreferenced;
62
- )
63
- # compute_floor_area now uses the RANSAC gravity plane directly instead)
64
- # ---- geometry-cleanup levers (improve abs_distance etc.; env-tunable) ----
65
- # DEPTH_COHERENCE (Tukey-fence bleed removal): SAFE + helpful everywhere -> default ON.
66
- # ablation: ARKit abs_distance 0.757->0.729 (no harm), ScanNet++ d755 0.443->0.486 (helps).
67
- # CONF_PCT (per-frame confidence percentile): noisy-dataset ONLY -> default OFF.
68
- # helps ScanNet++ distance more (~0.56) but DESTROYS clean ARKit (0.757->0.429). Opt in via VSI_CONF_PCT=55.
69
- CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0"))
70
- DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
71
- # cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
72
- # -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
73
- DEPTH_EDGE_REFINE = os.environ.get("VSI_DEPTH_EDGE_REFINE", "0") == "1"
74
- # MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
75
- # depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
76
- MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
77
-
78
-
79
- # ==========================================================================================
80
- # ROOM/OBJECT GEOMETRY -- gravity, floor basis, per-instance spatial-code records. Merged in
81
- # from perceptual.py, verbatim.
82
- # ==========================================================================================
83
-
84
-
85
- def to_labeled(objects, floor_area):
86
- """LEGACY per-class summary (kept for --format array-compat). Superseded by to_spatial_code."""
87
- out = {"objects": {}}
88
- for cls, row in objects.items():
89
- d = dict(zip(SCHEMA, row))
90
- out["objects"][cls] = {
91
- "count": int(d["n"]),
92
- "centroid_meters": {"x": d["x"], "y": d["y"], "z": d["z"]},
93
- "longest_dimension_meters": {
94
- "median": d["size_median"],
95
- "iqr": d["size_IQR"],
96
- },
97
- "centroid_spread": {
98
- "eigenvalues": [d["e1"], d["e2"], d["e3"]],
99
- "principal_axis_xz": [d["px"], d["pz"]],
100
- },
101
- "first_seen_seconds": d["time"],
102
- }
103
- out["room"] = {"floor_area_square_meters": floor_area}
104
- return out
105
-
106
-
107
- def room_up_axis(instances, c2w):
108
- """up axis = smallest-extent axis of all object points; sign from gravity (floor->camera).
109
- Floor = densest horizontal slab; cameras are always above it, which fixes the sign.
110
- Returns (axis_index, signed_unit_vector)."""
111
- points = np.concatenate([i["pts"] for v in instances.values() for i in v], 0)
112
- ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
113
- up = int(np.argmin(ext))
114
- h, edges = np.histogram(points[:, up], bins=80)
115
- floor = 0.5 * (edges[h.argmax()] + edges[h.argmax() + 1]) # densest slab = floor
116
- cam_up = c2w[:, :3, 3][:, up].mean()
117
- e = np.zeros(3, np.float32)
118
- e[up] = 1.0 if cam_up > floor else -1.0
119
- return up, e
120
-
121
-
122
- def room_gravity(
123
- depth, intr, c2w, conf, conf_pct=40, stride=12, fstride=15, iters=300, thr=0.05
124
- ):
125
- """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
126
- the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
127
- Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
128
- """
129
- points = []
130
- for f in range(0, len(depth), fstride):
131
- height, width = depth[f].shape
132
- ys, xs = np.mgrid[0:height:stride, 0:width:stride]
133
- ys = ys.ravel()
134
- xs = xs.ravel()
135
- z = depth[f][ys, xs]
136
- ok = (z > 0) & np.isfinite(z)
137
- if conf is not None and conf_pct > 0:
138
- ok &= conf[f][ys, xs] >= np.percentile(conf[f], conf_pct)
139
- ys, xs, z = ys[ok], xs[ok], z[ok]
140
- if not len(z):
141
- continue
142
- intrinsics = intr[f]
143
- camera_points = np.stack(
144
- [
145
- (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
146
- (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
147
- z,
148
- ],
149
- 1,
150
- )
151
- points.append((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3])
152
- points = np.concatenate(points).astype(np.float64) if points else np.zeros((0, 3))
153
- cam = c2w[:, :3, 3].mean(0)
154
- if len(points) < 100: # fallback to axis-extent
155
- ext = (
156
- np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
157
- if len(points)
158
- else np.ones(3)
159
- )
160
- ax = int(np.argmin(ext))
161
- g = np.zeros(3)
162
- g[ax] = 1.0
163
- return g, ax
164
- rng = np.random.RandomState(0)
165
- best = None
166
- best_score = -1
167
- for _ in range(iters):
168
- a, b, c = points[rng.choice(len(points), 3, False)]
169
- nrm = np.cross(b - a, c - a)
170
- ln = np.linalg.norm(nrm)
171
- if ln < 1e-6:
172
- continue
173
- nrm /= ln
174
- d = -nrm @ a
175
- side = points @ nrm + d
176
- ninl = int((np.abs(side) < thr).sum())
177
- if ninl < 50:
178
- continue
179
- score = ninl * max(
180
- np.mean(side > thr), np.mean(side < -thr)
181
- ) # big + one-sided = floor
182
- if score > best_score:
183
- best_score = score
184
- best = (nrm, d)
185
- if best is None:
186
- ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
187
- ax = int(np.argmin(ext))
188
- g = np.zeros(3)
189
- g[ax] = 1.0
190
- return g, ax
191
- nrm, d = best
192
- if (cam @ nrm + d) < 0:
193
- nrm = -nrm # orient toward cameras (up)
194
- return nrm.astype(np.float32), int(np.argmax(np.abs(nrm)))
195
-
196
-
197
- def pos3(rec):
198
- """Read either legacy numeric or current unit-string position formatting."""
199
- p = rec.get("position") or {}
200
-
201
- def meters(current, legacy):
202
- value = p.get(current, p.get(legacy, 0.0))
203
- if isinstance(value, str):
204
- if value.endswith(" meters"):
205
- value = value[: -len(" meters")]
206
- value = value.strip()
207
- return float(value)
208
-
209
- return [
210
- meters("x coordinate", "floor_x_meters"),
211
- meters("y coordinate", "floor_y_meters"),
212
- meters("height above floor", "height_above_floor_meters"),
213
- ]
214
-
215
-
216
- def _floor_basis(up_vec):
217
- """Orthonormal floor basis (u, v horizontal; g = up) from the gravity vector. u is the OLD
218
- floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
219
- differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
220
- rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
221
- all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
222
- """
223
- g = np.asarray(up_vec, np.float64)
224
- g = g / (np.linalg.norm(g) + 1e-12)
225
- up_ax = int(np.argmax(np.abs(g)))
226
- floor_axes = [
227
- a for a in range(3) if a != up_ax
228
- ] # the two world axes the old frame used
229
- e0 = np.zeros(3)
230
- e0[floor_axes[0]] = 1.0 # old floor_x world axis
231
- u = e0 - (e0 @ g) * g
232
- u = u / (np.linalg.norm(u) + 1e-12) # project it into the gravity plane
233
- v = np.cross(g, u)
234
- if v[floor_axes[1]] < 0:
235
- v = -v # keep floor_y sign aligned with the old axis
236
- return u, v, g
237
-
238
-
239
- def _floor_level(points, gravity, v2=None):
240
- """Reference floor estimator shared by every model representation.
241
-
242
- The supplied geometry uses the densest gravity-height slab for its reproducible v1
243
- behavior and the robust second percentile for v2. Keep that switch here, after model
244
- adapters have produced world points, so it cannot become model-specific.
245
- """
246
- heights = np.asarray(points, np.float64) @ np.asarray(gravity, np.float64)
247
- heights = heights[np.isfinite(heights)]
248
- if not len(heights):
249
- return 0.0
250
- if v2 is None:
251
- v2 = os.environ.get("VSI_CODE_V2") == "1"
252
- if v2:
253
- return float(np.percentile(heights, 2))
254
- counts, edges = np.histogram(heights, bins=80)
255
- index = int(counts.argmax())
256
- return float(0.5 * (edges[index] + edges[index + 1]))
257
-
258
-
259
- # ==========================================================================================
260
- # DETERMINISTIC ANSWER LAYER (parameter-free; validated on VSI GT). Reads the in-memory
261
- # instances (pos for direction/route, point clouds for distance). Merged in from
262
- # perceptual.py, verbatim.
263
- # ==========================================================================================
264
-
265
-
266
- def _find_cls(name, classes):
267
- """Mirrors symbolic/solver.py's _find_class exactly (see its docstring): word-TOKEN
268
- subset, not raw character substring -- "washer" must not match "dishwasher" just
269
- because the characters appear inside it (2026-07-26 fix, found via the citation-
270
- fidelity audit)."""
271
- name = name.strip().lower()
272
- for c in classes:
273
- if c == name or c.replace(" ", "") == name.replace(" ", ""):
274
- return c
275
- name_tokens = set(name.split())
276
- for c in classes:
277
- class_tokens = set(c.split())
278
- if (
279
- name_tokens
280
- and class_tokens
281
- and (name_tokens <= class_tokens or class_tokens <= name_tokens)
282
- ):
283
- return c
284
- return None
285
-
286
-
287
- def _rep(insts):
288
- """representative instance = most observed points (best-segmented, validated 8/8 on direction)."""
289
- return max(insts, key=lambda i: i["n"])
290
-
291
-
292
- def answer_rel_direction(point_a, point_b, point_c, up_vec, up_ax, mode="hard"):
293
- """Standing at A facing B, where is C? front/back=dot(C-A,fwd); left/right=dot(C-A, up x fwd).
294
- Right-handed world (OpenCV cam frame + det+1 c2w) makes up x fwd = left a fixed identity.
295
- Projection uses the gravity VECTOR (v-(v.g)g), so a tilted floor (ScanNet++) is handled; for an
296
- axis-aligned up this reduces to zeroing that axis (ARKit unchanged)."""
297
- g = np.asarray(up_vec, np.float64)
298
- g = g / (np.linalg.norm(g) + 1e-12)
299
-
300
- def fl(v):
301
- w = v.astype(np.float64)
302
- return w - (w @ g) * g
303
-
304
- fwd = fl(point_b - point_a)
305
- n = np.linalg.norm(fwd)
306
- if n < 1e-6:
307
- return None
308
- fwd /= n
309
- left = np.cross(g, fwd)
310
- left /= np.linalg.norm(left) + 1e-9
311
- d = fl(point_c - point_a)
312
- f = float(d @ fwd)
313
- lateral = float(d @ left)
314
- if mode == "medium":
315
- if abs(np.degrees(np.arctan2(lateral, f))) >= 135:
316
- return "back"
317
- return "left" if lateral > 0 else "right"
318
- return f"{'front' if f > 0 else 'back'}-{'left' if lateral > 0 else 'right'}"
319
-
320
-
321
- def _classify_turn(h_in, h_out, up_vec, up_ax):
322
- """rotation h_in->h_out in floor plane -> turn left/right/back (135deg = VSI's own 'back' cutoff)."""
323
- g = np.asarray(up_vec, np.float64)
324
- g = g / (np.linalg.norm(g) + 1e-12)
325
-
326
- def fl(v):
327
- w = v.astype(np.float64)
328
- return w - (w @ g) * g
329
-
330
- a, b = fl(h_in), fl(h_out)
331
- na, nb = np.linalg.norm(a), np.linalg.norm(b)
332
- if na < 1e-6 or nb < 1e-6:
333
- return None
334
- a /= na
335
- b /= nb
336
- ang = np.degrees(np.arctan2(float(up_vec @ np.cross(a, b)), float(a @ b)))
337
- if abs(ang) >= 135:
338
- return "turn back"
339
- return "turn left" if ang > 0 else "turn right"
340
-
341
-
342
- def answer_route(ql, cents, up_vec, up_ax):
343
- """Chain the turn primitive over the waypoint sequence -> ordered ['turn left/right/back', ...]."""
344
- import re as _re
345
-
346
- m = _re.search(r"beginning at the (.+?) (?:and )?facing the (.+?)\.", ql)
347
- if not m:
348
- return None
349
-
350
- def position(name):
351
- class_name = _find_cls(name, cents)
352
- return cents[class_name] if class_name else None
353
-
354
- steps_txt = ql.split(":", 1)[1] if ":" in ql else ql
355
- steps = _re.findall(
356
- r"\d+\.\s*(\[please fill in\]|Go forward until the [^0-9\[]+?)(?=\s*\d+\.|$)",
357
- steps_txt,
358
- )
359
- cur_pos = position(m.group(1).strip())
360
- if cur_pos is None:
361
- return None
362
- fac = position(m.group(2).strip())
363
- cur_head = (fac - cur_pos) if fac is not None else None
364
- turns = []
365
- i = 0
366
- while i < len(steps):
367
- s = steps[i].strip()
368
- if s.startswith("Go forward"):
369
- tp = position(_re.sub(r"^Go forward until the ", "", s).strip().rstrip("."))
370
- if tp is not None:
371
- cur_head = tp - cur_pos
372
- cur_pos = tp
373
- else:
374
- nxt = next(
375
- (
376
- _re.sub(r"^Go forward until the ", "", steps[j].strip())
377
- .strip()
378
- .rstrip(".")
379
- for j in range(i + 1, len(steps))
380
- if steps[j].strip().startswith("Go forward")
381
- ),
382
- None,
383
- )
384
- tp = position(nxt) if nxt else None
385
- if tp is None or cur_head is None:
386
- turns.append(None)
387
- else:
388
- turns.append(_classify_turn(cur_head, tp - cur_pos, up_vec, up_ax))
389
- cur_head = tp - cur_pos
390
- i += 1
391
- return turns
392
-
393
-
394
- # ==========================================================================================
395
- # POINT-CLOUD CLEANING + DISTANCE ANSWERS -- outlier removal, closest-distance queries. Merged
396
- # in from perceptual.py, verbatim.
397
- # ==========================================================================================
398
-
399
-
400
- def _sor(pts, k=16, std=2.0, cap=4000):
401
- """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
402
- mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
403
- k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
404
- """
405
- from scipy.spatial import cKDTree
406
-
407
- if len(pts) < k + 2:
408
- return pts
409
- rs = np.random.RandomState(0)
410
- points = pts if len(pts) <= cap else pts[rs.choice(len(pts), cap, False)]
411
- d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
412
- md = d[:, 1:].mean(1)
413
- return points[md <= md.mean() + std * md.std()]
414
-
415
-
416
- def _main_cluster(pts):
417
- """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
418
- object forms a disconnected component (a gap separates two objects); the true object is the largest one.
419
- Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
420
- """
421
- from scipy.spatial import cKDTree
422
-
423
- if len(pts) < 30:
424
- return pts
425
- tree = cKDTree(pts)
426
- nn, _ = tree.query(pts, k=2)
427
- eps = 3.0 * float(np.median(nn[:, 1])) # 3x median NN gap (data-derived)
428
- pairs = tree.query_pairs(eps, output_type="ndarray")
429
- if len(pairs) == 0:
430
- return pts
431
- parent = np.arange(len(pts))
432
-
433
- def find(x):
434
- r = x
435
- while parent[r] != r:
436
- r = parent[r]
437
- while parent[x] != r:
438
- parent[x], x = r, parent[x]
439
- return r
440
-
441
- for a, b in pairs:
442
- ra, rb = find(int(a)), find(int(b))
443
- if ra != rb:
444
- parent[ra] = rb
445
- roots = np.array([find(i) for i in range(len(pts))])
446
- v, cnt = np.unique(roots, return_counts=True)
447
- return pts[roots == v[cnt.argmax()]]
448
-
449
-
450
- def _clean(inst, cap=4000):
451
- """Outlier removal self-calibrated from the pipeline's OWN per-object signals -- no universal constant,
452
- no benchmark knob. Cached on the instance so the O(classes^2) distance table cleans each object once.
453
- (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
454
- object's OWN median confidence (data-derived cut);
455
- (2) statistical density outlier removal on the survivors;
456
- (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
457
- """
458
- if inst.get("_cleanpts") is not None:
459
- return inst["_cleanpts"]
460
- pts = inst["pts"]
461
- conf = inst.get("conf")
462
- rs = np.random.RandomState(0)
463
- if len(pts) > cap:
464
- idx = rs.choice(len(pts), cap, False)
465
- pts = pts[idx]
466
- conf = conf[idx] if conf is not None else None
467
- if conf is not None and len(conf) > 20: # self-calibrating: object's OWN median
468
- keep = conf >= np.median(conf)
469
- if keep.sum() >= 10:
470
- pts = pts[keep]
471
- pts = _sor(pts, cap=cap) # density outlier removal on the survivors
472
- # NOTE: spatial de-bleeding (_main_cluster) was tried and REVERTED -- "largest cluster = the object" is
473
- # not guaranteed; when an object's near edge splits off it drops the true closest part (overshoot). You
474
- # cannot post-hoc recover the true object from a bleeding mask in 3D -- that needs better SOURCE masks.
475
- inst["_cleanpts"] = pts
476
- return pts
477
-
478
-
479
- def answer_closest_distance(instances_a, instances_b, k=4000):
480
- """Closest distance between the two objects' point clouds ('closest point of each object'). Points are
481
- cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
482
- KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
483
- boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
484
- """
485
- points_a = _clean(_rep(instances_a), cap=k)
486
- points_b = _clean(_rep(instances_b), cap=k)
487
- if len(points_a) == 0 or len(points_b) == 0:
488
- return float("inf")
489
- from scipy.spatial import cKDTree
490
-
491
- if len(points_a) <= len(points_b):
492
- d, _ = cKDTree(points_a).query(points_b, k=1, workers=KD_WORKERS)
493
- else:
494
- d, _ = cKDTree(points_b).query(points_a, k=1, workers=KD_WORKERS)
495
- return float(d.min())
496
-
497
-
498
- # ==========================================================================================
499
- # MASK/DEPTH CLEANUP + BACK-PROJECTION -- per-frame refinement before points enter an
500
- # instance's point cloud. Merged in from perceptual.py, verbatim.
501
- # ==========================================================================================
502
-
503
-
504
- def depth_edges(depth_f, valid_f):
505
- """Per-frame depth-DISCONTINUITY map: gradient magnitude above median + 3*MAD over the valid pixels.
506
- The threshold is data-derived (robust, universal statistical cut -- NOT benchmark-tuned). These edges are
507
- where mask-bleed crosses onto an adjacent object at a different depth."""
508
- if valid_f.sum() < 100:
509
- return np.zeros_like(depth_f, bool)
510
- d = np.where(valid_f, depth_f, np.median(depth_f[valid_f]))
511
- gy, gx = np.gradient(d)
512
- grad = np.hypot(gx, gy)
513
- g = grad[valid_f]
514
- med = np.median(g)
515
- mad = np.median(np.abs(g - med)) + 1e-9
516
- return (grad > med + 3.0 * 1.4826 * mad) & valid_f
517
-
518
-
519
- try:
520
- _GUIDED = (
521
- cv2.ximgproc.guidedFilter
522
- ) # opencv-contrib; appearance-guided boundary snap
523
- except AttributeError:
524
- _GUIDED = None
525
-
526
-
527
- def refine_mask(mask, rgb):
528
- """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
529
- bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
530
- cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
531
- variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
532
- """
533
- if mask.shape[:2] != rgb.shape[:2]:
534
- mask = cv2.resize(
535
- mask.astype(np.uint8),
536
- (rgb.shape[1], rgb.shape[0]),
537
- interpolation=cv2.INTER_NEAREST,
538
- ).astype(bool)
539
- a = int(mask.sum())
540
- if a < 60: # too small to refine meaningfully -> 1px erode as before
541
- me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
542
- return me if me.any() else mask
543
- if _GUIDED is not None:
544
- r = max(
545
- 4, int(round(0.02 * float(np.hypot(*mask.shape[:2]))))
546
- ) # radius ~2% of frame diagonal
547
- eps = (
548
- float(np.var(rgb.astype(np.float32) / 255.0)) * 0.01 + 1e-6
549
- ) # smoothness ~ image color variance
550
- soft = _GUIDED(rgb, mask.astype(np.float32), r, eps)
551
- out = soft > 0.5
552
- return out if out.sum() >= 0.4 * a else mask # majority guard: don't over-carve
553
- # fallback (base opencv, no ximgproc): grabCut seeded FG=mask, PR_FG=dilated ring, BG=far exterior
554
- try:
555
- gc = np.full(mask.shape[:2], cv2.GC_PR_BGD, np.uint8)
556
- dil = cv2.dilate(mask.astype(np.uint8), np.ones((15, 15), np.uint8), 1).astype(
557
- bool
558
- )
559
- er = cv2.erode(mask.astype(np.uint8), np.ones((5, 5), np.uint8), 1).astype(bool)
560
- gc[dil] = cv2.GC_PR_FGD
561
- gc[er] = cv2.GC_FGD
562
- bgm = np.zeros((1, 65), np.float64)
563
- fgm = np.zeros((1, 65), np.float64)
564
- cv2.grabCut(rgb, gc, None, bgm, fgm, 3, cv2.GC_INIT_WITH_MASK)
565
- out = (gc == cv2.GC_FGD) | (gc == cv2.GC_PR_FGD)
566
- return out if 0.4 * a <= out.sum() <= 1.5 * a else mask
567
- except Exception:
568
- me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
569
- return me if me.any() else mask
570
-
571
-
572
- def backproject_frame(
573
- depth_f,
574
- intrinsics,
575
- c2w_f,
576
- mask_f,
577
- conf_f=None,
578
- conf_thr=0.0,
579
- valid_f=None,
580
- return_conf=False,
581
- edges_f=None,
582
- ):
583
- """Return (M,3) world points for the masked pixels of one frame (c2w_f = cam->world 4x4).
584
- valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
585
- return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
586
- edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
587
- (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
588
- """
589
- height, width = depth_f.shape
590
- empty = (
591
- (np.empty((0, 3), np.float32), np.empty((0,), np.float32))
592
- if return_conf
593
- else np.empty((0, 3), np.float32)
594
- )
595
- if mask_f.shape != (height, width):
596
- mask_f = cv2.resize(
597
- mask_f.astype(np.uint8), (width, height), interpolation=cv2.INTER_NEAREST
598
- ).astype(bool)
599
- if valid_f is None:
600
- valid_f = np.isfinite(depth_f) & (depth_f > 0)
601
- m = mask_f & valid_f
602
- if conf_f is not None and conf_thr > 0:
603
- m &= conf_f >= conf_thr
604
- if (
605
- edges_f is not None and m.sum() >= 30
606
- ): # keep the largest depth-coherent piece of the mask
607
- from scipy import ndimage
608
-
609
- lab, nlab = ndimage.label(m & ~edges_f)
610
- if nlab >= 1:
611
- sizes = np.bincount(lab.ravel())
612
- sizes[0] = 0
613
- big = int(sizes.argmax())
614
- if (
615
- sizes[big] >= 0.5 * m.sum()
616
- ): # object is the MAJORITY piece (bleed is a minority)
617
- m = lab == big
618
- if not m.any():
619
- return empty
620
- ys, xs = np.nonzero(m)
621
- z = depth_f[ys, xs]
622
- if DEPTH_COHERENCE and len(z) >= 8:
623
- # an object is a coherent depth surface; floor/background BLEED pixels are depth outliers.
624
- # Drop them via the standard Tukey fence (1.5*IQR) on the masked region's depths -- parameter-free.
625
- q1, q3 = np.percentile(z, [25, 75])
626
- iqr = q3 - q1
627
- keep = (z >= q1 - 1.5 * iqr) & (z <= q3 + 1.5 * iqr)
628
- if keep.sum() >= 1:
629
- ys, xs, z = ys[keep], xs[keep], z[keep]
630
- fx, fy, cx, cy = (
631
- intrinsics[0, 0],
632
- intrinsics[1, 1],
633
- intrinsics[0, 2],
634
- intrinsics[1, 2],
635
- )
636
- camera_points = np.stack(
637
- [(xs - cx) * z / fx, (ys - cy) * z / fy, z], axis=1
638
- ) # camera coords
639
- world_points = (c2w_f[:3, :3] @ camera_points.T).T + c2w_f[:3, 3] # -> world
640
- if return_conf:
641
- cw = (
642
- conf_f[ys, xs].astype(np.float32)
643
- if conf_f is not None
644
- else np.ones(len(ys), np.float32)
645
- )
646
- return world_points.astype(np.float32), cw
647
- return world_points.astype(np.float32)
648
-
649
-
650
- # ==========================================================================================
651
- # INSTANCE BUILDING -- oriented extent, 3D box-overlap re-identification, and the main
652
- # build_instances() driver that turns per-frame masks into per-class 3D instances. Merged in
653
- # from perceptual.py, verbatim.
654
- # ==========================================================================================
655
-
656
-
657
- def robust_centroid_extent(pts, up_axis=None):
658
- """median centroid + ORIENTED robust extent.
659
- If up_axis is given: YAW-ONLY oriented extent -- rotation is found by 2D PCA on the
660
- floor-projected points only, with the up axis left untouched. This matches VSI-Bench's
661
- own annotation convention for indoor scans (ScanNet/ARKitScenes OrientedBoundingBox
662
- objects follow a Manhattan-world assumption: rotated only around the vertical axis,
663
- never tilted). Unconstrained 3D PCA (the previous behavior) can chase noise on the
664
- vertical axis for flat/elongated objects and drift away from the true yaw.
665
- If up_axis is None (unknown at the call site): falls back to unconstrained 3D PCA.
666
- Either way: parameter-free, rotation-invariant in-plane, p2..p98 robust extent."""
667
- c = np.median(pts, axis=0)
668
- centered = pts - c
669
- if len(centered) > 5000: # PCA on a sample (deterministic)
670
- centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
671
- if up_axis is not None:
672
- floor_axes = [i for i in range(3) if i != up_axis]
673
- floor_points = centered[:, floor_axes]
674
- try:
675
- _, _, floor_rotation = np.linalg.svd(
676
- floor_points - floor_points.mean(0), full_matrices=False
677
- )
678
- proj_floor = (
679
- floor_points @ floor_rotation.T
680
- ) # (N,2) along the object's own floor-plane axes
681
- except np.linalg.LinAlgError:
682
- proj_floor = floor_points
683
- up_col = centered[:, up_axis : up_axis + 1] # up axis untouched (yaw-only)
684
- proj = np.concatenate([proj_floor, up_col], axis=1)
685
- else:
686
- try:
687
- _, _, rotation = np.linalg.svd(
688
- centered - centered.mean(0), full_matrices=False
689
- )
690
- proj = centered @ rotation.T # coordinates along principal axes
691
- except np.linalg.LinAlgError:
692
- proj = centered
693
- lo = np.percentile(proj, 2, axis=0)
694
- hi = np.percentile(proj, 98, axis=0)
695
- ext = np.maximum(hi - lo, 0.0)
696
- dims = np.sort(ext)[::-1] # the object's 3 oriented side lengths, longest first
697
- return c.astype(np.float32), float(dims[0]), dims
698
-
699
-
700
- def _aabb(pts):
701
- """robust (p2..p98) axis-aligned 3D box of an instance's world points."""
702
- return np.percentile(pts, 2, axis=0), np.percentile(pts, 98, axis=0)
703
-
704
-
705
- def merge_by_box_overlap(insts, up_axis=None):
706
- """Parameter-free 3D re-identification, with a temporal-exclusion gate.
707
-
708
- SAM3 (a 2D tracker) emits a NEW masklet each time the camera revisits an object, so one
709
- physical object -> several masklets at the same 3D location. We fuse two same-class masklets
710
- iff BOTH:
711
- (a) their measured 3D boxes overlap (or one centroid is inside the other) -- same volume, and
712
- (b) they NEVER appear in the same frame -- temporal exclusion.
713
- (b) is the key parameter-free invariant: two masklets co-visible in one frame were tracked by
714
- SAM3 as distinct objects in that frame, so they ARE distinct (e.g. two chairs around a table);
715
- we must never merge them, even if depth noise makes their boxes overlap. A revisit-duplicate,
716
- by contrast, lives in DISJOINT frames. Both tests are exact/measured -- NO tuned threshold.
717
- """
718
- n = len(insts)
719
- if n <= 1:
720
- return insts
721
- # Precompute the FULL pairwise box-match as one vectorized boolean matrix. With the per-frame
722
- # batched detector a class can have 100+ raw instances; the old O(n^3) loop called np.all-based
723
- # box_match millions of times. Here every pairwise test is one broadcast -> O(1) lookups below.
724
- lo = np.stack([_aabb(i["pts"])[0] for i in insts]).astype(np.float32) # (n,3)
725
- hi = np.stack([_aabb(i["pts"])[1] for i in insts]).astype(np.float32) # (n,3)
726
- cents = np.stack([i["centroid"] for i in insts]).astype(np.float32) # (n,3)
727
- overlap = (hi[:, None, :] >= lo[None, :, :]).all(-1) & (
728
- hi[None, :, :] >= lo[:, None, :]
729
- ).all(-1)
730
- ins = (cents[:, None, :] >= lo[None, :, :]).all(-1) & (
731
- cents[:, None, :] <= hi[None, :, :]
732
- ).all(-1)
733
- match = (
734
- overlap | ins | ins.T
735
- ) # box_match[i,j]: same 3D volume (identical semantics to old code)
736
- # group-level agglomeration: merge two groups only if their COMBINED frame sets are disjoint
737
- # (so no two co-visible masklets ever land in one object) AND some cross-pair shares a 3D volume.
738
- groups = [
739
- {"members": [i], "frames": set(insts[i].get("frames", set()))} for i in range(n)
740
- ]
741
- changed = True
742
- while changed:
743
- changed = False
744
- for a in range(len(groups)):
745
- for b in range(a + 1, len(groups)):
746
- if (
747
- groups[a]["frames"] & groups[b]["frames"]
748
- ): # co-visible -> distinct objects
749
- continue
750
- if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
751
- groups[a]["members"] += groups[b]["members"]
752
- groups[a]["frames"] |= groups[b]["frames"]
753
- groups.pop(b)
754
- changed = True
755
- break
756
- if changed:
757
- break
758
- merged = []
759
- for g in groups:
760
- idxs = g["members"]
761
- pts = np.concatenate([insts[k]["pts"] for k in idxs], 0)
762
- cpts = np.concatenate(
763
- [
764
- insts[k].get("conf", np.ones(len(insts[k]["pts"]), np.float32))
765
- for k in idxs
766
- ],
767
- 0,
768
- )
769
- best = max(
770
- (insts[k]["best_pts"] for k in idxs), key=len
771
- ) # largest single obs in the group
772
- c, longest, dims = robust_centroid_extent(
773
- best, up_axis
774
- ) # size+pos+3 oriented dims from best view (#2/#4)
775
- merged.append(
776
- {
777
- "centroid": c,
778
- "size": longest,
779
- "dims": dims,
780
- "first_time": min(insts[k]["first_time"] for k in idxs),
781
- "pts": pts,
782
- "conf": cpts,
783
- "best_pts": best,
784
- "observations": [
785
- observation
786
- for k in idxs
787
- for observation in insts[k].get("observations", [insts[k]["pts"]])
788
- ],
789
- "frames": g["frames"],
790
- "n": sum(insts[k]["n"] for k in idxs),
791
- "nframes": len(g["frames"]),
792
- "oids": [oid for k in idxs for oid in insts[k].get("oids", [])],
793
- }
794
- ) # track persistence (evidence strength)
795
- return merged
796
-
797
-
798
- def build_instances(
799
- per_class, depth, intr, c2w, conf, frame_times, frame_paths=None, up_axis=None
800
- ):
801
- """-> {class: [ {centroid(3), size(longest dim), first_time, npts} ]}
802
- up_axis: if known (from room_gravity, computed BEFORE this call), threads through to
803
- robust_centroid_extent for yaw-only oriented sizing. If None, size falls back to
804
- unconstrained 3D PCA."""
805
- out = {}
806
- stats = {}
807
- nframes = len(depth)
808
- # precompute each frame's valid-depth mask ONCE (was recomputed per mask -> per class).
809
- valid = {}
810
- edges = {}
811
- rgb = {}
812
- used_frames = {fi for frames in per_class.values() for fi in frames if fi < nframes}
813
- for fi in used_frames:
814
- valid[fi] = np.isfinite(depth[fi]) & (depth[fi] > 0)
815
- edges[fi] = depth_edges(depth[fi], valid[fi]) if DEPTH_EDGE_REFINE else None
816
- if MASK_REFINE and frame_paths and fi < len(frame_paths):
817
- im = cv2.imread(frame_paths[fi]) # BGR; guidedFilter/grabCut want 3ch uint8
818
- rgb[fi] = (
819
- cv2.resize(im, (depth[fi].shape[1], depth[fi].shape[0]))
820
- if im is not None
821
- else None
822
- )
823
- for cls, frames in per_class.items():
824
- # peak co-visibility: max distinct masklets SAM3 tracks SIMULTANEOUSLY in any one frame.
825
- # geometry-free, parameter-free, immune to revisit over-count; provable lower bound on count.
826
- peak = max((len(objs) for objs in frames.values()), default=0)
827
- # gather world points + first-seen time + frame set per obj_id (SAM3 track id = masklet)
828
- pts_by_id, conf_by_id, first_t, frames_by_id = {}, {}, {}, {}
829
- # px_by_id: (fidx, frame_time, mask_pixel_count) per obj_id, for appearance-order timing.
830
- # VSI-Bench's own GT defines "first appearance" as the timestamp where an object's pixel
831
- # count crosses a threshold (paper appendix B.1) -- NOT the first frame with any pixel at
832
- # all. A single stray mask-bleed/false-positive pixel would otherwise register as "first
833
- # seen" far too early. The threshold is self-calibrated per instance (that instance's OWN
834
- # median observed pixel count across its frames), same convention as _clean's median cut.
835
- px_by_id = {}
836
- for fidx, objs in frames.items():
837
- if fidx >= nframes: # guard: SAM3 frame idx vs DA3 frames
838
- continue
839
- for oid, mask in objs.items():
840
- if MASK_REFINE and rgb.get(fidx) is not None:
841
- me = (
842
- mask
843
- if os.environ.get("VSI_NO_REFINE") == "1"
844
- else refine_mask(mask, rgb[fidx])
845
- ) # appearance-guided boundary snap (clips same-depth bleed)
846
- else:
847
- # erode 1px to drop mask-edge / background depth bleed
848
- me = cv2.erode(
849
- mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1
850
- ).astype(bool)
851
- if not me.any():
852
- me = mask
853
- conf_f = conf[fidx] if conf is not None else None
854
- conf_thr = (
855
- np.percentile(conf_f, CONF_PCT)
856
- if (conf_f is not None and CONF_PCT > 0)
857
- else 0.0
858
- )
859
- world_points, cw = backproject_frame(
860
- depth[fidx],
861
- intr[fidx],
862
- c2w[fidx],
863
- me,
864
- conf_f,
865
- conf_thr=conf_thr,
866
- valid_f=valid.get(fidx),
867
- return_conf=True,
868
- edges_f=edges.get(fidx),
869
- )
870
- if len(world_points):
871
- pts_by_id.setdefault(oid, []).append(world_points)
872
- conf_by_id.setdefault(oid, []).append(
873
- cw
874
- ) # per-point DA3 confidence (for _clean)
875
- frames_by_id.setdefault(oid, set()).add(
876
- fidx
877
- ) # for co-occurrence gate
878
- t = frame_times[fidx]
879
- px_by_id.setdefault(oid, []).append((fidx, t, int(me.sum())))
880
- # appearance_order timing: per instance, first frame at/above its OWN median pixel count
881
- for oid, obs in px_by_id.items():
882
- counts = [c for _, _, c in obs]
883
- thresh = float(np.median(counts))
884
- crossing = [t for _, t, c in obs if c >= thresh]
885
- first_t[oid] = min(crossing) if crossing else min(t for _, t, c in obs)
886
- insts = []
887
- for oid, plist in pts_by_id.items():
888
- pts = np.concatenate(plist, 0)
889
- cpts = np.concatenate(conf_by_id[oid], 0)
890
- if len(pts) < MIN_INSTANCE_PTS:
891
- continue
892
- best = max(
893
- plist, key=len
894
- ) # #2/#4: largest single-frame observation (closest/most pixels)
895
- bc, bsize, bdims = robust_centroid_extent(
896
- best, up_axis
897
- ) # size + position + 3 oriented dims from best view
898
- insts.append(
899
- {
900
- "centroid": bc,
901
- "size": bsize,
902
- "dims": bdims,
903
- "first_time": first_t[oid],
904
- "pts": pts,
905
- "conf": cpts,
906
- "best_pts": best,
907
- "observations": list(plist),
908
- "n": len(pts),
909
- "frames": frames_by_id[oid],
910
- # Raw SAM3 masklet id this fragment came from -- carried through every
911
- # later merge/consolidation step (never emitted in the JSON schema) so
912
- # a strong-correspondence overlay can draw SAM3's OWN per-frame
913
- # box/mask for a code instance instead of re-deriving one via 3D
914
- # projection. See encoder.geometric.instance_source_track_ids.
915
- "oids": [int(oid)],
916
- }
917
- )
918
- raw = len(insts)
919
- # 3D re-ID: fuse same-class masklets that occupy the same measured 3D volume (parameter-free).
920
- insts = merge_by_box_overlap(insts, up_axis)
921
- if insts:
922
- out[cls] = insts
923
- stats[cls] = {"raw": raw, "merged": len(insts), "peak": peak}
924
- return out, stats
925
-
926
-
927
- # ==========================================================================================
928
- # PER-CLASS SUMMARY -- legacy array-schema row builder. Merged in from perceptual.py, verbatim.
929
- # (The room-scale floor area calculation that used to live here is gone -- the explicit
930
- # schema's floor area is now a direct derivation of the compact schema's floor boundary
931
- # polygons; see build_explicit_spatial_code() near build_compact_spatial_code().)
932
- # ==========================================================================================
933
-
934
-
935
- # ---- Per-class spatial code (legacy array-schema row) -------------------------------------
936
- def class_spatial_code(insts, peak=0):
937
- cents = np.stack([i["centroid"] for i in insts], 0) # (n,3)
938
- sizes = np.array([i["size"] for i in insts], np.float32)
939
- n = len(insts) # merged centroids (for spatial stats)
940
- count = peak if peak else n # reported count = peak co-visibility
941
- x, y, z = cents.mean(0)
942
- if n == 1:
943
- e1 = e2 = e3 = px = pz = 0.0
944
- size_iqr = 0.0
945
- else:
946
- cov = np.cov(cents.T) # 3x3
947
- vals, vecs = np.linalg.eigh(cov) # ascending
948
- order = np.argsort(vals)[::-1]
949
- vals = np.clip(vals[order], 0, None)
950
- vecs = vecs[:, order]
951
- e1, e2, e3 = vals.tolist()
952
- pv = vecs[:, 0] # principal eigenvector
953
- px, pz = float(pv[0]), float(pv[2])
954
- q1, q3 = np.percentile(sizes, [25, 75])
955
- size_iqr = float(q3 - q1)
956
- size_median = float(np.median(sizes))
957
- first_time = float(min(i["first_time"] for i in insts))
958
- row = [x, y, z, e1, e2, e3, px, pz, size_median, size_iqr, first_time, count]
959
- row = [
960
- (lambda r: 0.0 if r == 0 else r)(round(float(v), 1)) for v in row
961
- ] # kill -0.0
962
- row[-1] = int(count)
963
- return row
964
-
965
-
966
- def _reference_object_records(insts, count, u, v, g, floor_level):
967
- """Object record formatter used by the original V2 spatial-code builder."""
968
- ranked = sorted(insts, key=lambda i: (i["n"], i.get("nframes", 0)), reverse=True)[
969
- : max(int(count), 1)
970
- ]
971
- recs = []
972
- for it in ranked:
973
- center = np.asarray(it["centroid"], np.float64)
974
- points = np.asarray(it["pts"], np.float64)
975
- floor_x = points @ u
976
- floor_y = points @ v
977
- height = points @ g - floor_level
978
- recs.append(
979
- {
980
- "position": {
981
- "floor_x_meters": round(float(center @ u), 2),
982
- "floor_y_meters": round(float(center @ v), 2),
983
- "height_above_floor_meters": round(
984
- float(center @ g - floor_level), 2
985
- ),
986
- },
987
- "longest_dimension_meters": round(float(it["size"]), 2),
988
- "bounding_box": {
989
- "floor_x_meters": [
990
- round(float(np.percentile(floor_x, 2)), 2),
991
- round(float(np.percentile(floor_x, 98)), 2),
992
- ],
993
- "floor_y_meters": [
994
- round(float(np.percentile(floor_y, 2)), 2),
995
- round(float(np.percentile(floor_y, 98)), 2),
996
- ],
997
- "height_above_floor_meters": [
998
- round(float(np.percentile(height, 2)), 2),
999
- round(float(np.percentile(height, 98)), 2),
1000
- ],
1001
- },
1002
- "dimensions_meters": [round(float(d), 2) for d in it["dims"]],
1003
- }
1004
- )
1005
- return recs
1006
-
1007
-
1008
- def _reference_to_spatial_code(
1009
- instances, stats, floor_area, up_axis, up_vec, floor_level
1010
- ):
1011
- """Per-instance spatial code shape from the original geometric V2 pipeline."""
1012
- u, v, g = _floor_basis(up_vec)
1013
- out = {"objects": {}}
1014
- for class_name, insts in instances.items():
1015
- count = int(stats[class_name]["peak"])
1016
- out["objects"][class_name] = {
1017
- "count": count,
1018
- "instances": _reference_object_records(insts, count, u, v, g, floor_level),
1019
- }
1020
- out["room"] = {"floor_area_square_meters": floor_area}
1021
- return out
1022
-
1023
-
1024
- def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
1025
- """Reference floor-area computation from the original geometric pipeline."""
1026
- points = []
1027
- for frame_index in range(depth.shape[0]):
1028
- height, width = depth[frame_index].shape
1029
- rows, columns = np.mgrid[0:height:stride, 0:width:stride]
1030
- rows = rows.ravel()
1031
- columns = columns.ravel()
1032
- values = depth[frame_index][rows, columns]
1033
- keep = np.isfinite(values) & (values > 0)
1034
- if sky is not None:
1035
- keep &= ~sky[frame_index][rows, columns].astype(bool)
1036
- if conf is not None:
1037
- keep &= conf[frame_index][rows, columns] >= np.percentile(
1038
- conf[frame_index], 40
1039
- )
1040
- rows, columns, values = rows[keep], columns[keep], values[keep]
1041
- if not len(values):
1042
- continue
1043
- current = intr[frame_index]
1044
- camera = np.stack(
1045
- [
1046
- (columns - current[0, 2]) * values / current[0, 0],
1047
- (rows - current[1, 2]) * values / current[1, 1],
1048
- values,
1049
- ],
1050
- 1,
1051
- )
1052
- world = (c2w[frame_index][:3, :3] @ camera.T).T + c2w[frame_index][:3, 3]
1053
- points.append(world.astype(np.float32))
1054
- if not points:
1055
- return 0.0
1056
- scene_points = np.concatenate(points, 0)
1057
- if up_vec is not None:
1058
- gravity = np.asarray(up_vec, np.float64)
1059
- gravity /= np.linalg.norm(gravity) + 1e-12
1060
- axis = (
1061
- np.array([1.0, 0.0, 0.0])
1062
- if abs(gravity[0]) < 0.9
1063
- else np.array([0.0, 1.0, 0.0])
1064
- )
1065
- u = np.cross(gravity, axis)
1066
- u /= np.linalg.norm(u)
1067
- v = np.cross(gravity, u)
1068
- floor_points = np.stack([scene_points @ u, scene_points @ v], 1)
1069
- else:
1070
- up_axis = int(np.argmin(scene_points.max(0) - scene_points.min(0)))
1071
- floor_axes = [axis for axis in range(3) if axis != up_axis]
1072
- floor_points = scene_points[:, floor_axes]
1073
- lower = np.percentile(floor_points, 0.5, 0)
1074
- upper = np.percentile(floor_points, 99.5, 0)
1075
- floor_points = floor_points[
1076
- (floor_points[:, 0] >= lower[0])
1077
- & (floor_points[:, 0] <= upper[0])
1078
- & (floor_points[:, 1] >= lower[1])
1079
- & (floor_points[:, 1] <= upper[1])
1080
- ]
1081
- if len(floor_points) < 10:
1082
- return 0.0
1083
- try:
1084
- import alphashape
1085
-
1086
- sample = np.random.RandomState(0).choice(
1087
- len(floor_points), min(10000, len(floor_points))
1088
- )
1089
- return round(
1090
- float(alphashape.alphashape(floor_points[sample], alpha=2).area), 1
1091
- )
1092
- except Exception:
1093
- from scipy import ndimage
1094
-
1095
- resolution = 0.10
1096
- rows = ((floor_points[:, 0] - floor_points[:, 0].min()) / resolution).astype(
1097
- int
1098
- )
1099
- columns = ((floor_points[:, 1] - floor_points[:, 1].min()) / resolution).astype(
1100
- int
1101
- )
1102
- grid = np.zeros((rows.max() + 3, columns.max() + 3), np.uint8)
1103
- grid[rows + 1, columns + 1] = 1
1104
- grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1105
- grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1106
- return round(float(grid.sum()) * resolution * resolution, 1)
1107
-
1108
-
1109
- # ---------------------------------------------------------------------------
1110
-
1111
- # ==========================================================================================
1112
- # SPATIAL CODE ASSEMBLY -- the top-level entry point this whole file exists for:
1113
- # build_spatial_code() calls everything above to turn already-computed depth/pose/masks into
1114
- # the final spatial code dict. Room outline + JSON writer. This section was already in
1115
- # geometric.py before the perceptual.py merge; build_spatial_code() below is updated to call
1116
- # the geometry functions above DIRECTLY (no `pl.` prefix -- they're plain local functions now
1117
- # that everything is in one file), same logic, unchanged otherwise.
1118
- # ==========================================================================================
1119
-
1120
-
1121
- def _room_outline(depth, intr, c2w, conf, bu, bv):
1122
- """(Unemitted by explicit format; compact format derives its boundary separately. This
1123
- math is kept intact for reuse.) Room floor-boundary polygon from the SAME grid as
1124
- compute_floor_area: floor points
1125
- projected onto the shared gravity plane (bu, bv), 10cm grid, close 7x7, fill holes,
1126
- largest contour, 0.2m polygon simplification. Same (bu, bv) as objects/camera, so the
1127
- outline, object positions, and floor_area all live in one consistent frame."""
1128
- from scipy import ndimage
1129
-
1130
- pts, stride = [], 8
1131
- for f in range(0, depth.shape[0], 3):
1132
- height, width = depth[f].shape
1133
- ys, xs = np.mgrid[0:height:stride, 0:width:stride]
1134
- ys = ys.ravel()
1135
- xs = xs.ravel()
1136
- z = depth[f][ys, xs]
1137
- ok = np.isfinite(z) & (z > 0)
1138
- if conf is not None:
1139
- ok &= conf[f][ys, xs] >= np.percentile(conf[f], 40)
1140
- ys, xs, z = ys[ok], xs[ok], z[ok]
1141
- if not len(z):
1142
- continue
1143
- intrinsics = intr[f]
1144
- camera_points = np.stack(
1145
- [
1146
- (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
1147
- (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
1148
- z,
1149
- ],
1150
- 1,
1151
- )
1152
- pts.append(
1153
- ((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3]).astype(np.float32)
1154
- )
1155
- if not pts:
1156
- return []
1157
- world_points = np.concatenate(pts, 0)
1158
- points = np.stack(
1159
- [world_points @ bu, world_points @ bv], 1
1160
- ) # gravity-plane projection (same bu,bv as objects/area)
1161
- lo = np.percentile(points, 0.5, 0)
1162
- hi = np.percentile(points, 99.5, 0)
1163
- points = points[
1164
- (points[:, 0] >= lo[0])
1165
- & (points[:, 0] <= hi[0])
1166
- & (points[:, 1] >= lo[1])
1167
- & (points[:, 1] <= hi[1])
1168
- ]
1169
- if len(points) < 10:
1170
- return []
1171
- res = 0.10
1172
- x0, y0 = points[:, 0].min(), points[:, 1].min()
1173
- ai = ((points[:, 0] - x0) / res).astype(int)
1174
- bi = ((points[:, 1] - y0) / res).astype(int)
1175
- grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
1176
- grid[ai + 1, bi + 1] = 1
1177
- grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1178
- grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1179
- cs, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1180
- if not cs:
1181
- return []
1182
- poly = cv2.approxPolyDP(max(cs, key=cv2.contourArea), 0.2 / res, True)[:, 0, :]
1183
- # cv2 contour points are (col=bi, row=ai) -> (floor_y, floor_x)
1184
- return [
1185
- {
1186
- "floor_x_meters": round(float((r - 1) * res + x0), 1),
1187
- "floor_y_meters": round(float((c - 1) * res + y0), 1),
1188
- }
1189
- for c, r in poly
1190
- ]
1191
-
1192
-
1193
- def dump_spatial_code(code, path):
1194
- """Save a spatial_code.json exactly like json.dump(code, f, indent=1), EXCEPT
1195
- "appearance order" is written as one compact line instead of one line per entry -- it's a
1196
- single ordered sequence meant to be scanned, not structured data meant to be read field by
1197
- field like the rest of the code. Every writer of spatial_code.json should go through this
1198
- (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
1199
- """
1200
- body = dict(code)
1201
- ao = body.pop("appearance order", None)
1202
- text = json.dumps(body, indent=1).rstrip()
1203
- if ao is not None:
1204
- assert text.endswith("}")
1205
- text = text[:-1].rstrip() + ',\n "appearance order": ' + json.dumps(ao) + "\n}"
1206
- with open(path, "w") as f:
1207
- f.write(text)
1208
-
1209
-
1210
- # Canonical world-space fallback used by SegVGGT and similar adapters.
1211
- def _canonical_room_gravity(points, cameras=None, iters=300, thr=0.05):
1212
- """Robust UP vector = normal of the RANSAC floor plane, oriented toward the cameras."""
1213
- points = np.asarray(points, np.float64)
1214
- points = points[np.isfinite(points).all(1)]
1215
- if len(points) > 100000:
1216
- points = points[np.random.RandomState(0).choice(len(points), 100000, False)]
1217
- cam = (
1218
- np.asarray(cameras, np.float64).mean(0)
1219
- if cameras is not None and len(cameras)
1220
- else None
1221
- )
1222
- if len(points) < 100:
1223
- ext = (
1224
- np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
1225
- if len(points)
1226
- else np.ones(3)
1227
- )
1228
- ax = int(np.argmin(ext))
1229
- g = np.zeros(3)
1230
- g[ax] = 1.0
1231
- return (g, ax)
1232
- rng = np.random.RandomState(0)
1233
- best = None
1234
- best_score = -1
1235
- for _ in range(iters):
1236
- a, b, c = points[rng.choice(len(points), 3, False)]
1237
- nrm = np.cross(b - a, c - a)
1238
- ln = np.linalg.norm(nrm)
1239
- if ln < 1e-06:
1240
- continue
1241
- nrm /= ln
1242
- d = -nrm @ a
1243
- side = points @ nrm + d
1244
- ninl = int((np.abs(side) < thr).sum())
1245
- if ninl < 50:
1246
- continue
1247
- score = ninl * max(np.mean(side > thr), np.mean(side < -thr))
1248
- if score > best_score:
1249
- best_score = score
1250
- best = (nrm, d)
1251
- if best is None:
1252
- ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
1253
- ax = int(np.argmin(ext))
1254
- g = np.zeros(3)
1255
- g[ax] = 1.0
1256
- return (g, ax)
1257
- nrm, d = best
1258
- if cam is not None and cam @ nrm + d < 0:
1259
- nrm = -nrm
1260
- return (nrm.astype(np.float32), int(np.argmax(np.abs(nrm))))
1261
-
1262
-
1263
- def _canonical_floor_basis(up_vec):
1264
- """Orthonormal floor basis (u, v horizontal; g = up), unchanged from the old file."""
1265
- g = np.asarray(up_vec, np.float64)
1266
- g = g / (np.linalg.norm(g) + 1e-12)
1267
- up_ax = int(np.argmax(np.abs(g)))
1268
- floor_axes = [a for a in range(3) if a != up_ax]
1269
- e0 = np.zeros(3)
1270
- e0[floor_axes[0]] = 1.0
1271
- u = e0 - e0 @ g * g
1272
- u = u / (np.linalg.norm(u) + 1e-12)
1273
- v = np.cross(g, u)
1274
- if v[floor_axes[1]] < 0:
1275
- v = -v
1276
- return (u, v, g)
1277
-
1278
-
1279
- def _canonical_robust_centroid_extent(pts, up_axis=None):
1280
- c = np.median(pts, axis=0)
1281
- centered = pts - c
1282
- if len(centered) > 5000:
1283
- centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
1284
- if up_axis is not None:
1285
- floor_axes = [i for i in range(3) if i != up_axis]
1286
- floor_points = centered[:, floor_axes]
1287
- try:
1288
- _, _, floor_rotation = np.linalg.svd(
1289
- floor_points - floor_points.mean(0), full_matrices=False
1290
- )
1291
- proj_floor = floor_points @ floor_rotation.T
1292
- except np.linalg.LinAlgError:
1293
- proj_floor = floor_points
1294
- proj = np.concatenate([proj_floor, centered[:, up_axis : up_axis + 1]], 1)
1295
- else:
1296
- try:
1297
- _, _, rotation = np.linalg.svd(
1298
- centered - centered.mean(0), full_matrices=False
1299
- )
1300
- proj = centered @ rotation.T
1301
- except np.linalg.LinAlgError:
1302
- proj = centered
1303
- ext = np.maximum(np.percentile(proj, 98, 0) - np.percentile(proj, 2, 0), 0.0)
1304
- dims = np.sort(ext)[::-1]
1305
- return (c.astype(np.float32), float(dims[0]), dims)
1306
-
1307
-
1308
- def _canonical_aabb(pts):
1309
- return (np.percentile(pts, 2, 0), np.percentile(pts, 98, 0))
1310
-
1311
-
1312
- def _canonical_merge_by_box_overlap(insts, up_axis=None):
1313
- """Parameter-free 3D re-identification with temporal exclusion, unchanged."""
1314
- n = len(insts)
1315
- if n <= 1:
1316
- return insts
1317
- lo = np.stack([_canonical_aabb(i["pts"])[0] for i in insts])
1318
- hi = np.stack([_canonical_aabb(i["pts"])[1] for i in insts])
1319
- cents = np.stack([i["centroid"] for i in insts])
1320
- overlap = (hi[:, None] >= lo[None]).all(-1) & (hi[None] >= lo[:, None]).all(-1)
1321
- ins = (cents[:, None] >= lo[None]).all(-1) & (cents[:, None] <= hi[None]).all(-1)
1322
- match = overlap | ins | ins.T
1323
- groups = [
1324
- {"members": [i], "frames": set(insts[i].get("frames", ()))} for i in range(n)
1325
- ]
1326
- changed = True
1327
- while changed:
1328
- changed = False
1329
- for a in range(len(groups)):
1330
- for b in range(a + 1, len(groups)):
1331
- if groups[a]["frames"] & groups[b]["frames"]:
1332
- continue
1333
- if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
1334
- groups[a]["members"] += groups[b]["members"]
1335
- groups[a]["frames"] |= groups[b]["frames"]
1336
- groups.pop(b)
1337
- changed = True
1338
- break
1339
- if changed:
1340
- break
1341
- out = []
1342
- for g in groups:
1343
- ii = g["members"]
1344
- pts = np.concatenate([insts[k]["pts"] for k in ii], 0)
1345
- best = max((insts[k]["best_pts"] for k in ii), key=len)
1346
- c, size, dims = _canonical_robust_centroid_extent(best, up_axis)
1347
- confs = [insts[k].get("conf") for k in ii]
1348
- conf = (
1349
- np.concatenate([x for x in confs if x is not None], 0)
1350
- if any((x is not None for x in confs))
1351
- else None
1352
- )
1353
- out.append(
1354
- {
1355
- "centroid": c,
1356
- "size": size,
1357
- "dims": dims,
1358
- "pts": pts,
1359
- "best_pts": best,
1360
- "observations": [
1361
- observation
1362
- for k in ii
1363
- for observation in insts[k].get("observations", [insts[k]["pts"]])
1364
- ],
1365
- "conf": conf,
1366
- "frames": g["frames"],
1367
- "nframes": len(g["frames"]),
1368
- "n": sum((insts[k]["n"] for k in ii)),
1369
- "first_time": min((insts[k]["first_time"] for k in ii)),
1370
- }
1371
- )
1372
- return out
1373
-
1374
-
1375
- def _canonical_sor(pts, k=16, std=2.0, cap=4000):
1376
- from scipy.spatial import cKDTree
1377
-
1378
- if len(pts) < k + 2:
1379
- return pts
1380
- points = (
1381
- pts
1382
- if len(pts) <= cap
1383
- else pts[np.random.RandomState(0).choice(len(pts), cap, False)]
1384
- )
1385
- d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
1386
- md = d[:, 1:].mean(1)
1387
- return points[md <= md.mean() + std * md.std()]
1388
-
1389
-
1390
- def _canonical_clean(inst, cap=4000):
1391
- if inst.get("_cleanpts") is not None:
1392
- return inst["_cleanpts"]
1393
- pts, conf = (inst["pts"], inst.get("conf"))
1394
- if len(pts) > cap:
1395
- idx = np.random.RandomState(0).choice(len(pts), cap, False)
1396
- pts = pts[idx]
1397
- if conf is not None:
1398
- conf = conf[idx]
1399
- if conf is not None and len(conf) > 20:
1400
- keep = conf >= np.median(conf)
1401
- if keep.sum() >= 10:
1402
- pts = pts[keep]
1403
- inst["_cleanpts"] = _canonical_sor(pts, cap=cap)
1404
- return inst["_cleanpts"]
1405
-
1406
-
1407
- # ==========================================================================================
1408
- # COMPACT SPATIAL CODE -- reusable geometry and time primitives, with no derived answers.
1409
- # ==========================================================================================
1410
-
1411
-
1412
- COMPACT_SPATIAL_CODE_SCHEMA = {
1413
- "objects": {
1414
- "<object class>": [
1415
- {
1416
- "3D oriented bounding box": {
1417
- "3D oriented bounding box center coordinates": {
1418
- "components": ["x", "y", "height above floor"],
1419
- "unit": "meters",
1420
- "description": (
1421
- "center of the 3D oriented bounding box in the shared room "
1422
- "coordinate system"
1423
- ),
1424
- },
1425
- "3D oriented bounding box dimensions": {
1426
- "components": ["dimension 1", "dimension 2", "dimension 3"],
1427
- "unit": "meters",
1428
- "description": (
1429
- "full lengths of the 3D oriented bounding box along the "
1430
- "corresponding orientation unit vectors"
1431
- ),
1432
- },
1433
- "3D oriented bounding box orientation unit vectors": {
1434
- "components": [
1435
- ["x", "y", "height"],
1436
- ["x", "y", "height"],
1437
- ["x", "y", "height"],
1438
- ],
1439
- "unit": None,
1440
- "description": (
1441
- "three perpendicular directions corresponding in order to the "
1442
- "three 3D oriented bounding box dimensions"
1443
- ),
1444
- },
1445
- },
1446
- "first visible time": {
1447
- "unit": "seconds",
1448
- "description": (
1449
- "earliest time at which this object instance is visibly observed"
1450
- ),
1451
- },
1452
- }
1453
- ]
1454
- },
1455
- "room": {
1456
- "floor boundary polygons": [
1457
- {
1458
- "outer boundary coordinates": {
1459
- "components": [["x", "y"], ["x", "y"]],
1460
- "unit": "meters",
1461
- "description": "ordered vertices enclosing one floor region",
1462
- },
1463
- "interior hole boundary coordinates": {
1464
- "components": [[["x", "y"], ["x", "y"]]],
1465
- "unit": "meters",
1466
- "description": (
1467
- "ordered boundaries enclosing regions excluded from the floor area"
1468
- ),
1469
- },
1470
- }
1471
- ]
1472
- },
1473
- }
1474
-
1475
-
1476
- def _rounded_list(values):
1477
- """Round one numeric vector to stable JSON values without negative zero."""
1478
- return [0.0 if (value := round(float(x), 2)) == 0 else value for x in values]
1479
-
1480
-
1481
- def _weighted_quantile(values, weights, quantile):
1482
- """Return one deterministic weighted quantile for observation consensus."""
1483
- values = np.asarray(values, np.float64)
1484
- weights = np.asarray(weights, np.float64)
1485
- order = np.argsort(values)
1486
- values, weights = values[order], weights[order]
1487
- cumulative = np.cumsum(weights) - 0.5 * weights
1488
- cumulative /= weights.sum()
1489
- return float(np.interp(quantile, cumulative, values))
1490
-
1491
-
1492
- def _compact_oriented_box(instance, u, v, g, floor_level):
1493
- """Fit one floor-aligned OBB from the same per-instance math as the reference code."""
1494
- center = np.asarray(instance["centroid"], np.float64)
1495
- points = np.asarray(instance["best_pts"], np.float64)
1496
- room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
1497
- centered = room_points[:, :2] - np.median(room_points[:, :2], axis=0)
1498
- if len(centered) > 5000:
1499
- centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
1500
- try:
1501
- _, _, rotation = np.linalg.svd(
1502
- centered - centered.mean(axis=0), full_matrices=False
1503
- )
1504
- except np.linalg.LinAlgError:
1505
- rotation = np.eye(2)
1506
- first = rotation[0]
1507
- dominant = int(np.argmax(np.abs(first)))
1508
- if first[dominant] < 0:
1509
- first = -first
1510
- second = np.array([-first[1], first[0]])
1511
- orientation = np.array(
1512
- [[first[0], first[1], 0.0], [second[0], second[1], 0.0], [0.0, 0.0, 1.0]]
1513
- )
1514
- box_center = np.array([center @ u, center @ v, center @ g - floor_level])
1515
- box_dimensions = np.asarray(instance["dims"], np.float64)
1516
- return {
1517
- "3D oriented bounding box center coordinates": _rounded_list(box_center),
1518
- "3D oriented bounding box dimensions": _rounded_list(box_dimensions),
1519
- "3D oriented bounding box orientation unit vectors": [
1520
- _rounded_list(axis) for axis in orientation
1521
- ],
1522
- }
1523
-
1524
-
1525
- def _contour_coordinates(contour, x_origin, y_origin, resolution):
1526
- """Translate one OpenCV grid contour to ordered shared-room coordinates."""
1527
- return [
1528
- _rounded_list(
1529
- [x_origin + (row - 1) * resolution, y_origin + (column - 1) * resolution]
1530
- )
1531
- for column, row in contour[:, 0, :]
1532
- ]
1533
-
1534
-
1535
- def _compact_scene_points(scene):
1536
- """Return the same dense floor-support sample used by explicit room-area math."""
1537
- raw_inputs = scene.get("raw_inputs")
1538
- if raw_inputs is None:
1539
- return scene["scene_pts"]
1540
- depth = raw_inputs["depth"]
1541
- intrinsics = raw_inputs["intr"]
1542
- poses = raw_inputs["c2w"]
1543
- confidence = raw_inputs.get("conf")
1544
- points = []
1545
- for frame_index in range(len(depth)):
1546
- height, width = depth[frame_index].shape
1547
- rows, columns = np.mgrid[0:height:8, 0:width:8]
1548
- rows, columns = rows.ravel(), columns.ravel()
1549
- values = depth[frame_index][rows, columns]
1550
- keep = np.isfinite(values) & (values > 0)
1551
- if confidence is not None:
1552
- threshold = np.percentile(confidence[frame_index], 40)
1553
- keep &= confidence[frame_index][rows, columns] >= threshold
1554
- rows, columns, values = rows[keep], columns[keep], values[keep]
1555
- if not len(values):
1556
- continue
1557
- current = intrinsics[frame_index]
1558
- camera = np.stack(
1559
- [
1560
- (columns - current[0, 2]) * values / current[0, 0],
1561
- (rows - current[1, 2]) * values / current[1, 1],
1562
- values,
1563
- ],
1564
- axis=1,
1565
- )
1566
- world = poses[frame_index][:3, :3] @ camera.T
1567
- points.append((world.T + poses[frame_index][:3, 3]).astype(np.float32))
1568
- return np.concatenate(points, axis=0) if points else scene["scene_pts"]
1569
-
1570
-
1571
- def _compact_floor_boundary_polygons(points, u, v, object_points=None):
1572
- """Extract the reference room outline as a compact floor-boundary polygon."""
1573
- from scipy import ndimage
1574
-
1575
- points = np.asarray(points, np.float64)
1576
- floor_points = np.stack([points @ u, points @ v], axis=1)
1577
- floor_points = floor_points[np.isfinite(floor_points).all(axis=1)]
1578
- if len(floor_points) < 3:
1579
- return []
1580
- lower = np.percentile(floor_points, 0.5, axis=0)
1581
- upper = np.percentile(floor_points, 99.5, axis=0)
1582
- floor_points = floor_points[
1583
- (floor_points[:, 0] >= lower[0])
1584
- & (floor_points[:, 0] <= upper[0])
1585
- & (floor_points[:, 1] >= lower[1])
1586
- & (floor_points[:, 1] <= upper[1])
1587
- ]
1588
- if len(floor_points) < 3:
1589
- return []
1590
- resolution = 0.1
1591
- x_origin, y_origin = floor_points.min(axis=0)
1592
- x_max, y_max = floor_points.max(axis=0)
1593
- row_count = int((x_max - x_origin) / resolution) + 3
1594
- column_count = int((y_max - y_origin) / resolution) + 3
1595
- grid = np.zeros((row_count, column_count), np.uint8)
1596
- rows = ((floor_points[:, 0] - x_origin) / resolution).astype(int)
1597
- columns = ((floor_points[:, 1] - y_origin) / resolution).astype(int)
1598
- grid[rows + 1, columns + 1] = 1
1599
- grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1600
- grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1601
- contours, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1602
- if not contours:
1603
- return []
1604
- contour = cv2.approxPolyDP(
1605
- max(contours, key=cv2.contourArea), 0.2 / resolution, True
1606
- )
1607
- return [
1608
- {
1609
- "outer boundary coordinates": _contour_coordinates(
1610
- contour, x_origin, y_origin, resolution
1611
- ),
1612
- "interior hole boundary coordinates": [],
1613
- }
1614
- ]
1615
-
1616
-
1617
- def _compact_duplicate_groups(instances):
1618
- """Group near-identical co-visible boxes that represent duplicate mask tracks."""
1619
- count = len(instances)
1620
- parent = list(range(count))
1621
-
1622
- def root(index):
1623
- while parent[index] != index:
1624
- parent[index] = parent[parent[index]]
1625
- index = parent[index]
1626
- return index
1627
-
1628
- def union(first, second):
1629
- first, second = root(first), root(second)
1630
- if first != second:
1631
- parent[second] = first
1632
-
1633
- bounds = [_canonical_aabb(_canonical_clean(instance)) for instance in instances]
1634
- for first in range(count):
1635
- lower_a, upper_a = bounds[first]
1636
- extent_a = np.maximum(upper_a - lower_a, 1e-6)
1637
- volume_a = float(np.prod(extent_a))
1638
- for second in range(first + 1, count):
1639
- lower_b, upper_b = bounds[second]
1640
- extent_b = np.maximum(upper_b - lower_b, 1e-6)
1641
- volume_b = float(np.prod(extent_b))
1642
- intersection = np.maximum(
1643
- np.minimum(upper_a, upper_b) - np.maximum(lower_a, lower_b), 0.0
1644
- )
1645
- overlap = float(np.prod(intersection)) / min(volume_a, volume_b)
1646
- if overlap >= 0.8:
1647
- union(first, second)
1648
- groups = {}
1649
- for index in range(count):
1650
- groups.setdefault(root(index), []).append(index)
1651
- return list(groups.values())
1652
-
1653
-
1654
- def _combine_compact_instances(instances, members, up_axis):
1655
- """Combine one duplicate group while retaining all evidence and earliest timing."""
1656
- selected = [instances[index] for index in members]
1657
- points = np.concatenate([instance["pts"] for instance in selected], axis=0)
1658
- best = max((instance["best_pts"] for instance in selected), key=len)
1659
- confidence = [instance.get("conf") for instance in selected]
1660
- confidence = (
1661
- np.concatenate(confidence, axis=0)
1662
- if all(value is not None for value in confidence)
1663
- else None
1664
- )
1665
- centroid, size, dimensions = _canonical_robust_centroid_extent(points, up_axis)
1666
- frames = set().union(*(set(instance.get("frames", ())) for instance in selected))
1667
- return {
1668
- "centroid": centroid,
1669
- "size": size,
1670
- "dims": dimensions,
1671
- "first_time": min(instance["first_time"] for instance in selected),
1672
- "pts": points,
1673
- "conf": confidence,
1674
- "best_pts": best,
1675
- "observations": [
1676
- observation
1677
- for instance in selected
1678
- for observation in instance.get("observations", [instance["pts"]])
1679
- ],
1680
- "frames": frames,
1681
- "n": sum(instance.get("n", len(instance["pts"])) for instance in selected),
1682
- "nframes": len(frames),
1683
- "oids": [oid for instance in selected for oid in instance.get("oids", [])],
1684
- }
1685
-
1686
-
1687
- def _compact_instance_evidence(instance):
1688
- """Rank one physical-instance hypothesis by persistence and geometric support."""
1689
- observations = instance.get("observations", [instance["pts"]])
1690
- observed_points = np.array([len(observation) for observation in observations])
1691
- return (
1692
- instance.get("nframes", len(instance.get("frames", ()))),
1693
- len(observations),
1694
- float(np.median(observed_points)) if len(observed_points) else 0.0,
1695
- instance.get("n", len(instance["pts"])),
1696
- )
1697
-
1698
-
1699
- def _consolidate_compact_instances(instances, stats, up_axis):
1700
- """Suppress duplicate tracks and retain the strongest co-visible instance set."""
1701
- consolidated = {}
1702
- for class_name, items in instances.items():
1703
- combined = [
1704
- _combine_compact_instances(items, members, up_axis)
1705
- for members in _compact_duplicate_groups(items)
1706
- ]
1707
- peak = int(stats.get(class_name, {}).get("peak", 0))
1708
- limit = min(len(combined), max(peak, 1))
1709
- ranked = sorted(combined, key=_compact_instance_evidence, reverse=True)
1710
- retained = ranked[:limit]
1711
- for fragment in ranked[limit:]:
1712
- nearest = min(
1713
- retained,
1714
- key=lambda instance: np.linalg.norm(
1715
- instance["centroid"] - fragment["centroid"]
1716
- ),
1717
- )
1718
- nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
1719
- consolidated[class_name] = retained
1720
- return consolidated
1721
-
1722
-
1723
- def _compact_instances(scene, up_axis):
1724
- """Return consolidated physical instances for raw or canonical adapter geometry."""
1725
- raw_inputs = scene.get("raw_inputs")
1726
- if raw_inputs is not None:
1727
- instances, stats = build_instances(
1728
- raw_inputs["per"],
1729
- raw_inputs["depth"],
1730
- raw_inputs["intr"],
1731
- raw_inputs["c2w"],
1732
- raw_inputs.get("conf"),
1733
- raw_inputs["ftimes"],
1734
- up_axis=up_axis,
1735
- )
1736
- else:
1737
- instances = {}
1738
- stats = {
1739
- class_name: dict(values) for class_name, values in scene["stats"].items()
1740
- }
1741
- for class_name, items in scene["instances"].items():
1742
- measured = []
1743
- for item in items:
1744
- points = _canonical_clean(item)
1745
- if not len(points):
1746
- points = item["pts"]
1747
- centroid, size, dimensions = _canonical_robust_centroid_extent(
1748
- points, up_axis
1749
- )
1750
- record = dict(item)
1751
- record.update({"centroid": centroid, "size": size, "dims": dimensions})
1752
- measured.append(record)
1753
- instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
1754
- for class_name, items in instances.items():
1755
- stats.setdefault(class_name, {})
1756
- stats[class_name]["merged"] = len(items)
1757
- return instances, stats
1758
-
1759
-
1760
- def instance_source_track_ids(scene):
1761
- """Return {emitted_class_name: [oids_for_instance_1, oids_for_instance_2, ...]},
1762
- one ordered list of raw SAM3 masklet ids per FINAL consolidated instance -- in
1763
- EXACTLY the rank order build_compact_spatial_code() emits instances in (same
1764
- (n, nframes)-descending sort, same class-name aliasing), so index i here IS the
1765
- "<class> {i+1}" instance id the strong correspondence overlay stamps. A raw-only
1766
- lookup: reruns nothing but the consolidation build_compact_spatial_code() already
1767
- does, just exposing the "oids" field that pipeline discards before emission (the
1768
- on-disk schema never carries SAM3 ids -- this function is the only place that does).
1769
- """
1770
- alias = {"coat hanger": "coat rack"}
1771
- raw_inputs = scene.get("raw_inputs")
1772
- if raw_inputs is None:
1773
- raise ValueError(
1774
- "instance_source_track_ids needs raw depth/intr/c2w inputs; this geometry "
1775
- "cache carries only canonical points (no SAM3 track ids to recover)"
1776
- )
1777
- up_vec, up_ax = room_gravity(
1778
- raw_inputs["depth"],
1779
- raw_inputs["intr"],
1780
- raw_inputs["c2w"],
1781
- raw_inputs.get("conf"),
1782
- )
1783
- instances, _stats = _compact_instances(scene, up_ax)
1784
- out = {}
1785
- for class_name, items in instances.items():
1786
- emitted_name = alias.get(class_name, class_name)
1787
- ranked = sorted(
1788
- items,
1789
- key=lambda item: (item.get("n", 0), item.get("nframes", 0)),
1790
- reverse=True,
1791
- )
1792
- out.setdefault(emitted_name, []).extend(item.get("oids", []) for item in ranked)
1793
- return out
1794
-
1795
-
1796
- def build_compact_spatial_code(scene):
1797
- """Build reusable OBB, visibility-time, and floor-boundary primitives."""
1798
- alias = {"coat hanger": "coat rack"}
1799
- raw_inputs = scene.get("raw_inputs")
1800
- if raw_inputs is not None:
1801
- up_vec, up_ax = room_gravity(
1802
- raw_inputs["depth"],
1803
- raw_inputs["intr"],
1804
- raw_inputs["c2w"],
1805
- raw_inputs.get("conf"),
1806
- )
1807
- u, v, g = _floor_basis(up_vec)
1808
- else:
1809
- up_vec, up_ax = _canonical_room_gravity(
1810
- scene["scene_pts"], scene.get("cameras")
1811
- )
1812
- u, v, g = _canonical_floor_basis(up_vec)
1813
- instances, stats = _compact_instances(scene, up_ax)
1814
- all_points = np.concatenate(
1815
- [item["pts"] for values in instances.values() for item in values], axis=0
1816
- )
1817
- floor_level = _floor_level(all_points, g)
1818
- objects = {}
1819
- for class_name, items in instances.items():
1820
- emitted_name = alias.get(class_name, class_name)
1821
- ranked = sorted(
1822
- items,
1823
- key=lambda item: (item.get("n", 0), item.get("nframes", 0)),
1824
- reverse=True,
1825
- )
1826
- count = int(stats.get(class_name, {}).get("peak", 0))
1827
- ranked = ranked[: max(count, 1)]
1828
- objects.setdefault(emitted_name, []).extend(
1829
- {
1830
- "3D oriented bounding box": _compact_oriented_box(
1831
- item, u, v, g, floor_level
1832
- ),
1833
- "first visible time": round(float(item["first_time"]), 2),
1834
- }
1835
- for item in ranked
1836
- )
1837
- code = {
1838
- "objects": objects,
1839
- "room": {
1840
- "floor boundary polygons": _compact_floor_boundary_polygons(
1841
- _compact_scene_points(scene), u, v
1842
- )
1843
- },
1844
- }
1845
- return code, instances, stats, up_ax, up_vec, None
1846
-
1847
-
1848
- # ==========================================================================================
1849
- # EXPLICIT SPATIAL CODE -- a strict derivation of the compact schema above. Every object
1850
- # position/dimension/count/appearance-order value is read directly off compact's own oriented
1851
- # boxes and "first visible time" (a direct subset, not independently recomputed); the distance
1852
- # table is the one thing compact never stores, so it is computed here purely from compact's own
1853
- # 3D oriented boxes -- exact surface-to-surface separation via bounded least squares (same
1854
- # convex, closed-form-adjacent optimization symbolic/adapters.py's solver-side derivation
1855
- # already used for compact input, now the ACTUAL on-disk construction for explicit too, so the
1856
- # two schemas can never independently disagree about the same scene's geometry).
1857
- # ==========================================================================================
1858
-
1859
-
1860
- EXPLICIT_SPATIAL_CODE_SCHEMA = {
1861
- "objects": {
1862
- "<object class>": {
1863
- "count": {
1864
- "unit": None,
1865
- "description": (
1866
- "number of instances of this class in the compact spatial code "
1867
- "(that schema's per-class oriented-box list length)"
1868
- ),
1869
- },
1870
- "instances": [
1871
- {
1872
- "position": {
1873
- "x coordinate": {
1874
- "unit": "meters",
1875
- "description": (
1876
- "x coordinate of this instance's compact 3D oriented "
1877
- "bounding box center"
1878
- ),
1879
- },
1880
- "y coordinate": {
1881
- "unit": "meters",
1882
- "description": (
1883
- "y coordinate of this instance's compact 3D oriented "
1884
- "bounding box center"
1885
- ),
1886
- },
1887
- "height above floor": {
1888
- "unit": "meters",
1889
- "description": (
1890
- "height coordinate of this instance's compact 3D oriented "
1891
- "bounding box center"
1892
- ),
1893
- },
1894
- },
1895
- "longest dimension": {
1896
- "unit": "meters",
1897
- "description": (
1898
- "longest of this instance's compact 3D oriented bounding box "
1899
- "dimensions"
1900
- ),
1901
- },
1902
- }
1903
- ],
1904
- }
1905
- },
1906
- "room": {
1907
- "floor area": {
1908
- "unit": "square meters",
1909
- "description": (
1910
- "shoelace area of the compact spatial code's floor boundary polygons, "
1911
- "with every interior hole subtracted"
1912
- ),
1913
- }
1914
- },
1915
- "closest classes distance meters from": {
1916
- "<object class>": {
1917
- "<other object class>": {
1918
- "distance": {
1919
- "unit": "meters",
1920
- "description": (
1921
- "estimated distance in meters between an object of this class "
1922
- "and an object of the other class"
1923
- ),
1924
- },
1925
- "closeness rank": {
1926
- "unit": None,
1927
- "description": (
1928
- "1 = the nearest other class to this one, 2 = second-nearest, "
1929
- "and so on; ranked by nearest-instance proximity, so use the "
1930
- "rank (not the distance values) to compare which class is "
1931
- "closest"
1932
- ),
1933
- },
1934
- }
1935
- }
1936
- },
1937
- "appearance order": {
1938
- "unit": None,
1939
- "description": (
1940
- "class names ordered by earliest compact 'first visible time' across all of "
1941
- "that class's instances"
1942
- ),
1943
- },
1944
- }
1945
-
1946
-
1947
- def _compact_box_distance(box_a, box_b):
1948
- """Return the true minimum Euclidean separation of two compact 3D oriented boxes.
1949
-
1950
- Verbatim derivation from symbolic/adapters.py's oriented_box_distance(): the six box
1951
- coefficients form one convex bounded least-squares problem, solved exactly by BVLS -- no
1952
- center, corner, or longest-dimension shortcut, so touching/intersecting boxes return zero.
1953
-
1954
- Orientation vectors are renormalized to unit length before use, exactly like
1955
- symbolic/adapters.py's _oriented_box() -- compact's on-disk vectors are rounded to 2
1956
- decimals, so they are no longer *exactly* unit length, and the matrix below implicitly
1957
- assumes they are (each column is dimension/2 along that axis). Skipping this step is a
1958
- real source of error, not just a rounding artifact: it measurably shifted computed
1959
- distances in testing (up to ~0.01 m on real scenes), and would make explicit silently
1960
- disagree with what the solver derives from the identical compact box at read time.
1961
- """
1962
- from scipy.optimize import lsq_linear
1963
-
1964
- center_a = np.asarray(
1965
- box_a["3D oriented bounding box center coordinates"], np.float64
1966
- )
1967
- dimensions_a = np.asarray(box_a["3D oriented bounding box dimensions"], np.float64)
1968
- orientation_a = np.asarray(
1969
- box_a["3D oriented bounding box orientation unit vectors"], np.float64
1970
- )
1971
- orientation_a = orientation_a / np.linalg.norm(orientation_a, axis=1, keepdims=True)
1972
- center_b = np.asarray(
1973
- box_b["3D oriented bounding box center coordinates"], np.float64
1974
- )
1975
- dimensions_b = np.asarray(box_b["3D oriented bounding box dimensions"], np.float64)
1976
- orientation_b = np.asarray(
1977
- box_b["3D oriented bounding box orientation unit vectors"], np.float64
1978
- )
1979
- orientation_b = orientation_b / np.linalg.norm(orientation_b, axis=1, keepdims=True)
1980
- matrix = np.column_stack(
1981
- [
1982
- *(dimensions_a[index] * orientation_a[index] / 2 for index in range(3)),
1983
- *(-dimensions_b[index] * orientation_b[index] / 2 for index in range(3)),
1984
- ]
1985
- )
1986
- result = lsq_linear(
1987
- matrix,
1988
- center_b - center_a,
1989
- bounds=(-1, 1),
1990
- method="bvls",
1991
- lsq_solver="exact",
1992
- tol=1e-12,
1993
- max_iter=200,
1994
- )
1995
- if not result.success:
1996
- raise RuntimeError(
1997
- f"oriented-box distance optimization failed: {result.message}"
1998
- )
1999
- distance = float(np.linalg.norm(matrix @ result.x + center_a - center_b))
2000
- return 0.0 if distance < 1e-10 else distance
2001
-
2002
-
2003
- def _compact_class_distance(instances_a, instances_b):
2004
- """Return the minimum compact oriented-box distance across every cross-class instance pair."""
2005
- return min(
2006
- _compact_box_distance(
2007
- a["3D oriented bounding box"], b["3D oriented bounding box"]
2008
- )
2009
- for a in instances_a
2010
- for b in instances_b
2011
- )
2012
-
2013
-
2014
- def _primary_instance_distance_floor(instances_a, instances_b):
2015
- """A sphere-approximation floor on the two classes' PRIMARY (instance[0]) distance:
2016
- 3D center-to-center distance minus each primary box's longest dimension / 2, floored
2017
- at 0. Mirrors symbolic/solver.py's _primary_instance_distance_estimate exactly (the
2018
- same correction, applied at ENCODING time so the table value a reader looks up
2019
- already carries it -- see _corrected_class_distance below)."""
2020
- box_a = instances_a[0]["3D oriented bounding box"]
2021
- box_b = instances_b[0]["3D oriented bounding box"]
2022
- center_a = box_a["3D oriented bounding box center coordinates"]
2023
- center_b = box_b["3D oriented bounding box center coordinates"]
2024
- center_distance = (
2025
- sum((float(a) - float(b)) ** 2 for a, b in zip(center_a, center_b)) ** 0.5
2026
- )
2027
- radius_a = max(box_a["3D oriented bounding box dimensions"]) / 2
2028
- radius_b = max(box_b["3D oriented bounding box dimensions"]) / 2
2029
- return max(0.0, center_distance - (radius_a + radius_b))
2030
-
2031
-
2032
- def _corrected_class_distance(instances_a, instances_b):
2033
- """max(min-across-pairs surface distance, primary-instance sphere floor) -- the
2034
- combination symbolic/solver.py applies at ANSWER time for ABSOLUTE-distance
2035
- questions. TRIED AND REVERTED as the table's stored value (2026-07-25, see
2036
- preregistration.md): baking it in re-derived the closeness RANKS from
2037
- corrected distances, and closest-of-class ranking is exactly where the raw
2038
- min-across-instances is the semantically correct quantity -- solver relative-
2039
- distance accuracy fell 59.2 -> 47.5 on real perceived codes and the VLM pilot
2040
- dropped in the same direction.
2041
-
2042
- REINSTATED (2026-07-25, second amendment, see preregistration.md) as the
2043
- table's PRINTED distance only, with the fix the first attempt lacked: closeness
2044
- ranks stay computed from the raw min-across-instances distance (the correct
2045
- closest-of-class quantity), and the solver's relative-distance answer reads the
2046
- rank field rather than comparing printed values. The printed value IS the solver's
2047
- absolute-distance answer, making abs-distance a pure lookup for any reader."""
2048
- return max(
2049
- _compact_class_distance(instances_a, instances_b),
2050
- _primary_instance_distance_floor(instances_a, instances_b),
2051
- )
2052
-
2053
-
2054
- def _compact_polygon_area(coordinates):
2055
- """Return the unsigned shoelace area of one ordered compact floor-boundary polygon."""
2056
- if len(coordinates) < 3:
2057
- return 0.0
2058
- return abs(
2059
- sum(
2060
- coordinates[index][0] * coordinates[(index + 1) % len(coordinates)][1]
2061
- - coordinates[(index + 1) % len(coordinates)][0] * coordinates[index][1]
2062
- for index in range(len(coordinates))
2063
- )
2064
- / 2
2065
- )
2066
-
2067
-
2068
- def _compact_room_floor_area(polygons):
2069
- """Sum outer areas and subtract every interior hole across compact's floor regions."""
2070
- area = 0.0
2071
- for polygon in polygons:
2072
- area += _compact_polygon_area(polygon.get("outer boundary coordinates", []))
2073
- area -= sum(
2074
- _compact_polygon_area(hole)
2075
- for hole in polygon.get("interior hole boundary coordinates", [])
2076
- )
2077
- return max(0.0, area)
2078
-
2079
-
2080
- def _compact_box_axis_bounds(box):
2081
- center = np.asarray(box["3D oriented bounding box center coordinates"], np.float64)
2082
- dimensions = np.asarray(box["3D oriented bounding box dimensions"], np.float64)
2083
- orientation = np.asarray(
2084
- box["3D oriented bounding box orientation unit vectors"], np.float64
2085
- )
2086
- orientation = orientation / np.linalg.norm(orientation, axis=1, keepdims=True)
2087
- offsets = []
2088
- for sx in (-1.0, 1.0):
2089
- for sy in (-1.0, 1.0):
2090
- for sz in (-1.0, 1.0):
2091
- offsets.append(
2092
- sx * dimensions[0] * orientation[0] / 2
2093
- + sy * dimensions[1] * orientation[1] / 2
2094
- + sz * dimensions[2] * orientation[2] / 2
2095
- )
2096
- corners = center + np.asarray(offsets)
2097
- return [
2098
- [
2099
- round(float(corners[:, axis].min()), 2),
2100
- round(float(corners[:, axis].max()), 2),
2101
- ]
2102
- for axis in range(3)
2103
- ]
2104
-
2105
-
2106
- def _compact_outline_for_v2(compact_code):
2107
- polygons = compact_code.get("room", {}).get("floor boundary polygons", [])
2108
- if not polygons:
2109
- return []
2110
- outline = []
2111
- for x, y in polygons[0].get("outer boundary coordinates", []):
2112
- outline.append(
2113
- {"floor_x_meters": round(float(x), 1), "floor_y_meters": round(float(y), 1)}
2114
- )
2115
- return outline
2116
-
2117
-
2118
- def _explicit_from_compact(compact_code):
2119
- """Derive a V2 explicit spatial code from an already-built compact spatial code.
2120
-
2121
- This is used for canonical adapter geometry and ground truth. It mirrors the V2 envelope
2122
- used by the raw encoder path: no embedded legend, numeric closest-class table, V2 room
2123
- keys, and compact "appearance order".
2124
- """
2125
- compact_objects = compact_code["objects"]
2126
-
2127
- objects = {}
2128
- first_visible = {}
2129
- for class_name, items in compact_objects.items():
2130
- rendered = []
2131
- for item in items:
2132
- box = item["3D oriented bounding box"]
2133
- center = box["3D oriented bounding box center coordinates"]
2134
- dimensions = box["3D oriented bounding box dimensions"]
2135
- bounds = _compact_box_axis_bounds(box)
2136
- rendered.append(
2137
- {
2138
- "position": {
2139
- "floor_x_meters": round(float(center[0]), 2),
2140
- "floor_y_meters": round(float(center[1]), 2),
2141
- "height_above_floor_meters": round(float(center[2]), 2),
2142
- },
2143
- "longest_dimension_meters": round(float(max(dimensions)), 2),
2144
- "bounding_box": {
2145
- "floor_x_meters": bounds[0],
2146
- "floor_y_meters": bounds[1],
2147
- "height_above_floor_meters": bounds[2],
2148
- },
2149
- "dimensions_meters": [
2150
- round(float(value), 2) for value in dimensions
2151
- ],
2152
- }
2153
- )
2154
- time = item["first visible time"]
2155
- if time is not None:
2156
- first_visible[class_name] = min(
2157
- first_visible.get(class_name, float("inf")), float(time)
2158
- )
2159
- objects[class_name] = {"count": len(items), "instances": rendered}
2160
-
2161
- classes = [name for name, items in compact_objects.items() if items]
2162
- raw_distances = {class_name: {} for class_name in classes}
2163
- printed_distances = {class_name: {} for class_name in classes}
2164
- for index, class_name in enumerate(classes):
2165
- for other in classes[index + 1 :]:
2166
- raw = _compact_class_distance(
2167
- compact_objects[class_name], compact_objects[other]
2168
- )
2169
- printed = _corrected_class_distance(
2170
- compact_objects[class_name], compact_objects[other]
2171
- )
2172
- raw_distances[class_name][other] = raw
2173
- raw_distances[other][class_name] = raw
2174
- printed_distances[class_name][other] = printed
2175
- printed_distances[other][class_name] = printed
2176
- closest = {}
2177
- for class_name, distances in raw_distances.items():
2178
- ranked = sorted(distances.items(), key=lambda item: (item[1], item[0]))
2179
- closest[class_name] = {
2180
- other: {
2181
- "closeness_rank": rank + 1,
2182
- "distance_meters": round(printed_distances[class_name][other], 2),
2183
- }
2184
- for rank, (other, _raw) in enumerate(ranked)
2185
- }
2186
-
2187
- floor_area = round(
2188
- _compact_room_floor_area(
2189
- compact_code["room"].get("floor boundary polygons", [])
2190
- ),
2191
- 1,
2192
- )
2193
-
2194
- return {
2195
- "objects": objects,
2196
- "room": {
2197
- "outline": _compact_outline_for_v2(compact_code),
2198
- "floor_area_square_meters": floor_area,
2199
- },
2200
- "closest_classes_from": closest,
2201
- "appearance order": sorted(
2202
- classes, key=lambda name: first_visible.get(name, float("inf"))
2203
- ),
2204
- }, floor_area
2205
-
2206
-
2207
- def _build_reference_v2_spatial_code(raw_inputs):
2208
- """Build the raw encoder spatial code exactly like the reference V2 branch."""
2209
- alias = {"coat hanger": "coat rack"}
2210
- per = {
2211
- alias.get(class_name, class_name): frames
2212
- for class_name, frames in raw_inputs["per"].items()
2213
- }
2214
- depth = raw_inputs["depth"]
2215
- intr = raw_inputs["intr"]
2216
- c2w = raw_inputs["c2w"]
2217
- conf = raw_inputs.get("conf")
2218
- frame_times = raw_inputs["ftimes"]
2219
-
2220
- up_vec, up_axis = room_gravity(depth, intr, c2w, conf)
2221
- instances, stats = build_instances(
2222
- per, depth, intr, c2w, conf, frame_times, up_axis=up_axis
2223
- )
2224
- u, v, g = _floor_basis(up_vec)
2225
- all_points = np.concatenate(
2226
- [item["pts"] for values in instances.values() for item in values], axis=0
2227
- )
2228
- floor_level = float(np.percentile(all_points @ g, 2))
2229
- floor_area = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
2230
- code = _reference_to_spatial_code(
2231
- instances, stats, floor_area, up_axis, up_vec, floor_level
2232
- )
2233
- classes = list(instances.keys())
2234
- class_first = {
2235
- class_name: min(item["first_time"] for item in values)
2236
- for class_name, values in instances.items()
2237
- }
2238
-
2239
- for class_name in classes:
2240
- ranked = sorted(
2241
- instances[class_name],
2242
- key=lambda item: (item["n"], item.get("nframes", 0)),
2243
- reverse=True,
2244
- )
2245
- for record, item in zip(code["objects"][class_name]["instances"], ranked):
2246
- record["seen_in_video_frames"] = int(
2247
- item.get("nframes", len(item.get("frames", ())))
2248
- )
2249
-
2250
- closest = {}
2251
- for class_name in classes:
2252
- distances = sorted(
2253
- (
2254
- round(
2255
- answer_closest_distance(instances[class_name], instances[other]), 2
2256
- ),
2257
- other,
2258
- )
2259
- for other in classes
2260
- if other != class_name
2261
- )
2262
- closest[class_name] = {
2263
- other: {"closeness_rank": rank + 1, "distance_meters": distance}
2264
- for rank, (distance, other) in enumerate(distances)
2265
- }
2266
- code["closest_classes_from"] = closest
2267
-
2268
- waypoints = []
2269
- next_time = 0.0
2270
- for index, time_seconds in enumerate(np.asarray(frame_times, np.float64)):
2271
- if time_seconds + 1e-9 < next_time:
2272
- continue
2273
- next_time = float(time_seconds) + 5.0
2274
- position = c2w[index][:3, 3]
2275
- forward = c2w[index][:3, 2]
2276
- waypoints.append(
2277
- {
2278
- "time_seconds": round(float(time_seconds), 1),
2279
- "floor_x_meters": round(float(position @ u), 2),
2280
- "floor_y_meters": round(float(position @ v), 2),
2281
- "heading_degrees": round(
2282
- float(np.degrees(np.arctan2(forward @ v, forward @ u)))
2283
- ),
2284
- }
2285
- )
2286
- code["camera_trajectory"] = {
2287
- "sample_interval_seconds": 5,
2288
- "waypoints": waypoints,
2289
- }
2290
- code["room"] = {
2291
- "outline": _room_outline(depth, intr, c2w, conf, u, v),
2292
- "floor_area_square_meters": code["room"]["floor_area_square_meters"],
2293
- }
2294
- code["appearance order"] = [
2295
- class_name
2296
- for class_name, _time in sorted(class_first.items(), key=lambda item: item[1])
2297
- ]
2298
- return code, instances, stats, up_axis, up_vec, floor_area
2299
-
2300
-
2301
- def build_explicit_spatial_code(scene):
2302
- """Build the selected explicit code.
2303
-
2304
- Raw encoder inputs follow the original geometric V2 spatial-code construction. Canonical
2305
- geometry keeps the compact-derived schema used by ground-truth and non-raw adapters.
2306
- """
2307
- raw_inputs = scene.get("raw_inputs")
2308
- if raw_inputs is not None:
2309
- return _build_reference_v2_spatial_code(raw_inputs)
2310
-
2311
- compact_code, instances, stats, up_ax, up_vec, _ = build_compact_spatial_code(scene)
2312
- code, floor_area = _explicit_from_compact(compact_code)
2313
- return code, instances, stats, up_ax, up_vec, floor_area
2314
-
2315
-
2316
- # ==========================================================================================
2317
- # MODEL-AGNOSTIC ENTRY POINT
2318
- # ==========================================================================================
2319
-
2320
-
2321
- def build_spatial_code(scene, spatial_code_format="explicit"):
2322
- """Build one selected spatial-code schema from canonical scene geometry.
2323
-
2324
- Compact is built directly from raw depth/pose/mask bundles or canonical world-space
2325
- geometry (build_compact_spatial_code() handles that duality). Explicit is always a
2326
- derivation of compact (build_explicit_spatial_code() calls build_compact_spatial_code()
2327
- first), so there is no separate raw/canonical branch for explicit any more.
2328
- """
2329
- if spatial_code_format == "compact":
2330
- return build_compact_spatial_code(scene)
2331
- if spatial_code_format != "explicit":
2332
- raise ValueError(f"unknown spatial-code format {spatial_code_format!r}")
2333
- return build_explicit_spatial_code(scene)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/__init__.py DELETED
@@ -1 +0,0 @@
1
- """Spatial-code encoder package."""
 
 
encoder/adapters.py DELETED
@@ -1,586 +0,0 @@
1
- """Model-output adapters -- the ONLY file that knows any model's native output shape.
2
-
3
- Every adapter returns THE canonical geometry dict below. geometric.py sees only this dict:
4
-
5
- instances: class -> list of already-reconstructed 3D instance dicts
6
- stats: class -> raw/merged/peak counts
7
- scene_pts: full-scene world points used by gravity/floor-area math
8
- cameras: world-space camera positions (only to orient gravity upward)
9
- raw_inputs: optional raw depth/pose/mask bundle for exact reference-math execution
10
-
11
- Adapters may decode depth, masks, queries, meshes, voxels, Gaussians, or anything else. None
12
- of those representations cross this file boundary.
13
- """
14
-
15
- from __future__ import annotations
16
-
17
- import gzip
18
- import os
19
- import pickle
20
- import sys
21
-
22
- import numpy as np
23
-
24
- CACHE_ROOT = os.environ.get("VSI_CACHE_ROOT", "/root/data/caches")
25
- FPS = float(os.environ.get("VSI_FPS", "6"))
26
- MODELS_ROOT = os.environ.get("VSI_MODELS_ROOT", "/root/models")
27
- DA3_ROOT = os.environ.get("VSI_DA3_ROOT", os.path.join(MODELS_ROOT, "depth-anything-3"))
28
- SEGVGGT_ROOT = os.environ.get("VSI_SEGVGGT_ROOT", os.path.join(MODELS_ROOT, "SegVGGT"))
29
-
30
-
31
- RAW_CACHE_ROOT = CACHE_ROOT
32
- SPATIAL_CODE_FORMATS = ("compact", "explicit")
33
-
34
-
35
- def _raw_cache_root(root=None):
36
- """Resolve the shared inference-output root without importing encoder config."""
37
- return root or os.environ.get("VSI_CACHE_ROOT", RAW_CACHE_ROOT)
38
-
39
-
40
- def validate_spatial_code_format(spatial_code_format):
41
- """Validate one output format at the model-agnostic geometry boundary."""
42
- if spatial_code_format not in SPATIAL_CODE_FORMATS:
43
- raise ValueError(
44
- f"unknown spatial-code format {spatial_code_format!r}; "
45
- f"expected {SPATIAL_CODE_FORMATS}"
46
- )
47
- return spatial_code_format
48
-
49
-
50
- # ==========================================================================================
51
- # CANONICAL SHAPE -- validation only. Plain dicts on purpose: no schema/contract class layer.
52
- # ==========================================================================================
53
-
54
-
55
- def _pts(x, where):
56
- p = np.asarray(x, np.float32)
57
- if p.ndim != 2 or p.shape[1] != 3:
58
- raise ValueError(f"{where} must be [N,3], got {p.shape}")
59
- return p[np.isfinite(p).all(1)]
60
-
61
-
62
- class EmptySceneError(ValueError):
63
- """Raised when a valid adapter result contains no spatial instances."""
64
-
65
-
66
- def validate(scene):
67
- """Coerces one adapter result to THE canonical shape and fails loudly on drift."""
68
- if not isinstance(scene, dict):
69
- raise TypeError("adapter result must be a dict")
70
- if not scene.get("instances"):
71
- raise EmptySceneError("adapter produced no instances")
72
- for cls, insts in scene["instances"].items():
73
- for i in insts:
74
- i["pts"] = _pts(i["pts"], f"{cls}.pts")
75
- i["best_pts"] = _pts(i.get("best_pts", i["pts"]), f"{cls}.best_pts")
76
- i["n"] = int(i.get("n", len(i["pts"])))
77
- i["frames"] = set(i.get("frames", ()))
78
- i["nframes"] = int(i.get("nframes", len(i["frames"])))
79
- i["first_time"] = float(i.get("first_time", 0.0))
80
- if i.get("conf") is not None:
81
- i["conf"] = np.asarray(i["conf"], np.float32).reshape(-1)
82
- scene["scene_pts"] = _pts(scene["scene_pts"], "scene_pts")
83
- if scene.get("cameras") is not None:
84
- scene["cameras"] = _pts(scene["cameras"], "cameras")
85
- return scene
86
-
87
-
88
- # ==========================================================================================
89
- # DA3 + SAM3 -- compatibility adapter for the existing cache. All depth/mask projection lives
90
- # HERE, not geometric.py. The geometric cleanup/measurement math is unchanged downstream.
91
- # ==========================================================================================
92
-
93
-
94
- def _load_masks(path):
95
- candidates = [path]
96
- if os.path.isdir(path):
97
- candidates = [
98
- os.path.join(path, n)
99
- for n in ("sam3.pkl.gz", "sam3_full.pkl.gz", "sam3.pkl")
100
- ]
101
- for path in candidates:
102
- if not os.path.exists(path):
103
- continue
104
- op = gzip.open if path.endswith(".gz") else open
105
- with op(path, "rb") as f:
106
- packed = pickle.load(f)
107
- out = {}
108
- for cls, frames in packed.items():
109
- out[cls] = {}
110
- for fi, objects in frames.items():
111
- out[cls][int(fi)] = {}
112
- for oid, value in objects.items():
113
- if isinstance(value, tuple) and len(value) == 2:
114
- bits, shape = value
115
- m = (
116
- np.unpackbits(bits)[: int(np.prod(shape))]
117
- .reshape(shape)
118
- .astype(bool)
119
- )
120
- else:
121
- m = np.asarray(value, bool)
122
- out[cls][int(fi)][int(oid)] = m
123
- return out
124
- raise FileNotFoundError(f"no SAM3 cache found at {path}")
125
-
126
-
127
- def _sam3_response_masks(response, frame_index, allow_empty):
128
- """Normalize one tracked or independent SAM3 response to object-id masks."""
129
- if not isinstance(response, dict):
130
- raise ValueError(
131
- f"invalid SAM3 response at frame {frame_index}; expected a dict"
132
- )
133
- outputs = (
134
- response.get("outputs")
135
- if isinstance(response.get("outputs"), dict)
136
- else response
137
- )
138
- masks = outputs.get("masks")
139
- if masks is None:
140
- masks = outputs.get("out_binary_masks")
141
- if masks is None:
142
- if allow_empty and not outputs:
143
- return {}
144
- raise ValueError(f"SAM3 response at frame {frame_index} has no masks")
145
- masks = (
146
- masks.detach().cpu().numpy() if hasattr(masks, "detach") else np.asarray(masks)
147
- )
148
- if masks.ndim == 2:
149
- masks = masks[None]
150
- if masks.ndim == 4 and masks.shape[1] == 1:
151
- masks = masks[:, 0]
152
- if masks.ndim != 3:
153
- raise ValueError(
154
- f"SAM3 masks at frame {frame_index} must be [N,H,W], got {masks.shape}"
155
- )
156
- object_ids = outputs.get("out_obj_ids")
157
- if object_ids is None:
158
- object_ids = range(len(masks))
159
- elif hasattr(object_ids, "detach"):
160
- object_ids = object_ids.detach().cpu().numpy()
161
- return {
162
- int(object_id): mask.astype(bool) for object_id, mask in zip(object_ids, masks)
163
- }
164
-
165
-
166
- def _load_native_sam3(path):
167
- """Decode tracked or independent native SAM3 frame responses."""
168
- try:
169
- import torch
170
- except ImportError as exc:
171
- raise RuntimeError("PyTorch is required to read a raw SAM3 .pt cache") from exc
172
- responses = torch.load(path, map_location="cpu", weights_only=False)
173
- if isinstance(responses, dict):
174
- decoded = {}
175
- for class_name, class_responses in responses.items():
176
- if isinstance(class_responses, dict) and "stream" in class_responses:
177
- # Lossless tracking caches retain complete request responses and
178
- # streamed envelopes. Only the stream is needed for geometry.
179
- stream = class_responses["stream"]
180
- if not isinstance(stream, list):
181
- raise ValueError(
182
- f"invalid SAM3 stream for {class_name!r}; expected a list"
183
- )
184
- decoded[str(class_name)] = {
185
- int(response["frame_index"]): _sam3_response_masks(
186
- response, int(response["frame_index"]), True
187
- )
188
- for response in stream
189
- if isinstance(response, dict)
190
- and response.get("frame_index") is not None
191
- }
192
- continue
193
- if not isinstance(class_responses, list):
194
- raise ValueError(
195
- f"invalid SAM3 responses for {class_name!r}; expected a list"
196
- )
197
- decoded[str(class_name)] = {
198
- frame_index: _sam3_response_masks(response, frame_index, True)
199
- for frame_index, response in enumerate(class_responses)
200
- }
201
- return decoded
202
- if not isinstance(responses, list):
203
- raise ValueError(f"invalid SAM3 raw cache {path}; expected a list or dict")
204
- class_name = os.environ.get("VSI_SAM3_PROMPT", "object")
205
- return {
206
- class_name: {
207
- frame_index: _sam3_response_masks(response, frame_index, False)
208
- for frame_index, response in enumerate(responses)
209
- }
210
- }
211
-
212
-
213
- def _load_native_da3(path):
214
- """Decode DA3's exact pickled Prediction object into projection inputs."""
215
- model_root = str(DA3_ROOT)
216
- source_root = os.path.join(model_root, "src")
217
- if source_root not in sys.path:
218
- sys.path.insert(0, source_root)
219
- with open(path, "rb") as stream:
220
- prediction = pickle.load(stream)
221
-
222
- def field(name, required=True):
223
- value = getattr(prediction, name, None)
224
- if value is None and isinstance(prediction, dict):
225
- value = prediction.get(name)
226
- if required and value is None:
227
- raise ValueError(f"DA3 Prediction in {path} has no {name}")
228
- return value
229
-
230
- depth = np.asarray(field("depth"), np.float32)
231
- intr = np.asarray(field("intrinsics"), np.float32)
232
- extr = np.asarray(field("extrinsics"), np.float32)
233
- if extr.shape[-2:] == (3, 4):
234
- homogeneous = np.broadcast_to(
235
- np.eye(4, dtype=np.float32), extr.shape[:-2] + (4, 4)
236
- ).copy()
237
- homogeneous[..., :3, :] = extr
238
- extr = homogeneous
239
- if extr.shape[-2:] != (4, 4):
240
- raise ValueError(f"DA3 extrinsics must end in [3,4] or [4,4], got {extr.shape}")
241
- c2w = np.linalg.inv(extr).astype(np.float32)
242
- conf_value = field("conf", required=False)
243
- conf = np.asarray(conf_value, np.float32) if conf_value is not None else None
244
- return depth, intr, c2w, conf
245
-
246
-
247
- def _resize_mask_nearest(mask, shape):
248
- """Resize one boolean mask to a depth-map shape with nearest sampling."""
249
- mask = np.asarray(mask, bool)
250
- if mask.ndim != 2:
251
- raise ValueError(f"mask must be two-dimensional, got {mask.shape}")
252
- if mask.shape == tuple(shape):
253
- return mask
254
- source_height, source_width = mask.shape
255
- target_height, target_width = shape
256
- rows = np.minimum(
257
- np.arange(target_height) * source_height // target_height,
258
- source_height - 1,
259
- )
260
- columns = np.minimum(
261
- np.arange(target_width) * source_width // target_width,
262
- source_width - 1,
263
- )
264
- return mask[np.ix_(rows, columns)]
265
-
266
-
267
- def _backproject(depth, intrinsics, c2w, mask, conf=None):
268
- mask = _resize_mask_nearest(mask, depth.shape)
269
- ys, xs = np.nonzero(mask)
270
- z = depth[ys, xs]
271
- ok = np.isfinite(z) & (z > 0)
272
- ys, xs, z = ys[ok], xs[ok], z[ok]
273
- if not len(z):
274
- return np.zeros((0, 3), np.float32), None
275
- camera_points = np.stack(
276
- [
277
- (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
278
- (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
279
- z,
280
- ],
281
- 1,
282
- )
283
- world_points = (c2w[:3, :3] @ camera_points.T).T + c2w[:3, 3]
284
- cf = conf[ys, xs].astype(np.float32) if conf is not None else None
285
- return world_points.astype(np.float32), cf
286
-
287
-
288
- def _fusion_cache_paths(root, da3_path, sam3_path, scene):
289
- if scene:
290
- root = _raw_cache_root(root)
291
- da3_path = da3_path or os.path.join(root, "depth-anything-3", f"{scene}.pkl")
292
- sam3_path = sam3_path or os.path.join(root, "sam3", f"{scene}.pt")
293
- if da3_path is None:
294
- da3_path = os.path.join(root, "da3.npz") if root else None
295
- if sam3_path is None:
296
- sam3_path = root
297
- if not da3_path:
298
- raise ValueError("da3_path is required")
299
- return da3_path, sam3_path
300
-
301
-
302
- def _load_fusion_inputs(da3_path, sam3_path):
303
- if str(da3_path).endswith(".pkl"):
304
- depth, intr, c2w, conf = _load_native_da3(da3_path)
305
- ft = np.arange(len(depth), dtype=np.float32) / FPS
306
- else:
307
- d = np.load(da3_path)
308
- depth, intr, c2w = d["depth"], d["intr"], d["c2w"]
309
- conf = d["conf"] if "conf" in d and d["conf"].size else None
310
- ft = (
311
- d["frame_times"]
312
- if "frame_times" in d
313
- else np.arange(len(depth), dtype=np.float32)
314
- )
315
- per = (
316
- _load_native_sam3(sam3_path)
317
- if str(sam3_path).endswith(".pt")
318
- else _load_masks(sam3_path)
319
- )
320
- return depth, intr, c2w, conf, ft, per
321
-
322
-
323
- def _fuse_mask_instances(per, depth, intr, c2w, conf, frame_times):
324
- instances, stats = {}, {}
325
- for cls, frames in per.items():
326
- by_id = {}
327
- peak = max((len(v) for v in frames.values()), default=0)
328
- for fi, objects in frames.items():
329
- for oid, mask in objects.items():
330
- pts, cf = _backproject(
331
- depth[fi],
332
- intr[fi],
333
- c2w[fi],
334
- mask,
335
- conf[fi] if conf is not None else None,
336
- )
337
- if not len(pts):
338
- continue
339
- r = by_id.setdefault(
340
- oid,
341
- {
342
- "chunks": [],
343
- "conf": [],
344
- "frames": set(),
345
- "first_time": float(frame_times[fi]),
346
- },
347
- )
348
- r["chunks"].append(pts)
349
- r["frames"].add(fi)
350
- if cf is not None:
351
- r["conf"].append(cf)
352
- raw = []
353
- for r in by_id.values():
354
- pts = np.concatenate(r["chunks"], 0)
355
- raw.append(
356
- {
357
- "pts": pts,
358
- "best_pts": max(r["chunks"], key=len),
359
- "observations": list(r["chunks"]),
360
- "conf": np.concatenate(r["conf"], 0) if r["conf"] else None,
361
- "frames": r["frames"],
362
- "nframes": len(r["frames"]),
363
- "n": len(pts),
364
- "first_time": r["first_time"],
365
- }
366
- )
367
- if raw:
368
- instances[cls] = raw
369
- stats[cls] = {"raw": len(raw), "merged": len(raw), "peak": peak}
370
- return instances, stats
371
-
372
-
373
- def _sample_scene_points(depth, intr, c2w):
374
- scene_points = []
375
- for fi in range(0, len(depth), 3):
376
- m = np.zeros_like(depth[fi], bool)
377
- m[::8, ::8] = True
378
- pts, _ = _backproject(depth[fi], intr[fi], c2w[fi], m)
379
- if len(pts):
380
- scene_points.append(pts)
381
- return np.concatenate(scene_points, 0)
382
-
383
-
384
- def adapt_sam3_depth_anything_3(
385
- root=None, da3_path=None, sam3_path=None, scene=None, **_
386
- ):
387
- """Fuse raw DA3 geometry and raw per-frame SAM3 masks into canonical geometry."""
388
- da3_path, sam3_path = _fusion_cache_paths(root, da3_path, sam3_path, scene)
389
- depth, intr, c2w, conf, frame_times, per = _load_fusion_inputs(da3_path, sam3_path)
390
- instances, stats = _fuse_mask_instances(per, depth, intr, c2w, conf, frame_times)
391
- return validate(
392
- {
393
- "instances": instances,
394
- "stats": stats,
395
- "scene_pts": _sample_scene_points(depth, intr, c2w),
396
- "cameras": c2w[:, :3, 3],
397
- "raw_inputs": {
398
- "depth": depth,
399
- "intr": intr,
400
- "c2w": c2w,
401
- "conf": conf,
402
- "ftimes": frame_times,
403
- "per": per,
404
- },
405
- }
406
- )
407
-
408
-
409
- # ==========================================================================================
410
- # SegVGGT -- reads one deliberately boring NPZ export and groups already-world-space
411
- # points by instance mask. Model inference is intentionally outside the encoder package.
412
- # ==========================================================================================
413
-
414
-
415
- SEGVGGT_CLASSES = """wall|floor|chair|table|door|couch|cabinet|shelf|desk|office chair|bed|pillow|sink|picture|window|toilet|bookshelf|monitor|curtain|book|armchair|coffee table|box|refrigerator|lamp|kitchen cabinet|towel|clothes|tv|nightstand|counter|dresser|stool|cushion|plant|ceiling|bathtub|end table|dining table|keyboard|bag|backpack|toilet paper|printer|tv stand|whiteboard|blanket|shower curtain|trash can|closet|stairs|microwave|stove|shoe|computer tower|bottle|bin|ottoman|bench|board|washing machine|mirror|copier|basket|sofa chair|file cabinet|fan|laptop|shower|paper|person|paper towel dispenser|oven|blinds|rack|plate|blackboard|piano|suitcase|rail|radiator|recycling bin|container|wardrobe|soap dispenser|telephone""".split(
416
- "|"
417
- )
418
-
419
-
420
- def _decode_segvggt_raw(path):
421
- """Decode the official SegVGGT.forward tensor dictionary for this adapter."""
422
- import sys
423
-
424
- try:
425
- import torch
426
- import torch.nn.functional as functional
427
- except ImportError as exc:
428
- raise RuntimeError("PyTorch is required to read a SegVGGT .pt cache") from exc
429
-
430
- model_root = str(SEGVGGT_ROOT)
431
- if model_root not in sys.path:
432
- sys.path.insert(0, model_root)
433
- try:
434
- from eval.instance_eval_common import predict_by_feat_instance
435
- from segvggt.utils.pose_enc import pose_encoding_to_extri_intri
436
- except ImportError as exc:
437
- raise RuntimeError(
438
- "SegVGGT is required to decode its native prediction dictionary"
439
- ) from exc
440
-
441
- raw = torch.load(path, map_location="cpu", weights_only=False)
442
- required = {"world_points", "instance_maps", "instance_labels", "pose_enc"}
443
- if not isinstance(raw, dict) or not required.issubset(raw):
444
- missing = (
445
- sorted(required - set(raw)) if isinstance(raw, dict) else sorted(required)
446
- )
447
- raise ValueError(f"invalid SegVGGT raw cache {path}; missing keys: {missing}")
448
-
449
- logits = raw["instance_maps"][0]
450
- query_count, frame_total, height, width = logits.shape
451
- masks, label_ids, _ = predict_by_feat_instance(
452
- raw["instance_labels"][0],
453
- logits.reshape(query_count, -1),
454
- mask_thr=float(os.environ.get("VSI_MASK_THR", "0.4")),
455
- npoint_thr=1,
456
- )
457
- masks = masks.reshape(-1, frame_total, height, width).cpu().numpy()
458
- label_ids = label_ids.cpu().numpy()
459
- keep = [index for index, label in enumerate(label_ids) if int(label) >= 2]
460
-
461
- world = raw["world_points"][0].float()
462
- if tuple(world.shape[1:3]) != (height, width):
463
- world = functional.interpolate(
464
- world.permute(0, 3, 1, 2),
465
- (height, width),
466
- mode="nearest",
467
- ).permute(0, 2, 3, 1)
468
- world = world.cpu().numpy()
469
-
470
- if "images" in raw:
471
- image_size = raw["images"].shape[-2:]
472
- elif "depth" in raw:
473
- image_size = raw["depth"].shape[2:4]
474
- else:
475
- image_size = (height, width)
476
- extrinsics, _ = pose_encoding_to_extri_intri(raw["pose_enc"].float(), image_size)
477
- extrinsics = extrinsics[0].cpu().numpy()
478
- rotations = extrinsics[:, :3, :3]
479
- translations = extrinsics[:, :3, 3]
480
- cameras = -np.einsum("sji,sj->si", rotations, translations)
481
- labels = np.asarray(
482
- [
483
- (
484
- SEGVGGT_CLASSES[int(label_ids[index])]
485
- if int(label_ids[index]) < len(SEGVGGT_CLASSES)
486
- else f"class {int(label_ids[index])}"
487
- )
488
- for index in keep
489
- ],
490
- dtype=object,
491
- )
492
- return {
493
- "world_points": world,
494
- "instance_masks": masks[keep].astype(bool),
495
- "labels": labels,
496
- "camera_positions": cameras.astype(np.float32),
497
- }
498
-
499
-
500
- def adapt_segvggt(root=None, path=None, scene=None, **_):
501
- """Translate a raw-preserving SegVGGT cache to canonical geometry."""
502
- if path is None and scene:
503
- root = _raw_cache_root(root)
504
- path = os.path.join(root, "segvggt", f"{scene}.pt")
505
- else:
506
- path = path or root
507
- if path is None:
508
- raise ValueError("SegVGGT cache path is required")
509
- if os.path.isdir(path):
510
- path = os.path.join(path, f"{scene}.pt" if scene else "geometry.pt")
511
- if not os.path.exists(path):
512
- raise FileNotFoundError(f"SegVGGT raw cache does not exist: {path}")
513
- if str(path).endswith(".pt"):
514
- d = _decode_segvggt_raw(path)
515
- else:
516
- d = np.load(path, allow_pickle=True)
517
- world, masks = (
518
- np.asarray(d["world_points"], np.float32),
519
- np.asarray(d["instance_masks"], bool),
520
- )
521
- labels = [str(x) for x in d["labels"].tolist()]
522
- ft = (
523
- d["frame_times"]
524
- if "frame_times" in d
525
- else np.arange(world.shape[0], dtype=np.float32)
526
- )
527
- instances = {}
528
- for cls, mask in zip(labels, masks):
529
- fs = np.flatnonzero(mask.reshape(mask.shape[0], -1).any(1))
530
- chunks = [world[f][mask[f]] for f in fs if mask[f].any()]
531
- chunks = [p[np.isfinite(p).all(1)] for p in chunks if len(p)]
532
- if not chunks:
533
- continue
534
- pts = np.concatenate(chunks, 0)
535
- instances.setdefault(cls, []).append(
536
- {
537
- "pts": pts,
538
- "best_pts": max(chunks, key=len),
539
- "observations": list(chunks),
540
- "conf": None,
541
- "frames": set(map(int, fs)),
542
- "nframes": len(fs),
543
- "n": len(pts),
544
- "first_time": float(ft[fs[0]]) if len(fs) else 0.0,
545
- }
546
- )
547
- stats = {}
548
- for cls, insts in instances.items():
549
- n = {}
550
- for i in insts:
551
- for f in i["frames"]:
552
- n[f] = n.get(f, 0) + 1
553
- stats[cls] = {
554
- "raw": len(insts),
555
- "merged": len(insts),
556
- "peak": max(n.values(), default=len(insts)),
557
- }
558
- return validate(
559
- {
560
- "instances": instances,
561
- "stats": stats,
562
- "scene_pts": world.reshape(-1, 3),
563
- "cameras": d["camera_positions"] if "camera_positions" in d else None,
564
- }
565
- )
566
-
567
-
568
- RAW_ADAPTERS = {
569
- "sam3+depth-anything-3": adapt_sam3_depth_anything_3,
570
- "segvggt": adapt_segvggt,
571
- }
572
-
573
-
574
- def available_models():
575
- """Return raw model formats supported by the encoder."""
576
- return tuple(sorted(RAW_ADAPTERS))
577
-
578
-
579
- def adapt(model, **raw_cache):
580
- """Dispatch one model's native cache to its isolated format adapter."""
581
- adapter = RAW_ADAPTERS.get(model)
582
- if adapter is None:
583
- raise KeyError(
584
- f"no raw encoder adapter for {model!r}; expected one of {available_models()}"
585
- )
586
- return validate(adapter(**raw_cache))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/config.py DELETED
@@ -1,166 +0,0 @@
1
- """Configuration and path helpers for the VSI spatial-code encoder."""
2
-
3
- from __future__ import annotations
4
-
5
- import os
6
- from pathlib import Path
7
-
8
- MODEL = "sam3+depth-anything-3"
9
- FRAMES_PER_VIDEO = int(os.environ.get("VSI_FRAMES_PER_VIDEO", "32"))
10
- FPS = float(os.environ.get("VSI_FPS", "6"))
11
-
12
- WORKSPACE_ROOT = Path(
13
- os.environ.get("VSI_WORKSPACE_ROOT", Path(__file__).resolve().parent.parent)
14
- ).resolve()
15
- DATA_ROOT = Path(os.environ.get("VSI_DATA_ROOT", "/root/data"))
16
- VSI_ROOT = Path(os.environ.get("VSI_ROOT", DATA_ROOT / "VSI-Bench"))
17
- JSONL = Path(os.environ.get("VSI_JSONL", VSI_ROOT / "test.jsonl"))
18
- CACHE_ROOT = Path(os.environ.get("VSI_CACHE_ROOT", DATA_ROOT / "caches"))
19
- CODES_ROOT = Path(
20
- os.environ.get("VSI_CODES", WORKSPACE_ROOT / "data" / "spatial codes")
21
- )
22
- VIDEO_DATASETS = ("scannet", "scannetpp", "arkitscenes")
23
- DEPTH_VARIANTS = ("relative", "metric")
24
- INPUT_SELECTIONS = ("uniform", "selective")
25
- VIDEO_INPUT_SELECTION = "video"
26
- VIDEO_FRAME_SELECTION = "uniform"
27
- VIDEO_CACHE_SEGMENT = "video"
28
- TRACKING_MODES = ("tracking", "no tracking")
29
- SPATIAL_CODE_FORMATS = ("compact", "explicit")
30
-
31
-
32
- def _validate_dimensions(
33
- depth, input_selection, tracking, frame_count, allow_video=False
34
- ):
35
- """Validate the dimensions shared by cache and spatial-code paths."""
36
- if depth not in DEPTH_VARIANTS:
37
- raise ValueError(f"unknown depth variant {depth!r}; expected {DEPTH_VARIANTS}")
38
- selections = INPUT_SELECTIONS + ((VIDEO_INPUT_SELECTION,) if allow_video else ())
39
- if input_selection not in selections:
40
- raise ValueError(
41
- f"unknown input selection {input_selection!r}; expected {selections}"
42
- )
43
- if tracking not in TRACKING_MODES:
44
- raise ValueError(
45
- f"unknown tracking mode {tracking!r}; expected {TRACKING_MODES}"
46
- )
47
- if input_selection != VIDEO_INPUT_SELECTION and (
48
- frame_count is None or frame_count < 1
49
- ):
50
- raise ValueError("frame count must be positive")
51
-
52
-
53
- def _combined_directory(
54
- root, depth, input_selection, tracking, frame_count, allow_video=False
55
- ):
56
- """Build the combined hierarchy: tracking/{frames/<selection>|video}."""
57
- _validate_dimensions(depth, input_selection, tracking, frame_count, allow_video)
58
- directory = Path(root) / tracking
59
- if input_selection == VIDEO_INPUT_SELECTION:
60
- return directory / VIDEO_CACHE_SEGMENT
61
- return directory / "frames" / input_selection / str(frame_count)
62
-
63
-
64
- def video_path(scene, dataset=None):
65
- """Return the unique MP4 for ``scene`` from the VSI-Bench dataset folders."""
66
- scene = str(scene)
67
- datasets = (dataset,) if dataset else VIDEO_DATASETS
68
- matches = []
69
- for name in datasets:
70
- if name not in VIDEO_DATASETS:
71
- raise ValueError(
72
- f"unknown VSI dataset {name!r}; expected one of {VIDEO_DATASETS}"
73
- )
74
- candidate = VSI_ROOT / name / f"{scene}.mp4"
75
- if candidate.is_file():
76
- matches.append(candidate)
77
- if not matches:
78
- searched = ", ".join(str(VSI_ROOT / d / f"{scene}.mp4") for d in datasets)
79
- raise FileNotFoundError(
80
- f"video for scene {scene!r} not found; searched: {searched}"
81
- )
82
- if len(matches) > 1:
83
- raise RuntimeError(f"scene {scene!r} exists in multiple datasets: {matches}")
84
- return str(matches[0])
85
-
86
-
87
- def cache_file(scene, depth, input_selection, tracking, frame_count=FRAMES_PER_VIDEO):
88
- """Return one combined geometry cache isolated by every input dimension."""
89
- directory = _combined_directory(
90
- CACHE_ROOT / MODEL,
91
- depth,
92
- input_selection,
93
- tracking,
94
- frame_count,
95
- allow_video=True,
96
- )
97
- return str(directory / f"{scene}.pkl.gz")
98
-
99
-
100
- def da3_cache_file(scene, depth, input_selection, frame_count=FRAMES_PER_VIDEO):
101
- """Return one native DA3 cache path; tracking never applies to DA3."""
102
- _validate_dimensions(depth, input_selection, "tracking", frame_count)
103
- directory = CACHE_ROOT / "depth-anything-3" / depth / "frames" / input_selection
104
- return str(directory / str(frame_count) / f"{scene}.pkl")
105
-
106
-
107
- def sam3_cache_file(scene, input_selection, tracking, frame_count=FRAMES_PER_VIDEO):
108
- """Return one native SAM3 cache path for a specific set of input dimensions."""
109
- _validate_dimensions("relative", input_selection, tracking, frame_count)
110
- directory = CACHE_ROOT / "sam3" / tracking / "frames" / input_selection
111
- return str(directory / str(frame_count) / f"{scene}.pt")
112
-
113
-
114
- def video_da3_cache_file(scene, depth="metric", input_selection=VIDEO_FRAME_SELECTION):
115
- """Return the DA3 full-video cache for the encoder's video layout."""
116
- _validate_dimensions(depth, input_selection, "tracking", FRAMES_PER_VIDEO)
117
- directory = CACHE_ROOT / "depth-anything-3" / depth / VIDEO_CACHE_SEGMENT
118
- return str(directory / f"{scene}.npz")
119
-
120
-
121
- def video_sam3_cache_file(
122
- scene, tracking="no tracking", input_selection=VIDEO_FRAME_SELECTION
123
- ):
124
- """Return the SAM3 full-video cache for the encoder's video layout."""
125
- _validate_dimensions("relative", input_selection, tracking, FRAMES_PER_VIDEO)
126
- directory = CACHE_ROOT / "sam3" / tracking / VIDEO_CACHE_SEGMENT
127
- return str(directory / f"{scene}.pkl.gz")
128
-
129
-
130
- def spatial_code_model_dir(
131
- depth,
132
- input_selection,
133
- tracking,
134
- frame_count=FRAMES_PER_VIDEO,
135
- spatial_code_format="explicit",
136
- ):
137
- """Return one final spatial-code directory for a specific set of input dimensions."""
138
- if spatial_code_format not in SPATIAL_CODE_FORMATS:
139
- raise ValueError(
140
- f"unknown spatial-code format {spatial_code_format!r}; "
141
- f"expected {SPATIAL_CODE_FORMATS}"
142
- )
143
- directory = _combined_directory(
144
- CODES_ROOT / MODEL,
145
- depth,
146
- input_selection,
147
- tracking,
148
- frame_count,
149
- allow_video=True,
150
- )
151
- return str(directory / spatial_code_format)
152
-
153
-
154
- def spatial_code_path(
155
- scene,
156
- depth,
157
- input_selection,
158
- tracking,
159
- frame_count=FRAMES_PER_VIDEO,
160
- spatial_code_format="explicit",
161
- ):
162
- """Return the final spatial-code JSON path for one scene."""
163
- directory = spatial_code_model_dir(
164
- depth, input_selection, tracking, frame_count, spatial_code_format
165
- )
166
- return str(Path(directory) / f"{scene}.json")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/geometric.py DELETED
@@ -1,2333 +0,0 @@
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 feed build_compact_spatial_code() (see its own docstring for how it handles
9
- that duality). The explicit schema is no longer built independently: it is a strict derivation
10
- of the compact schema (build_explicit_spatial_code() calls build_compact_spatial_code() first,
11
- then reads every explicit value directly off compact's own oriented boxes and floor polygons --
12
- positions/dimensions/counts/appearance-order are direct subsets, and the distance table is
13
- computed purely from compact's 3D oriented boxes). This guarantees the two schemas can never
14
- silently disagree about the same scene's geometry.
15
-
16
- Formerly this file called into perceptual.py (as a dynamically-loaded `pl` module) for its own
17
- geometry helpers -- build_instances, room_gravity, answer_closest_distance, and everything else
18
- in this file below _room_outline(). Those functions are now merged in directly, verbatim, since
19
- they were never DA3/SAM3 calls -- they're geometric computations over already-extracted
20
- depth/masks, which is exactly this file's job. perceptual.py's OTHER half (the actual
21
- model-calling functions) moved to run.py instead; perceptual.py itself no longer exists.
22
-
23
- The spatial code is the sole spatial representation the downstream VLM sees; no answer engine
24
- is computed here (the harness runs the model).
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import os
30
- import json
31
- import numpy as np
32
- import cv2
33
-
34
- # ==========================================================================================
35
- # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that
36
- # affect only the math below (build_instances/backproject_frame/etc.), never model inference.
37
- # ==========================================================================================
38
-
39
- SCHEMA = [
40
- "x",
41
- "y",
42
- "z",
43
- "e1",
44
- "e2",
45
- "e3",
46
- "px",
47
- "pz",
48
- "size_median",
49
- "size_IQR",
50
- "time",
51
- "n",
52
- ] # legacy row schema, see to_labeled()
53
- KD_WORKERS = max(1, int(os.environ.get("VSI_KD_WORKERS", "4")))
54
- # Batch workers set VSI_KD_WORKERS from their per-process CPU budget. Keeping a
55
- # bounded default avoids pathological all-core thread spawning for small queries.
56
- MIN_INSTANCE_PTS = (
57
- 1 # bare geometry floor only: need >=1 valid depth pixel to place a 3D point.
58
- )
59
- # NO quality filtering / dedup -- count = exactly SAM3's tracked masklets (honest)
60
- FLOOR_BAND = (
61
- 0.15 # m above the floor to count as floor-level (LEGACY -- currently unreferenced;
62
- )
63
- # compute_floor_area now uses the RANSAC gravity plane directly instead)
64
- # ---- geometry-cleanup levers (improve abs_distance etc.; env-tunable) ----
65
- # DEPTH_COHERENCE (Tukey-fence bleed removal): SAFE + helpful everywhere -> default ON.
66
- # ablation: ARKit abs_distance 0.757->0.729 (no harm), ScanNet++ d755 0.443->0.486 (helps).
67
- # CONF_PCT (per-frame confidence percentile): noisy-dataset ONLY -> default OFF.
68
- # helps ScanNet++ distance more (~0.56) but DESTROYS clean ARKit (0.757->0.429). Opt in via VSI_CONF_PCT=55.
69
- CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0"))
70
- DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1"
71
- # cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed
72
- # -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need.
73
- DEPTH_EDGE_REFINE = os.environ.get("VSI_DEPTH_EDGE_REFINE", "0") == "1"
74
- # MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that
75
- # depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1.
76
- MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1"
77
-
78
-
79
- # ==========================================================================================
80
- # ROOM/OBJECT GEOMETRY -- gravity, floor basis, per-instance spatial-code records. Merged in
81
- # from perceptual.py, verbatim.
82
- # ==========================================================================================
83
-
84
-
85
- def to_labeled(objects, floor_area):
86
- """LEGACY per-class summary (kept for --format array-compat). Superseded by to_spatial_code."""
87
- out = {"objects": {}}
88
- for cls, row in objects.items():
89
- d = dict(zip(SCHEMA, row))
90
- out["objects"][cls] = {
91
- "count": int(d["n"]),
92
- "centroid_meters": {"x": d["x"], "y": d["y"], "z": d["z"]},
93
- "longest_dimension_meters": {
94
- "median": d["size_median"],
95
- "iqr": d["size_IQR"],
96
- },
97
- "centroid_spread": {
98
- "eigenvalues": [d["e1"], d["e2"], d["e3"]],
99
- "principal_axis_xz": [d["px"], d["pz"]],
100
- },
101
- "first_seen_seconds": d["time"],
102
- }
103
- out["room"] = {"floor_area_square_meters": floor_area}
104
- return out
105
-
106
-
107
- def room_up_axis(instances, c2w):
108
- """up axis = smallest-extent axis of all object points; sign from gravity (floor->camera).
109
- Floor = densest horizontal slab; cameras are always above it, which fixes the sign.
110
- Returns (axis_index, signed_unit_vector)."""
111
- points = np.concatenate([i["pts"] for v in instances.values() for i in v], 0)
112
- ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
113
- up = int(np.argmin(ext))
114
- h, edges = np.histogram(points[:, up], bins=80)
115
- floor = 0.5 * (edges[h.argmax()] + edges[h.argmax() + 1]) # densest slab = floor
116
- cam_up = c2w[:, :3, 3][:, up].mean()
117
- e = np.zeros(3, np.float32)
118
- e[up] = 1.0 if cam_up > floor else -1.0
119
- return up, e
120
-
121
-
122
- def room_gravity(
123
- depth, intr, c2w, conf, conf_pct=40, stride=12, fstride=15, iters=300, thr=0.05
124
- ):
125
- """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward
126
- the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails.
127
- Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).
128
- """
129
- points = []
130
- for f in range(0, len(depth), fstride):
131
- height, width = depth[f].shape
132
- ys, xs = np.mgrid[0:height:stride, 0:width:stride]
133
- ys = ys.ravel()
134
- xs = xs.ravel()
135
- z = depth[f][ys, xs]
136
- ok = (z > 0) & np.isfinite(z)
137
- if conf is not None and conf_pct > 0:
138
- ok &= conf[f][ys, xs] >= np.percentile(conf[f], conf_pct)
139
- ys, xs, z = ys[ok], xs[ok], z[ok]
140
- if not len(z):
141
- continue
142
- intrinsics = intr[f]
143
- camera_points = np.stack(
144
- [
145
- (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
146
- (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
147
- z,
148
- ],
149
- 1,
150
- )
151
- points.append((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3])
152
- points = np.concatenate(points).astype(np.float64) if points else np.zeros((0, 3))
153
- cam = c2w[:, :3, 3].mean(0)
154
- if len(points) < 100: # fallback to axis-extent
155
- ext = (
156
- np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
157
- if len(points)
158
- else np.ones(3)
159
- )
160
- ax = int(np.argmin(ext))
161
- g = np.zeros(3)
162
- g[ax] = 1.0
163
- return g, ax
164
- rng = np.random.RandomState(0)
165
- best = None
166
- best_score = -1
167
- for _ in range(iters):
168
- a, b, c = points[rng.choice(len(points), 3, False)]
169
- nrm = np.cross(b - a, c - a)
170
- ln = np.linalg.norm(nrm)
171
- if ln < 1e-6:
172
- continue
173
- nrm /= ln
174
- d = -nrm @ a
175
- side = points @ nrm + d
176
- ninl = int((np.abs(side) < thr).sum())
177
- if ninl < 50:
178
- continue
179
- score = ninl * max(
180
- np.mean(side > thr), np.mean(side < -thr)
181
- ) # big + one-sided = floor
182
- if score > best_score:
183
- best_score = score
184
- best = (nrm, d)
185
- if best is None:
186
- ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
187
- ax = int(np.argmin(ext))
188
- g = np.zeros(3)
189
- g[ax] = 1.0
190
- return g, ax
191
- nrm, d = best
192
- if (cam @ nrm + d) < 0:
193
- nrm = -nrm # orient toward cameras (up)
194
- return nrm.astype(np.float32), int(np.argmax(np.abs(nrm)))
195
-
196
-
197
- def pos3(rec):
198
- """Read either legacy numeric or current unit-string position formatting."""
199
- p = rec.get("position") or {}
200
-
201
- def meters(current, legacy):
202
- value = p.get(current, p.get(legacy, 0.0))
203
- if isinstance(value, str):
204
- if value.endswith(" meters"):
205
- value = value[: -len(" meters")]
206
- value = value.strip()
207
- return float(value)
208
-
209
- return [
210
- meters("x coordinate", "floor_x_meters"),
211
- meters("y coordinate", "floor_y_meters"),
212
- meters("height above floor", "height_above_floor_meters"),
213
- ]
214
-
215
-
216
- def _floor_basis(up_vec):
217
- """Orthonormal floor basis (u, v horizontal; g = up) from the gravity vector. u is the OLD
218
- floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame
219
- differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane
220
- rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline
221
- all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.
222
- """
223
- g = np.asarray(up_vec, np.float64)
224
- g = g / (np.linalg.norm(g) + 1e-12)
225
- up_ax = int(np.argmax(np.abs(g)))
226
- floor_axes = [
227
- a for a in range(3) if a != up_ax
228
- ] # the two world axes the old frame used
229
- e0 = np.zeros(3)
230
- e0[floor_axes[0]] = 1.0 # old floor_x world axis
231
- u = e0 - (e0 @ g) * g
232
- u = u / (np.linalg.norm(u) + 1e-12) # project it into the gravity plane
233
- v = np.cross(g, u)
234
- if v[floor_axes[1]] < 0:
235
- v = -v # keep floor_y sign aligned with the old axis
236
- return u, v, g
237
-
238
-
239
- def _floor_level(points, gravity, v2=None):
240
- """Reference floor estimator shared by every model representation.
241
-
242
- The supplied geometry uses the densest gravity-height slab for its reproducible v1
243
- behavior and the robust second percentile for v2. Keep that switch here, after model
244
- adapters have produced world points, so it cannot become model-specific.
245
- """
246
- heights = np.asarray(points, np.float64) @ np.asarray(gravity, np.float64)
247
- heights = heights[np.isfinite(heights)]
248
- if not len(heights):
249
- return 0.0
250
- if v2 is None:
251
- v2 = os.environ.get("VSI_CODE_V2") == "1"
252
- if v2:
253
- return float(np.percentile(heights, 2))
254
- counts, edges = np.histogram(heights, bins=80)
255
- index = int(counts.argmax())
256
- return float(0.5 * (edges[index] + edges[index + 1]))
257
-
258
-
259
- # ==========================================================================================
260
- # DETERMINISTIC ANSWER LAYER (parameter-free; validated on VSI GT). Reads the in-memory
261
- # instances (pos for direction/route, point clouds for distance). Merged in from
262
- # perceptual.py, verbatim.
263
- # ==========================================================================================
264
-
265
-
266
- def _find_cls(name, classes):
267
- """Mirrors symbolic/solver.py's _find_class exactly (see its docstring): word-TOKEN
268
- subset, not raw character substring -- "washer" must not match "dishwasher" just
269
- because the characters appear inside it (2026-07-26 fix, found via the citation-
270
- fidelity audit)."""
271
- name = name.strip().lower()
272
- for c in classes:
273
- if c == name or c.replace(" ", "") == name.replace(" ", ""):
274
- return c
275
- name_tokens = set(name.split())
276
- for c in classes:
277
- class_tokens = set(c.split())
278
- if (
279
- name_tokens
280
- and class_tokens
281
- and (name_tokens <= class_tokens or class_tokens <= name_tokens)
282
- ):
283
- return c
284
- return None
285
-
286
-
287
- def _rep(insts):
288
- """representative instance = most observed points (best-segmented, validated 8/8 on direction)."""
289
- return max(insts, key=lambda i: i["n"])
290
-
291
-
292
- def answer_rel_direction(point_a, point_b, point_c, up_vec, up_ax, mode="hard"):
293
- """Standing at A facing B, where is C? front/back=dot(C-A,fwd); left/right=dot(C-A, up x fwd).
294
- Right-handed world (OpenCV cam frame + det+1 c2w) makes up x fwd = left a fixed identity.
295
- Projection uses the gravity VECTOR (v-(v.g)g), so a tilted floor (ScanNet++) is handled; for an
296
- axis-aligned up this reduces to zeroing that axis (ARKit unchanged)."""
297
- g = np.asarray(up_vec, np.float64)
298
- g = g / (np.linalg.norm(g) + 1e-12)
299
-
300
- def fl(v):
301
- w = v.astype(np.float64)
302
- return w - (w @ g) * g
303
-
304
- fwd = fl(point_b - point_a)
305
- n = np.linalg.norm(fwd)
306
- if n < 1e-6:
307
- return None
308
- fwd /= n
309
- left = np.cross(g, fwd)
310
- left /= np.linalg.norm(left) + 1e-9
311
- d = fl(point_c - point_a)
312
- f = float(d @ fwd)
313
- lateral = float(d @ left)
314
- if mode == "medium":
315
- if abs(np.degrees(np.arctan2(lateral, f))) >= 135:
316
- return "back"
317
- return "left" if lateral > 0 else "right"
318
- return f"{'front' if f > 0 else 'back'}-{'left' if lateral > 0 else 'right'}"
319
-
320
-
321
- def _classify_turn(h_in, h_out, up_vec, up_ax):
322
- """rotation h_in->h_out in floor plane -> turn left/right/back (135deg = VSI's own 'back' cutoff)."""
323
- g = np.asarray(up_vec, np.float64)
324
- g = g / (np.linalg.norm(g) + 1e-12)
325
-
326
- def fl(v):
327
- w = v.astype(np.float64)
328
- return w - (w @ g) * g
329
-
330
- a, b = fl(h_in), fl(h_out)
331
- na, nb = np.linalg.norm(a), np.linalg.norm(b)
332
- if na < 1e-6 or nb < 1e-6:
333
- return None
334
- a /= na
335
- b /= nb
336
- ang = np.degrees(np.arctan2(float(up_vec @ np.cross(a, b)), float(a @ b)))
337
- if abs(ang) >= 135:
338
- return "turn back"
339
- return "turn left" if ang > 0 else "turn right"
340
-
341
-
342
- def answer_route(ql, cents, up_vec, up_ax):
343
- """Chain the turn primitive over the waypoint sequence -> ordered ['turn left/right/back', ...]."""
344
- import re as _re
345
-
346
- m = _re.search(r"beginning at the (.+?) (?:and )?facing the (.+?)\.", ql)
347
- if not m:
348
- return None
349
-
350
- def position(name):
351
- class_name = _find_cls(name, cents)
352
- return cents[class_name] if class_name else None
353
-
354
- steps_txt = ql.split(":", 1)[1] if ":" in ql else ql
355
- steps = _re.findall(
356
- r"\d+\.\s*(\[please fill in\]|Go forward until the [^0-9\[]+?)(?=\s*\d+\.|$)",
357
- steps_txt,
358
- )
359
- cur_pos = position(m.group(1).strip())
360
- if cur_pos is None:
361
- return None
362
- fac = position(m.group(2).strip())
363
- cur_head = (fac - cur_pos) if fac is not None else None
364
- turns = []
365
- i = 0
366
- while i < len(steps):
367
- s = steps[i].strip()
368
- if s.startswith("Go forward"):
369
- tp = position(_re.sub(r"^Go forward until the ", "", s).strip().rstrip("."))
370
- if tp is not None:
371
- cur_head = tp - cur_pos
372
- cur_pos = tp
373
- else:
374
- nxt = next(
375
- (
376
- _re.sub(r"^Go forward until the ", "", steps[j].strip())
377
- .strip()
378
- .rstrip(".")
379
- for j in range(i + 1, len(steps))
380
- if steps[j].strip().startswith("Go forward")
381
- ),
382
- None,
383
- )
384
- tp = position(nxt) if nxt else None
385
- if tp is None or cur_head is None:
386
- turns.append(None)
387
- else:
388
- turns.append(_classify_turn(cur_head, tp - cur_pos, up_vec, up_ax))
389
- cur_head = tp - cur_pos
390
- i += 1
391
- return turns
392
-
393
-
394
- # ==========================================================================================
395
- # POINT-CLOUD CLEANING + DISTANCE ANSWERS -- outlier removal, closest-distance queries. Merged
396
- # in from perceptual.py, verbatim.
397
- # ==========================================================================================
398
-
399
-
400
- def _sor(pts, k=16, std=2.0, cap=4000):
401
- """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds
402
- mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min.
403
- k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).
404
- """
405
- from scipy.spatial import cKDTree
406
-
407
- if len(pts) < k + 2:
408
- return pts
409
- rs = np.random.RandomState(0)
410
- points = pts if len(pts) <= cap else pts[rs.choice(len(pts), cap, False)]
411
- d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
412
- md = d[:, 1:].mean(1)
413
- return points[md <= md.mean() + std * md.std()]
414
-
415
-
416
- def _main_cluster(pts):
417
- """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent
418
- object forms a disconnected component (a gap separates two objects); the true object is the largest one.
419
- Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.
420
- """
421
- from scipy.spatial import cKDTree
422
-
423
- if len(pts) < 30:
424
- return pts
425
- tree = cKDTree(pts)
426
- nn, _ = tree.query(pts, k=2)
427
- eps = 3.0 * float(np.median(nn[:, 1])) # 3x median NN gap (data-derived)
428
- pairs = tree.query_pairs(eps, output_type="ndarray")
429
- if len(pairs) == 0:
430
- return pts
431
- parent = np.arange(len(pts))
432
-
433
- def find(x):
434
- r = x
435
- while parent[r] != r:
436
- r = parent[r]
437
- while parent[x] != r:
438
- parent[x], x = r, parent[x]
439
- return r
440
-
441
- for a, b in pairs:
442
- ra, rb = find(int(a)), find(int(b))
443
- if ra != rb:
444
- parent[ra] = rb
445
- roots = np.array([find(i) for i in range(len(pts))])
446
- v, cnt = np.unique(roots, return_counts=True)
447
- return pts[roots == v[cnt.argmax()]]
448
-
449
-
450
- def _clean(inst, cap=4000):
451
- """Outlier removal self-calibrated from the pipeline's OWN per-object signals -- no universal constant,
452
- no benchmark knob. Cached on the instance so the O(classes^2) distance table cleans each object once.
453
- (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the
454
- object's OWN median confidence (data-derived cut);
455
- (2) statistical density outlier removal on the survivors;
456
- (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.
457
- """
458
- if inst.get("_cleanpts") is not None:
459
- return inst["_cleanpts"]
460
- pts = inst["pts"]
461
- conf = inst.get("conf")
462
- rs = np.random.RandomState(0)
463
- if len(pts) > cap:
464
- idx = rs.choice(len(pts), cap, False)
465
- pts = pts[idx]
466
- conf = conf[idx] if conf is not None else None
467
- if conf is not None and len(conf) > 20: # self-calibrating: object's OWN median
468
- keep = conf >= np.median(conf)
469
- if keep.sum() >= 10:
470
- pts = pts[keep]
471
- pts = _sor(pts, cap=cap) # density outlier removal on the survivors
472
- # NOTE: spatial de-bleeding (_main_cluster) was tried and REVERTED -- "largest cluster = the object" is
473
- # not guaranteed; when an object's near edge splits off it drops the true closest part (overshoot). You
474
- # cannot post-hoc recover the true object from a bleeding mask in 3D -- that needs better SOURCE masks.
475
- inst["_cleanpts"] = pts
476
- return pts
477
-
478
-
479
- def answer_closest_distance(instances_a, instances_b, k=4000):
480
- """Closest distance between the two objects' point clouds ('closest point of each object'). Points are
481
- cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via
482
- KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation
483
- boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.
484
- """
485
- points_a = _clean(_rep(instances_a), cap=k)
486
- points_b = _clean(_rep(instances_b), cap=k)
487
- if len(points_a) == 0 or len(points_b) == 0:
488
- return float("inf")
489
- from scipy.spatial import cKDTree
490
-
491
- if len(points_a) <= len(points_b):
492
- d, _ = cKDTree(points_a).query(points_b, k=1, workers=KD_WORKERS)
493
- else:
494
- d, _ = cKDTree(points_b).query(points_a, k=1, workers=KD_WORKERS)
495
- return float(d.min())
496
-
497
-
498
- # ==========================================================================================
499
- # MASK/DEPTH CLEANUP + BACK-PROJECTION -- per-frame refinement before points enter an
500
- # instance's point cloud. Merged in from perceptual.py, verbatim.
501
- # ==========================================================================================
502
-
503
-
504
- def depth_edges(depth_f, valid_f):
505
- """Per-frame depth-DISCONTINUITY map: gradient magnitude above median + 3*MAD over the valid pixels.
506
- The threshold is data-derived (robust, universal statistical cut -- NOT benchmark-tuned). These edges are
507
- where mask-bleed crosses onto an adjacent object at a different depth."""
508
- if valid_f.sum() < 100:
509
- return np.zeros_like(depth_f, bool)
510
- d = np.where(valid_f, depth_f, np.median(depth_f[valid_f]))
511
- gy, gx = np.gradient(d)
512
- grad = np.hypot(gx, gy)
513
- g = grad[valid_f]
514
- med = np.median(g)
515
- mad = np.median(np.abs(g - med)) + 1e-9
516
- return (grad > med + 3.0 * 1.4826 * mad) & valid_f
517
-
518
-
519
- try:
520
- _GUIDED = (
521
- cv2.ximgproc.guidedFilter
522
- ) # opencv-contrib; appearance-guided boundary snap
523
- except AttributeError:
524
- _GUIDED = None
525
-
526
-
527
- def refine_mask(mask, rgb):
528
- """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth
529
- bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge
530
- cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color
531
- variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.
532
- """
533
- if mask.shape[:2] != rgb.shape[:2]:
534
- mask = cv2.resize(
535
- mask.astype(np.uint8),
536
- (rgb.shape[1], rgb.shape[0]),
537
- interpolation=cv2.INTER_NEAREST,
538
- ).astype(bool)
539
- a = int(mask.sum())
540
- if a < 60: # too small to refine meaningfully -> 1px erode as before
541
- me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
542
- return me if me.any() else mask
543
- if _GUIDED is not None:
544
- r = max(
545
- 4, int(round(0.02 * float(np.hypot(*mask.shape[:2]))))
546
- ) # radius ~2% of frame diagonal
547
- eps = (
548
- float(np.var(rgb.astype(np.float32) / 255.0)) * 0.01 + 1e-6
549
- ) # smoothness ~ image color variance
550
- soft = _GUIDED(rgb, mask.astype(np.float32), r, eps)
551
- out = soft > 0.5
552
- return out if out.sum() >= 0.4 * a else mask # majority guard: don't over-carve
553
- # fallback (base opencv, no ximgproc): grabCut seeded FG=mask, PR_FG=dilated ring, BG=far exterior
554
- try:
555
- gc = np.full(mask.shape[:2], cv2.GC_PR_BGD, np.uint8)
556
- dil = cv2.dilate(mask.astype(np.uint8), np.ones((15, 15), np.uint8), 1).astype(
557
- bool
558
- )
559
- er = cv2.erode(mask.astype(np.uint8), np.ones((5, 5), np.uint8), 1).astype(bool)
560
- gc[dil] = cv2.GC_PR_FGD
561
- gc[er] = cv2.GC_FGD
562
- bgm = np.zeros((1, 65), np.float64)
563
- fgm = np.zeros((1, 65), np.float64)
564
- cv2.grabCut(rgb, gc, None, bgm, fgm, 3, cv2.GC_INIT_WITH_MASK)
565
- out = (gc == cv2.GC_FGD) | (gc == cv2.GC_PR_FGD)
566
- return out if 0.4 * a <= out.sum() <= 1.5 * a else mask
567
- except Exception:
568
- me = cv2.erode(mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1).astype(bool)
569
- return me if me.any() else mask
570
-
571
-
572
- def backproject_frame(
573
- depth_f,
574
- intrinsics,
575
- c2w_f,
576
- mask_f,
577
- conf_f=None,
578
- conf_thr=0.0,
579
- valid_f=None,
580
- return_conf=False,
581
- edges_f=None,
582
- ):
583
- """Return (M,3) world points for the masked pixels of one frame (c2w_f = cam->world 4x4).
584
- valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame.
585
- return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning).
586
- edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component
587
- (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).
588
- """
589
- height, width = depth_f.shape
590
- empty = (
591
- (np.empty((0, 3), np.float32), np.empty((0,), np.float32))
592
- if return_conf
593
- else np.empty((0, 3), np.float32)
594
- )
595
- if mask_f.shape != (height, width):
596
- mask_f = cv2.resize(
597
- mask_f.astype(np.uint8), (width, height), interpolation=cv2.INTER_NEAREST
598
- ).astype(bool)
599
- if valid_f is None:
600
- valid_f = np.isfinite(depth_f) & (depth_f > 0)
601
- m = mask_f & valid_f
602
- if conf_f is not None and conf_thr > 0:
603
- m &= conf_f >= conf_thr
604
- if (
605
- edges_f is not None and m.sum() >= 30
606
- ): # keep the largest depth-coherent piece of the mask
607
- from scipy import ndimage
608
-
609
- lab, nlab = ndimage.label(m & ~edges_f)
610
- if nlab >= 1:
611
- sizes = np.bincount(lab.ravel())
612
- sizes[0] = 0
613
- big = int(sizes.argmax())
614
- if (
615
- sizes[big] >= 0.5 * m.sum()
616
- ): # object is the MAJORITY piece (bleed is a minority)
617
- m = lab == big
618
- if not m.any():
619
- return empty
620
- ys, xs = np.nonzero(m)
621
- z = depth_f[ys, xs]
622
- if DEPTH_COHERENCE and len(z) >= 8:
623
- # an object is a coherent depth surface; floor/background BLEED pixels are depth outliers.
624
- # Drop them via the standard Tukey fence (1.5*IQR) on the masked region's depths -- parameter-free.
625
- q1, q3 = np.percentile(z, [25, 75])
626
- iqr = q3 - q1
627
- keep = (z >= q1 - 1.5 * iqr) & (z <= q3 + 1.5 * iqr)
628
- if keep.sum() >= 1:
629
- ys, xs, z = ys[keep], xs[keep], z[keep]
630
- fx, fy, cx, cy = (
631
- intrinsics[0, 0],
632
- intrinsics[1, 1],
633
- intrinsics[0, 2],
634
- intrinsics[1, 2],
635
- )
636
- camera_points = np.stack(
637
- [(xs - cx) * z / fx, (ys - cy) * z / fy, z], axis=1
638
- ) # camera coords
639
- world_points = (c2w_f[:3, :3] @ camera_points.T).T + c2w_f[:3, 3] # -> world
640
- if return_conf:
641
- cw = (
642
- conf_f[ys, xs].astype(np.float32)
643
- if conf_f is not None
644
- else np.ones(len(ys), np.float32)
645
- )
646
- return world_points.astype(np.float32), cw
647
- return world_points.astype(np.float32)
648
-
649
-
650
- # ==========================================================================================
651
- # INSTANCE BUILDING -- oriented extent, 3D box-overlap re-identification, and the main
652
- # build_instances() driver that turns per-frame masks into per-class 3D instances. Merged in
653
- # from perceptual.py, verbatim.
654
- # ==========================================================================================
655
-
656
-
657
- def robust_centroid_extent(pts, up_axis=None):
658
- """median centroid + ORIENTED robust extent.
659
- If up_axis is given: YAW-ONLY oriented extent -- rotation is found by 2D PCA on the
660
- floor-projected points only, with the up axis left untouched. This matches VSI-Bench's
661
- own annotation convention for indoor scans (ScanNet/ARKitScenes OrientedBoundingBox
662
- objects follow a Manhattan-world assumption: rotated only around the vertical axis,
663
- never tilted). Unconstrained 3D PCA (the previous behavior) can chase noise on the
664
- vertical axis for flat/elongated objects and drift away from the true yaw.
665
- If up_axis is None (unknown at the call site): falls back to unconstrained 3D PCA.
666
- Either way: parameter-free, rotation-invariant in-plane, p2..p98 robust extent."""
667
- c = np.median(pts, axis=0)
668
- centered = pts - c
669
- if len(centered) > 5000: # PCA on a sample (deterministic)
670
- centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
671
- if up_axis is not None:
672
- floor_axes = [i for i in range(3) if i != up_axis]
673
- floor_points = centered[:, floor_axes]
674
- try:
675
- _, _, floor_rotation = np.linalg.svd(
676
- floor_points - floor_points.mean(0), full_matrices=False
677
- )
678
- proj_floor = (
679
- floor_points @ floor_rotation.T
680
- ) # (N,2) along the object's own floor-plane axes
681
- except np.linalg.LinAlgError:
682
- proj_floor = floor_points
683
- up_col = centered[:, up_axis : up_axis + 1] # up axis untouched (yaw-only)
684
- proj = np.concatenate([proj_floor, up_col], axis=1)
685
- else:
686
- try:
687
- _, _, rotation = np.linalg.svd(
688
- centered - centered.mean(0), full_matrices=False
689
- )
690
- proj = centered @ rotation.T # coordinates along principal axes
691
- except np.linalg.LinAlgError:
692
- proj = centered
693
- lo = np.percentile(proj, 2, axis=0)
694
- hi = np.percentile(proj, 98, axis=0)
695
- ext = np.maximum(hi - lo, 0.0)
696
- dims = np.sort(ext)[::-1] # the object's 3 oriented side lengths, longest first
697
- return c.astype(np.float32), float(dims[0]), dims
698
-
699
-
700
- def _aabb(pts):
701
- """robust (p2..p98) axis-aligned 3D box of an instance's world points."""
702
- return np.percentile(pts, 2, axis=0), np.percentile(pts, 98, axis=0)
703
-
704
-
705
- def merge_by_box_overlap(insts, up_axis=None):
706
- """Parameter-free 3D re-identification, with a temporal-exclusion gate.
707
-
708
- SAM3 (a 2D tracker) emits a NEW masklet each time the camera revisits an object, so one
709
- physical object -> several masklets at the same 3D location. We fuse two same-class masklets
710
- iff BOTH:
711
- (a) their measured 3D boxes overlap (or one centroid is inside the other) -- same volume, and
712
- (b) they NEVER appear in the same frame -- temporal exclusion.
713
- (b) is the key parameter-free invariant: two masklets co-visible in one frame were tracked by
714
- SAM3 as distinct objects in that frame, so they ARE distinct (e.g. two chairs around a table);
715
- we must never merge them, even if depth noise makes their boxes overlap. A revisit-duplicate,
716
- by contrast, lives in DISJOINT frames. Both tests are exact/measured -- NO tuned threshold.
717
- """
718
- n = len(insts)
719
- if n <= 1:
720
- return insts
721
- # Precompute the FULL pairwise box-match as one vectorized boolean matrix. With the per-frame
722
- # batched detector a class can have 100+ raw instances; the old O(n^3) loop called np.all-based
723
- # box_match millions of times. Here every pairwise test is one broadcast -> O(1) lookups below.
724
- lo = np.stack([_aabb(i["pts"])[0] for i in insts]).astype(np.float32) # (n,3)
725
- hi = np.stack([_aabb(i["pts"])[1] for i in insts]).astype(np.float32) # (n,3)
726
- cents = np.stack([i["centroid"] for i in insts]).astype(np.float32) # (n,3)
727
- overlap = (hi[:, None, :] >= lo[None, :, :]).all(-1) & (
728
- hi[None, :, :] >= lo[:, None, :]
729
- ).all(-1)
730
- ins = (cents[:, None, :] >= lo[None, :, :]).all(-1) & (
731
- cents[:, None, :] <= hi[None, :, :]
732
- ).all(-1)
733
- match = (
734
- overlap | ins | ins.T
735
- ) # box_match[i,j]: same 3D volume (identical semantics to old code)
736
- # group-level agglomeration: merge two groups only if their COMBINED frame sets are disjoint
737
- # (so no two co-visible masklets ever land in one object) AND some cross-pair shares a 3D volume.
738
- groups = [
739
- {"members": [i], "frames": set(insts[i].get("frames", set()))} for i in range(n)
740
- ]
741
- changed = True
742
- while changed:
743
- changed = False
744
- for a in range(len(groups)):
745
- for b in range(a + 1, len(groups)):
746
- if (
747
- groups[a]["frames"] & groups[b]["frames"]
748
- ): # co-visible -> distinct objects
749
- continue
750
- if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
751
- groups[a]["members"] += groups[b]["members"]
752
- groups[a]["frames"] |= groups[b]["frames"]
753
- groups.pop(b)
754
- changed = True
755
- break
756
- if changed:
757
- break
758
- merged = []
759
- for g in groups:
760
- idxs = g["members"]
761
- pts = np.concatenate([insts[k]["pts"] for k in idxs], 0)
762
- cpts = np.concatenate(
763
- [
764
- insts[k].get("conf", np.ones(len(insts[k]["pts"]), np.float32))
765
- for k in idxs
766
- ],
767
- 0,
768
- )
769
- best = max(
770
- (insts[k]["best_pts"] for k in idxs), key=len
771
- ) # largest single obs in the group
772
- c, longest, dims = robust_centroid_extent(
773
- best, up_axis
774
- ) # size+pos+3 oriented dims from best view (#2/#4)
775
- merged.append(
776
- {
777
- "centroid": c,
778
- "size": longest,
779
- "dims": dims,
780
- "first_time": min(insts[k]["first_time"] for k in idxs),
781
- "pts": pts,
782
- "conf": cpts,
783
- "best_pts": best,
784
- "observations": [
785
- observation
786
- for k in idxs
787
- for observation in insts[k].get("observations", [insts[k]["pts"]])
788
- ],
789
- "frames": g["frames"],
790
- "n": sum(insts[k]["n"] for k in idxs),
791
- "nframes": len(g["frames"]),
792
- "oids": [oid for k in idxs for oid in insts[k].get("oids", [])],
793
- }
794
- ) # track persistence (evidence strength)
795
- return merged
796
-
797
-
798
- def build_instances(
799
- per_class, depth, intr, c2w, conf, frame_times, frame_paths=None, up_axis=None
800
- ):
801
- """-> {class: [ {centroid(3), size(longest dim), first_time, npts} ]}
802
- up_axis: if known (from room_gravity, computed BEFORE this call), threads through to
803
- robust_centroid_extent for yaw-only oriented sizing. If None, size falls back to
804
- unconstrained 3D PCA."""
805
- out = {}
806
- stats = {}
807
- nframes = len(depth)
808
- # precompute each frame's valid-depth mask ONCE (was recomputed per mask -> per class).
809
- valid = {}
810
- edges = {}
811
- rgb = {}
812
- used_frames = {fi for frames in per_class.values() for fi in frames if fi < nframes}
813
- for fi in used_frames:
814
- valid[fi] = np.isfinite(depth[fi]) & (depth[fi] > 0)
815
- edges[fi] = depth_edges(depth[fi], valid[fi]) if DEPTH_EDGE_REFINE else None
816
- if MASK_REFINE and frame_paths and fi < len(frame_paths):
817
- im = cv2.imread(frame_paths[fi]) # BGR; guidedFilter/grabCut want 3ch uint8
818
- rgb[fi] = (
819
- cv2.resize(im, (depth[fi].shape[1], depth[fi].shape[0]))
820
- if im is not None
821
- else None
822
- )
823
- for cls, frames in per_class.items():
824
- # peak co-visibility: max distinct masklets SAM3 tracks SIMULTANEOUSLY in any one frame.
825
- # geometry-free, parameter-free, immune to revisit over-count; provable lower bound on count.
826
- peak = max((len(objs) for objs in frames.values()), default=0)
827
- # gather world points + first-seen time + frame set per obj_id (SAM3 track id = masklet)
828
- pts_by_id, conf_by_id, first_t, frames_by_id = {}, {}, {}, {}
829
- # px_by_id: (fidx, frame_time, mask_pixel_count) per obj_id, for appearance-order timing.
830
- # VSI-Bench's own GT defines "first appearance" as the timestamp where an object's pixel
831
- # count crosses a threshold (paper appendix B.1) -- NOT the first frame with any pixel at
832
- # all. A single stray mask-bleed/false-positive pixel would otherwise register as "first
833
- # seen" far too early. The threshold is self-calibrated per instance (that instance's OWN
834
- # median observed pixel count across its frames), same convention as _clean's median cut.
835
- px_by_id = {}
836
- for fidx, objs in frames.items():
837
- if fidx >= nframes: # guard: SAM3 frame idx vs DA3 frames
838
- continue
839
- for oid, mask in objs.items():
840
- if MASK_REFINE and rgb.get(fidx) is not None:
841
- me = (
842
- mask
843
- if os.environ.get("VSI_NO_REFINE") == "1"
844
- else refine_mask(mask, rgb[fidx])
845
- ) # appearance-guided boundary snap (clips same-depth bleed)
846
- else:
847
- # erode 1px to drop mask-edge / background depth bleed
848
- me = cv2.erode(
849
- mask.astype(np.uint8), np.ones((3, 3), np.uint8), 1
850
- ).astype(bool)
851
- if not me.any():
852
- me = mask
853
- conf_f = conf[fidx] if conf is not None else None
854
- conf_thr = (
855
- np.percentile(conf_f, CONF_PCT)
856
- if (conf_f is not None and CONF_PCT > 0)
857
- else 0.0
858
- )
859
- world_points, cw = backproject_frame(
860
- depth[fidx],
861
- intr[fidx],
862
- c2w[fidx],
863
- me,
864
- conf_f,
865
- conf_thr=conf_thr,
866
- valid_f=valid.get(fidx),
867
- return_conf=True,
868
- edges_f=edges.get(fidx),
869
- )
870
- if len(world_points):
871
- pts_by_id.setdefault(oid, []).append(world_points)
872
- conf_by_id.setdefault(oid, []).append(
873
- cw
874
- ) # per-point DA3 confidence (for _clean)
875
- frames_by_id.setdefault(oid, set()).add(
876
- fidx
877
- ) # for co-occurrence gate
878
- t = frame_times[fidx]
879
- px_by_id.setdefault(oid, []).append((fidx, t, int(me.sum())))
880
- # appearance_order timing: per instance, first frame at/above its OWN median pixel count
881
- for oid, obs in px_by_id.items():
882
- counts = [c for _, _, c in obs]
883
- thresh = float(np.median(counts))
884
- crossing = [t for _, t, c in obs if c >= thresh]
885
- first_t[oid] = min(crossing) if crossing else min(t for _, t, c in obs)
886
- insts = []
887
- for oid, plist in pts_by_id.items():
888
- pts = np.concatenate(plist, 0)
889
- cpts = np.concatenate(conf_by_id[oid], 0)
890
- if len(pts) < MIN_INSTANCE_PTS:
891
- continue
892
- best = max(
893
- plist, key=len
894
- ) # #2/#4: largest single-frame observation (closest/most pixels)
895
- bc, bsize, bdims = robust_centroid_extent(
896
- best, up_axis
897
- ) # size + position + 3 oriented dims from best view
898
- insts.append(
899
- {
900
- "centroid": bc,
901
- "size": bsize,
902
- "dims": bdims,
903
- "first_time": first_t[oid],
904
- "pts": pts,
905
- "conf": cpts,
906
- "best_pts": best,
907
- "observations": list(plist),
908
- "n": len(pts),
909
- "frames": frames_by_id[oid],
910
- # Raw SAM3 masklet id this fragment came from -- carried through every
911
- # later merge/consolidation step (never emitted in the JSON schema) so
912
- # a strong-correspondence overlay can draw SAM3's OWN per-frame
913
- # box/mask for a code instance instead of re-deriving one via 3D
914
- # projection. See encoder.geometric.instance_source_track_ids.
915
- "oids": [int(oid)],
916
- }
917
- )
918
- raw = len(insts)
919
- # 3D re-ID: fuse same-class masklets that occupy the same measured 3D volume (parameter-free).
920
- insts = merge_by_box_overlap(insts, up_axis)
921
- if insts:
922
- out[cls] = insts
923
- stats[cls] = {"raw": raw, "merged": len(insts), "peak": peak}
924
- return out, stats
925
-
926
-
927
- # ==========================================================================================
928
- # PER-CLASS SUMMARY -- legacy array-schema row builder. Merged in from perceptual.py, verbatim.
929
- # (The room-scale floor area calculation that used to live here is gone -- the explicit
930
- # schema's floor area is now a direct derivation of the compact schema's floor boundary
931
- # polygons; see build_explicit_spatial_code() near build_compact_spatial_code().)
932
- # ==========================================================================================
933
-
934
-
935
- # ---- Per-class spatial code (legacy array-schema row) -------------------------------------
936
- def class_spatial_code(insts, peak=0):
937
- cents = np.stack([i["centroid"] for i in insts], 0) # (n,3)
938
- sizes = np.array([i["size"] for i in insts], np.float32)
939
- n = len(insts) # merged centroids (for spatial stats)
940
- count = peak if peak else n # reported count = peak co-visibility
941
- x, y, z = cents.mean(0)
942
- if n == 1:
943
- e1 = e2 = e3 = px = pz = 0.0
944
- size_iqr = 0.0
945
- else:
946
- cov = np.cov(cents.T) # 3x3
947
- vals, vecs = np.linalg.eigh(cov) # ascending
948
- order = np.argsort(vals)[::-1]
949
- vals = np.clip(vals[order], 0, None)
950
- vecs = vecs[:, order]
951
- e1, e2, e3 = vals.tolist()
952
- pv = vecs[:, 0] # principal eigenvector
953
- px, pz = float(pv[0]), float(pv[2])
954
- q1, q3 = np.percentile(sizes, [25, 75])
955
- size_iqr = float(q3 - q1)
956
- size_median = float(np.median(sizes))
957
- first_time = float(min(i["first_time"] for i in insts))
958
- row = [x, y, z, e1, e2, e3, px, pz, size_median, size_iqr, first_time, count]
959
- row = [
960
- (lambda r: 0.0 if r == 0 else r)(round(float(v), 1)) for v in row
961
- ] # kill -0.0
962
- row[-1] = int(count)
963
- return row
964
-
965
-
966
- def _reference_object_records(insts, count, u, v, g, floor_level):
967
- """Object record formatter used by the original V2 spatial-code builder."""
968
- ranked = sorted(insts, key=lambda i: (i["n"], i.get("nframes", 0)), reverse=True)[
969
- : max(int(count), 1)
970
- ]
971
- recs = []
972
- for it in ranked:
973
- center = np.asarray(it["centroid"], np.float64)
974
- points = np.asarray(it["pts"], np.float64)
975
- floor_x = points @ u
976
- floor_y = points @ v
977
- height = points @ g - floor_level
978
- recs.append(
979
- {
980
- "position": {
981
- "floor_x_meters": round(float(center @ u), 2),
982
- "floor_y_meters": round(float(center @ v), 2),
983
- "height_above_floor_meters": round(
984
- float(center @ g - floor_level), 2
985
- ),
986
- },
987
- "longest_dimension_meters": round(float(it["size"]), 2),
988
- "bounding_box": {
989
- "floor_x_meters": [
990
- round(float(np.percentile(floor_x, 2)), 2),
991
- round(float(np.percentile(floor_x, 98)), 2),
992
- ],
993
- "floor_y_meters": [
994
- round(float(np.percentile(floor_y, 2)), 2),
995
- round(float(np.percentile(floor_y, 98)), 2),
996
- ],
997
- "height_above_floor_meters": [
998
- round(float(np.percentile(height, 2)), 2),
999
- round(float(np.percentile(height, 98)), 2),
1000
- ],
1001
- },
1002
- "dimensions_meters": [round(float(d), 2) for d in it["dims"]],
1003
- }
1004
- )
1005
- return recs
1006
-
1007
-
1008
- def _reference_to_spatial_code(
1009
- instances, stats, floor_area, up_axis, up_vec, floor_level
1010
- ):
1011
- """Per-instance spatial code shape from the original geometric V2 pipeline."""
1012
- u, v, g = _floor_basis(up_vec)
1013
- out = {"objects": {}}
1014
- for class_name, insts in instances.items():
1015
- count = int(stats[class_name]["peak"])
1016
- out["objects"][class_name] = {
1017
- "count": count,
1018
- "instances": _reference_object_records(insts, count, u, v, g, floor_level),
1019
- }
1020
- out["room"] = {"floor_area_square_meters": floor_area}
1021
- return out
1022
-
1023
-
1024
- def compute_floor_area(depth, intr, c2w, conf, sky, stride=8, up_vec=None):
1025
- """Reference floor-area computation from the original geometric pipeline."""
1026
- points = []
1027
- for frame_index in range(depth.shape[0]):
1028
- height, width = depth[frame_index].shape
1029
- rows, columns = np.mgrid[0:height:stride, 0:width:stride]
1030
- rows = rows.ravel()
1031
- columns = columns.ravel()
1032
- values = depth[frame_index][rows, columns]
1033
- keep = np.isfinite(values) & (values > 0)
1034
- if sky is not None:
1035
- keep &= ~sky[frame_index][rows, columns].astype(bool)
1036
- if conf is not None:
1037
- keep &= conf[frame_index][rows, columns] >= np.percentile(
1038
- conf[frame_index], 40
1039
- )
1040
- rows, columns, values = rows[keep], columns[keep], values[keep]
1041
- if not len(values):
1042
- continue
1043
- current = intr[frame_index]
1044
- camera = np.stack(
1045
- [
1046
- (columns - current[0, 2]) * values / current[0, 0],
1047
- (rows - current[1, 2]) * values / current[1, 1],
1048
- values,
1049
- ],
1050
- 1,
1051
- )
1052
- world = (c2w[frame_index][:3, :3] @ camera.T).T + c2w[frame_index][:3, 3]
1053
- points.append(world.astype(np.float32))
1054
- if not points:
1055
- return 0.0
1056
- scene_points = np.concatenate(points, 0)
1057
- if up_vec is not None:
1058
- gravity = np.asarray(up_vec, np.float64)
1059
- gravity /= np.linalg.norm(gravity) + 1e-12
1060
- axis = (
1061
- np.array([1.0, 0.0, 0.0])
1062
- if abs(gravity[0]) < 0.9
1063
- else np.array([0.0, 1.0, 0.0])
1064
- )
1065
- u = np.cross(gravity, axis)
1066
- u /= np.linalg.norm(u)
1067
- v = np.cross(gravity, u)
1068
- floor_points = np.stack([scene_points @ u, scene_points @ v], 1)
1069
- else:
1070
- up_axis = int(np.argmin(scene_points.max(0) - scene_points.min(0)))
1071
- floor_axes = [axis for axis in range(3) if axis != up_axis]
1072
- floor_points = scene_points[:, floor_axes]
1073
- lower = np.percentile(floor_points, 0.5, 0)
1074
- upper = np.percentile(floor_points, 99.5, 0)
1075
- floor_points = floor_points[
1076
- (floor_points[:, 0] >= lower[0])
1077
- & (floor_points[:, 0] <= upper[0])
1078
- & (floor_points[:, 1] >= lower[1])
1079
- & (floor_points[:, 1] <= upper[1])
1080
- ]
1081
- if len(floor_points) < 10:
1082
- return 0.0
1083
- try:
1084
- import alphashape
1085
-
1086
- sample = np.random.RandomState(0).choice(
1087
- len(floor_points), min(10000, len(floor_points))
1088
- )
1089
- return round(
1090
- float(alphashape.alphashape(floor_points[sample], alpha=2).area), 1
1091
- )
1092
- except Exception:
1093
- from scipy import ndimage
1094
-
1095
- resolution = 0.10
1096
- rows = ((floor_points[:, 0] - floor_points[:, 0].min()) / resolution).astype(
1097
- int
1098
- )
1099
- columns = ((floor_points[:, 1] - floor_points[:, 1].min()) / resolution).astype(
1100
- int
1101
- )
1102
- grid = np.zeros((rows.max() + 3, columns.max() + 3), np.uint8)
1103
- grid[rows + 1, columns + 1] = 1
1104
- grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1105
- grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1106
- return round(float(grid.sum()) * resolution * resolution, 1)
1107
-
1108
-
1109
- # ---------------------------------------------------------------------------
1110
-
1111
- # ==========================================================================================
1112
- # SPATIAL CODE ASSEMBLY -- the top-level entry point this whole file exists for:
1113
- # build_spatial_code() calls everything above to turn already-computed depth/pose/masks into
1114
- # the final spatial code dict. Room outline + JSON writer. This section was already in
1115
- # geometric.py before the perceptual.py merge; build_spatial_code() below is updated to call
1116
- # the geometry functions above DIRECTLY (no `pl.` prefix -- they're plain local functions now
1117
- # that everything is in one file), same logic, unchanged otherwise.
1118
- # ==========================================================================================
1119
-
1120
-
1121
- def _room_outline(depth, intr, c2w, conf, bu, bv):
1122
- """(Unemitted by explicit format; compact format derives its boundary separately. This
1123
- math is kept intact for reuse.) Room floor-boundary polygon from the SAME grid as
1124
- compute_floor_area: floor points
1125
- projected onto the shared gravity plane (bu, bv), 10cm grid, close 7x7, fill holes,
1126
- largest contour, 0.2m polygon simplification. Same (bu, bv) as objects/camera, so the
1127
- outline, object positions, and floor_area all live in one consistent frame."""
1128
- from scipy import ndimage
1129
-
1130
- pts, stride = [], 8
1131
- for f in range(0, depth.shape[0], 3):
1132
- height, width = depth[f].shape
1133
- ys, xs = np.mgrid[0:height:stride, 0:width:stride]
1134
- ys = ys.ravel()
1135
- xs = xs.ravel()
1136
- z = depth[f][ys, xs]
1137
- ok = np.isfinite(z) & (z > 0)
1138
- if conf is not None:
1139
- ok &= conf[f][ys, xs] >= np.percentile(conf[f], 40)
1140
- ys, xs, z = ys[ok], xs[ok], z[ok]
1141
- if not len(z):
1142
- continue
1143
- intrinsics = intr[f]
1144
- camera_points = np.stack(
1145
- [
1146
- (xs - intrinsics[0, 2]) * z / intrinsics[0, 0],
1147
- (ys - intrinsics[1, 2]) * z / intrinsics[1, 1],
1148
- z,
1149
- ],
1150
- 1,
1151
- )
1152
- pts.append(
1153
- ((c2w[f][:3, :3] @ camera_points.T).T + c2w[f][:3, 3]).astype(np.float32)
1154
- )
1155
- if not pts:
1156
- return []
1157
- world_points = np.concatenate(pts, 0)
1158
- points = np.stack(
1159
- [world_points @ bu, world_points @ bv], 1
1160
- ) # gravity-plane projection (same bu,bv as objects/area)
1161
- lo = np.percentile(points, 0.5, 0)
1162
- hi = np.percentile(points, 99.5, 0)
1163
- points = points[
1164
- (points[:, 0] >= lo[0])
1165
- & (points[:, 0] <= hi[0])
1166
- & (points[:, 1] >= lo[1])
1167
- & (points[:, 1] <= hi[1])
1168
- ]
1169
- if len(points) < 10:
1170
- return []
1171
- res = 0.10
1172
- x0, y0 = points[:, 0].min(), points[:, 1].min()
1173
- ai = ((points[:, 0] - x0) / res).astype(int)
1174
- bi = ((points[:, 1] - y0) / res).astype(int)
1175
- grid = np.zeros((ai.max() + 3, bi.max() + 3), np.uint8)
1176
- grid[ai + 1, bi + 1] = 1
1177
- grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1178
- grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1179
- cs, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1180
- if not cs:
1181
- return []
1182
- poly = cv2.approxPolyDP(max(cs, key=cv2.contourArea), 0.2 / res, True)[:, 0, :]
1183
- # cv2 contour points are (col=bi, row=ai) -> (floor_y, floor_x)
1184
- return [
1185
- {
1186
- "floor_x_meters": round(float((r - 1) * res + x0), 1),
1187
- "floor_y_meters": round(float((c - 1) * res + y0), 1),
1188
- }
1189
- for c, r in poly
1190
- ]
1191
-
1192
-
1193
- def dump_spatial_code(code, path):
1194
- """Save a spatial_code.json exactly like json.dump(code, f, indent=1), EXCEPT
1195
- "appearance order" is written as one compact line instead of one line per entry -- it's a
1196
- single ordered sequence meant to be scanned, not structured data meant to be read field by
1197
- field like the rest of the code. Every writer of spatial_code.json should go through this
1198
- (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.
1199
- """
1200
- body = dict(code)
1201
- ao = body.pop("appearance order", None)
1202
- text = json.dumps(body, indent=1).rstrip()
1203
- if ao is not None:
1204
- assert text.endswith("}")
1205
- text = text[:-1].rstrip() + ',\n "appearance order": ' + json.dumps(ao) + "\n}"
1206
- with open(path, "w") as f:
1207
- f.write(text)
1208
-
1209
-
1210
- # Canonical world-space fallback used by SegVGGT and similar adapters.
1211
- def _canonical_room_gravity(points, cameras=None, iters=300, thr=0.05):
1212
- """Robust UP vector = normal of the RANSAC floor plane, oriented toward the cameras."""
1213
- points = np.asarray(points, np.float64)
1214
- points = points[np.isfinite(points).all(1)]
1215
- if len(points) > 100000:
1216
- points = points[np.random.RandomState(0).choice(len(points), 100000, False)]
1217
- cam = (
1218
- np.asarray(cameras, np.float64).mean(0)
1219
- if cameras is not None and len(cameras)
1220
- else None
1221
- )
1222
- if len(points) < 100:
1223
- ext = (
1224
- np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
1225
- if len(points)
1226
- else np.ones(3)
1227
- )
1228
- ax = int(np.argmin(ext))
1229
- g = np.zeros(3)
1230
- g[ax] = 1.0
1231
- return (g, ax)
1232
- rng = np.random.RandomState(0)
1233
- best = None
1234
- best_score = -1
1235
- for _ in range(iters):
1236
- a, b, c = points[rng.choice(len(points), 3, False)]
1237
- nrm = np.cross(b - a, c - a)
1238
- ln = np.linalg.norm(nrm)
1239
- if ln < 1e-06:
1240
- continue
1241
- nrm /= ln
1242
- d = -nrm @ a
1243
- side = points @ nrm + d
1244
- ninl = int((np.abs(side) < thr).sum())
1245
- if ninl < 50:
1246
- continue
1247
- score = ninl * max(np.mean(side > thr), np.mean(side < -thr))
1248
- if score > best_score:
1249
- best_score = score
1250
- best = (nrm, d)
1251
- if best is None:
1252
- ext = np.percentile(points, 98, 0) - np.percentile(points, 2, 0)
1253
- ax = int(np.argmin(ext))
1254
- g = np.zeros(3)
1255
- g[ax] = 1.0
1256
- return (g, ax)
1257
- nrm, d = best
1258
- if cam is not None and cam @ nrm + d < 0:
1259
- nrm = -nrm
1260
- return (nrm.astype(np.float32), int(np.argmax(np.abs(nrm))))
1261
-
1262
-
1263
- def _canonical_floor_basis(up_vec):
1264
- """Orthonormal floor basis (u, v horizontal; g = up), unchanged from the old file."""
1265
- g = np.asarray(up_vec, np.float64)
1266
- g = g / (np.linalg.norm(g) + 1e-12)
1267
- up_ax = int(np.argmax(np.abs(g)))
1268
- floor_axes = [a for a in range(3) if a != up_ax]
1269
- e0 = np.zeros(3)
1270
- e0[floor_axes[0]] = 1.0
1271
- u = e0 - e0 @ g * g
1272
- u = u / (np.linalg.norm(u) + 1e-12)
1273
- v = np.cross(g, u)
1274
- if v[floor_axes[1]] < 0:
1275
- v = -v
1276
- return (u, v, g)
1277
-
1278
-
1279
- def _canonical_robust_centroid_extent(pts, up_axis=None):
1280
- c = np.median(pts, axis=0)
1281
- centered = pts - c
1282
- if len(centered) > 5000:
1283
- centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
1284
- if up_axis is not None:
1285
- floor_axes = [i for i in range(3) if i != up_axis]
1286
- floor_points = centered[:, floor_axes]
1287
- try:
1288
- _, _, floor_rotation = np.linalg.svd(
1289
- floor_points - floor_points.mean(0), full_matrices=False
1290
- )
1291
- proj_floor = floor_points @ floor_rotation.T
1292
- except np.linalg.LinAlgError:
1293
- proj_floor = floor_points
1294
- proj = np.concatenate([proj_floor, centered[:, up_axis : up_axis + 1]], 1)
1295
- else:
1296
- try:
1297
- _, _, rotation = np.linalg.svd(
1298
- centered - centered.mean(0), full_matrices=False
1299
- )
1300
- proj = centered @ rotation.T
1301
- except np.linalg.LinAlgError:
1302
- proj = centered
1303
- ext = np.maximum(np.percentile(proj, 98, 0) - np.percentile(proj, 2, 0), 0.0)
1304
- dims = np.sort(ext)[::-1]
1305
- return (c.astype(np.float32), float(dims[0]), dims)
1306
-
1307
-
1308
- def _canonical_aabb(pts):
1309
- return (np.percentile(pts, 2, 0), np.percentile(pts, 98, 0))
1310
-
1311
-
1312
- def _canonical_merge_by_box_overlap(insts, up_axis=None):
1313
- """Parameter-free 3D re-identification with temporal exclusion, unchanged."""
1314
- n = len(insts)
1315
- if n <= 1:
1316
- return insts
1317
- lo = np.stack([_canonical_aabb(i["pts"])[0] for i in insts])
1318
- hi = np.stack([_canonical_aabb(i["pts"])[1] for i in insts])
1319
- cents = np.stack([i["centroid"] for i in insts])
1320
- overlap = (hi[:, None] >= lo[None]).all(-1) & (hi[None] >= lo[:, None]).all(-1)
1321
- ins = (cents[:, None] >= lo[None]).all(-1) & (cents[:, None] <= hi[None]).all(-1)
1322
- match = overlap | ins | ins.T
1323
- groups = [
1324
- {"members": [i], "frames": set(insts[i].get("frames", ()))} for i in range(n)
1325
- ]
1326
- changed = True
1327
- while changed:
1328
- changed = False
1329
- for a in range(len(groups)):
1330
- for b in range(a + 1, len(groups)):
1331
- if groups[a]["frames"] & groups[b]["frames"]:
1332
- continue
1333
- if match[np.ix_(groups[a]["members"], groups[b]["members"])].any():
1334
- groups[a]["members"] += groups[b]["members"]
1335
- groups[a]["frames"] |= groups[b]["frames"]
1336
- groups.pop(b)
1337
- changed = True
1338
- break
1339
- if changed:
1340
- break
1341
- out = []
1342
- for g in groups:
1343
- ii = g["members"]
1344
- pts = np.concatenate([insts[k]["pts"] for k in ii], 0)
1345
- best = max((insts[k]["best_pts"] for k in ii), key=len)
1346
- c, size, dims = _canonical_robust_centroid_extent(best, up_axis)
1347
- confs = [insts[k].get("conf") for k in ii]
1348
- conf = (
1349
- np.concatenate([x for x in confs if x is not None], 0)
1350
- if any((x is not None for x in confs))
1351
- else None
1352
- )
1353
- out.append(
1354
- {
1355
- "centroid": c,
1356
- "size": size,
1357
- "dims": dims,
1358
- "pts": pts,
1359
- "best_pts": best,
1360
- "observations": [
1361
- observation
1362
- for k in ii
1363
- for observation in insts[k].get("observations", [insts[k]["pts"]])
1364
- ],
1365
- "conf": conf,
1366
- "frames": g["frames"],
1367
- "nframes": len(g["frames"]),
1368
- "n": sum((insts[k]["n"] for k in ii)),
1369
- "first_time": min((insts[k]["first_time"] for k in ii)),
1370
- }
1371
- )
1372
- return out
1373
-
1374
-
1375
- def _canonical_sor(pts, k=16, std=2.0, cap=4000):
1376
- from scipy.spatial import cKDTree
1377
-
1378
- if len(pts) < k + 2:
1379
- return pts
1380
- points = (
1381
- pts
1382
- if len(pts) <= cap
1383
- else pts[np.random.RandomState(0).choice(len(pts), cap, False)]
1384
- )
1385
- d, _ = cKDTree(points).query(points, k=k + 1, workers=KD_WORKERS)
1386
- md = d[:, 1:].mean(1)
1387
- return points[md <= md.mean() + std * md.std()]
1388
-
1389
-
1390
- def _canonical_clean(inst, cap=4000):
1391
- if inst.get("_cleanpts") is not None:
1392
- return inst["_cleanpts"]
1393
- pts, conf = (inst["pts"], inst.get("conf"))
1394
- if len(pts) > cap:
1395
- idx = np.random.RandomState(0).choice(len(pts), cap, False)
1396
- pts = pts[idx]
1397
- if conf is not None:
1398
- conf = conf[idx]
1399
- if conf is not None and len(conf) > 20:
1400
- keep = conf >= np.median(conf)
1401
- if keep.sum() >= 10:
1402
- pts = pts[keep]
1403
- inst["_cleanpts"] = _canonical_sor(pts, cap=cap)
1404
- return inst["_cleanpts"]
1405
-
1406
-
1407
- # ==========================================================================================
1408
- # COMPACT SPATIAL CODE -- reusable geometry and time primitives, with no derived answers.
1409
- # ==========================================================================================
1410
-
1411
-
1412
- COMPACT_SPATIAL_CODE_SCHEMA = {
1413
- "objects": {
1414
- "<object class>": [
1415
- {
1416
- "3D oriented bounding box": {
1417
- "3D oriented bounding box center coordinates": {
1418
- "components": ["x", "y", "height above floor"],
1419
- "unit": "meters",
1420
- "description": (
1421
- "center of the 3D oriented bounding box in the shared room "
1422
- "coordinate system"
1423
- ),
1424
- },
1425
- "3D oriented bounding box dimensions": {
1426
- "components": ["dimension 1", "dimension 2", "dimension 3"],
1427
- "unit": "meters",
1428
- "description": (
1429
- "full lengths of the 3D oriented bounding box along the "
1430
- "corresponding orientation unit vectors"
1431
- ),
1432
- },
1433
- "3D oriented bounding box orientation unit vectors": {
1434
- "components": [
1435
- ["x", "y", "height"],
1436
- ["x", "y", "height"],
1437
- ["x", "y", "height"],
1438
- ],
1439
- "unit": None,
1440
- "description": (
1441
- "three perpendicular directions corresponding in order to the "
1442
- "three 3D oriented bounding box dimensions"
1443
- ),
1444
- },
1445
- },
1446
- "first visible time": {
1447
- "unit": "seconds",
1448
- "description": (
1449
- "earliest time at which this object instance is visibly observed"
1450
- ),
1451
- },
1452
- }
1453
- ]
1454
- },
1455
- "room": {
1456
- "floor boundary polygons": [
1457
- {
1458
- "outer boundary coordinates": {
1459
- "components": [["x", "y"], ["x", "y"]],
1460
- "unit": "meters",
1461
- "description": "ordered vertices enclosing one floor region",
1462
- },
1463
- "interior hole boundary coordinates": {
1464
- "components": [[["x", "y"], ["x", "y"]]],
1465
- "unit": "meters",
1466
- "description": (
1467
- "ordered boundaries enclosing regions excluded from the floor area"
1468
- ),
1469
- },
1470
- }
1471
- ]
1472
- },
1473
- }
1474
-
1475
-
1476
- def _rounded_list(values):
1477
- """Round one numeric vector to stable JSON values without negative zero."""
1478
- return [0.0 if (value := round(float(x), 2)) == 0 else value for x in values]
1479
-
1480
-
1481
- def _weighted_quantile(values, weights, quantile):
1482
- """Return one deterministic weighted quantile for observation consensus."""
1483
- values = np.asarray(values, np.float64)
1484
- weights = np.asarray(weights, np.float64)
1485
- order = np.argsort(values)
1486
- values, weights = values[order], weights[order]
1487
- cumulative = np.cumsum(weights) - 0.5 * weights
1488
- cumulative /= weights.sum()
1489
- return float(np.interp(quantile, cumulative, values))
1490
-
1491
-
1492
- def _compact_oriented_box(instance, u, v, g, floor_level):
1493
- """Fit one floor-aligned OBB from the same per-instance math as the reference code."""
1494
- center = np.asarray(instance["centroid"], np.float64)
1495
- points = np.asarray(instance["best_pts"], np.float64)
1496
- room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1)
1497
- centered = room_points[:, :2] - np.median(room_points[:, :2], axis=0)
1498
- if len(centered) > 5000:
1499
- centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)]
1500
- try:
1501
- _, _, rotation = np.linalg.svd(
1502
- centered - centered.mean(axis=0), full_matrices=False
1503
- )
1504
- except np.linalg.LinAlgError:
1505
- rotation = np.eye(2)
1506
- first = rotation[0]
1507
- dominant = int(np.argmax(np.abs(first)))
1508
- if first[dominant] < 0:
1509
- first = -first
1510
- second = np.array([-first[1], first[0]])
1511
- orientation = np.array(
1512
- [[first[0], first[1], 0.0], [second[0], second[1], 0.0], [0.0, 0.0, 1.0]]
1513
- )
1514
- box_center = np.array([center @ u, center @ v, center @ g - floor_level])
1515
- box_dimensions = np.asarray(instance["dims"], np.float64)
1516
- return {
1517
- "3D oriented bounding box center coordinates": _rounded_list(box_center),
1518
- "3D oriented bounding box dimensions": _rounded_list(box_dimensions),
1519
- "3D oriented bounding box orientation unit vectors": [
1520
- _rounded_list(axis) for axis in orientation
1521
- ],
1522
- }
1523
-
1524
-
1525
- def _contour_coordinates(contour, x_origin, y_origin, resolution):
1526
- """Translate one OpenCV grid contour to ordered shared-room coordinates."""
1527
- return [
1528
- _rounded_list(
1529
- [x_origin + (row - 1) * resolution, y_origin + (column - 1) * resolution]
1530
- )
1531
- for column, row in contour[:, 0, :]
1532
- ]
1533
-
1534
-
1535
- def _compact_scene_points(scene):
1536
- """Return the same dense floor-support sample used by explicit room-area math."""
1537
- raw_inputs = scene.get("raw_inputs")
1538
- if raw_inputs is None:
1539
- return scene["scene_pts"]
1540
- depth = raw_inputs["depth"]
1541
- intrinsics = raw_inputs["intr"]
1542
- poses = raw_inputs["c2w"]
1543
- confidence = raw_inputs.get("conf")
1544
- points = []
1545
- for frame_index in range(len(depth)):
1546
- height, width = depth[frame_index].shape
1547
- rows, columns = np.mgrid[0:height:8, 0:width:8]
1548
- rows, columns = rows.ravel(), columns.ravel()
1549
- values = depth[frame_index][rows, columns]
1550
- keep = np.isfinite(values) & (values > 0)
1551
- if confidence is not None:
1552
- threshold = np.percentile(confidence[frame_index], 40)
1553
- keep &= confidence[frame_index][rows, columns] >= threshold
1554
- rows, columns, values = rows[keep], columns[keep], values[keep]
1555
- if not len(values):
1556
- continue
1557
- current = intrinsics[frame_index]
1558
- camera = np.stack(
1559
- [
1560
- (columns - current[0, 2]) * values / current[0, 0],
1561
- (rows - current[1, 2]) * values / current[1, 1],
1562
- values,
1563
- ],
1564
- axis=1,
1565
- )
1566
- world = poses[frame_index][:3, :3] @ camera.T
1567
- points.append((world.T + poses[frame_index][:3, 3]).astype(np.float32))
1568
- return np.concatenate(points, axis=0) if points else scene["scene_pts"]
1569
-
1570
-
1571
- def _compact_floor_boundary_polygons(points, u, v, object_points=None):
1572
- """Extract the reference room outline as a compact floor-boundary polygon."""
1573
- from scipy import ndimage
1574
-
1575
- points = np.asarray(points, np.float64)
1576
- floor_points = np.stack([points @ u, points @ v], axis=1)
1577
- floor_points = floor_points[np.isfinite(floor_points).all(axis=1)]
1578
- if len(floor_points) < 3:
1579
- return []
1580
- lower = np.percentile(floor_points, 0.5, axis=0)
1581
- upper = np.percentile(floor_points, 99.5, axis=0)
1582
- floor_points = floor_points[
1583
- (floor_points[:, 0] >= lower[0])
1584
- & (floor_points[:, 0] <= upper[0])
1585
- & (floor_points[:, 1] >= lower[1])
1586
- & (floor_points[:, 1] <= upper[1])
1587
- ]
1588
- if len(floor_points) < 3:
1589
- return []
1590
- resolution = 0.1
1591
- x_origin, y_origin = floor_points.min(axis=0)
1592
- x_max, y_max = floor_points.max(axis=0)
1593
- row_count = int((x_max - x_origin) / resolution) + 3
1594
- column_count = int((y_max - y_origin) / resolution) + 3
1595
- grid = np.zeros((row_count, column_count), np.uint8)
1596
- rows = ((floor_points[:, 0] - x_origin) / resolution).astype(int)
1597
- columns = ((floor_points[:, 1] - y_origin) / resolution).astype(int)
1598
- grid[rows + 1, columns + 1] = 1
1599
- grid = cv2.morphologyEx(grid, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
1600
- grid = ndimage.binary_fill_holes(grid).astype(np.uint8)
1601
- contours, _ = cv2.findContours(grid, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1602
- if not contours:
1603
- return []
1604
- contour = cv2.approxPolyDP(
1605
- max(contours, key=cv2.contourArea), 0.2 / resolution, True
1606
- )
1607
- return [
1608
- {
1609
- "outer boundary coordinates": _contour_coordinates(
1610
- contour, x_origin, y_origin, resolution
1611
- ),
1612
- "interior hole boundary coordinates": [],
1613
- }
1614
- ]
1615
-
1616
-
1617
- def _compact_duplicate_groups(instances):
1618
- """Group near-identical co-visible boxes that represent duplicate mask tracks."""
1619
- count = len(instances)
1620
- parent = list(range(count))
1621
-
1622
- def root(index):
1623
- while parent[index] != index:
1624
- parent[index] = parent[parent[index]]
1625
- index = parent[index]
1626
- return index
1627
-
1628
- def union(first, second):
1629
- first, second = root(first), root(second)
1630
- if first != second:
1631
- parent[second] = first
1632
-
1633
- bounds = [_canonical_aabb(_canonical_clean(instance)) for instance in instances]
1634
- for first in range(count):
1635
- lower_a, upper_a = bounds[first]
1636
- extent_a = np.maximum(upper_a - lower_a, 1e-6)
1637
- volume_a = float(np.prod(extent_a))
1638
- for second in range(first + 1, count):
1639
- lower_b, upper_b = bounds[second]
1640
- extent_b = np.maximum(upper_b - lower_b, 1e-6)
1641
- volume_b = float(np.prod(extent_b))
1642
- intersection = np.maximum(
1643
- np.minimum(upper_a, upper_b) - np.maximum(lower_a, lower_b), 0.0
1644
- )
1645
- overlap = float(np.prod(intersection)) / min(volume_a, volume_b)
1646
- if overlap >= 0.8:
1647
- union(first, second)
1648
- groups = {}
1649
- for index in range(count):
1650
- groups.setdefault(root(index), []).append(index)
1651
- return list(groups.values())
1652
-
1653
-
1654
- def _combine_compact_instances(instances, members, up_axis):
1655
- """Combine one duplicate group while retaining all evidence and earliest timing."""
1656
- selected = [instances[index] for index in members]
1657
- points = np.concatenate([instance["pts"] for instance in selected], axis=0)
1658
- best = max((instance["best_pts"] for instance in selected), key=len)
1659
- confidence = [instance.get("conf") for instance in selected]
1660
- confidence = (
1661
- np.concatenate(confidence, axis=0)
1662
- if all(value is not None for value in confidence)
1663
- else None
1664
- )
1665
- centroid, size, dimensions = _canonical_robust_centroid_extent(points, up_axis)
1666
- frames = set().union(*(set(instance.get("frames", ())) for instance in selected))
1667
- return {
1668
- "centroid": centroid,
1669
- "size": size,
1670
- "dims": dimensions,
1671
- "first_time": min(instance["first_time"] for instance in selected),
1672
- "pts": points,
1673
- "conf": confidence,
1674
- "best_pts": best,
1675
- "observations": [
1676
- observation
1677
- for instance in selected
1678
- for observation in instance.get("observations", [instance["pts"]])
1679
- ],
1680
- "frames": frames,
1681
- "n": sum(instance.get("n", len(instance["pts"])) for instance in selected),
1682
- "nframes": len(frames),
1683
- "oids": [oid for instance in selected for oid in instance.get("oids", [])],
1684
- }
1685
-
1686
-
1687
- def _compact_instance_evidence(instance):
1688
- """Rank one physical-instance hypothesis by persistence and geometric support."""
1689
- observations = instance.get("observations", [instance["pts"]])
1690
- observed_points = np.array([len(observation) for observation in observations])
1691
- return (
1692
- instance.get("nframes", len(instance.get("frames", ()))),
1693
- len(observations),
1694
- float(np.median(observed_points)) if len(observed_points) else 0.0,
1695
- instance.get("n", len(instance["pts"])),
1696
- )
1697
-
1698
-
1699
- def _consolidate_compact_instances(instances, stats, up_axis):
1700
- """Suppress duplicate tracks and retain the strongest co-visible instance set."""
1701
- consolidated = {}
1702
- for class_name, items in instances.items():
1703
- combined = [
1704
- _combine_compact_instances(items, members, up_axis)
1705
- for members in _compact_duplicate_groups(items)
1706
- ]
1707
- peak = int(stats.get(class_name, {}).get("peak", 0))
1708
- limit = min(len(combined), max(peak, 1))
1709
- ranked = sorted(combined, key=_compact_instance_evidence, reverse=True)
1710
- retained = ranked[:limit]
1711
- for fragment in ranked[limit:]:
1712
- nearest = min(
1713
- retained,
1714
- key=lambda instance: np.linalg.norm(
1715
- instance["centroid"] - fragment["centroid"]
1716
- ),
1717
- )
1718
- nearest["first_time"] = min(nearest["first_time"], fragment["first_time"])
1719
- consolidated[class_name] = retained
1720
- return consolidated
1721
-
1722
-
1723
- def _compact_instances(scene, up_axis):
1724
- """Return consolidated physical instances for raw or canonical adapter geometry."""
1725
- raw_inputs = scene.get("raw_inputs")
1726
- if raw_inputs is not None:
1727
- instances, stats = build_instances(
1728
- raw_inputs["per"],
1729
- raw_inputs["depth"],
1730
- raw_inputs["intr"],
1731
- raw_inputs["c2w"],
1732
- raw_inputs.get("conf"),
1733
- raw_inputs["ftimes"],
1734
- up_axis=up_axis,
1735
- )
1736
- else:
1737
- instances = {}
1738
- stats = {
1739
- class_name: dict(values) for class_name, values in scene["stats"].items()
1740
- }
1741
- for class_name, items in scene["instances"].items():
1742
- measured = []
1743
- for item in items:
1744
- points = _canonical_clean(item)
1745
- if not len(points):
1746
- points = item["pts"]
1747
- centroid, size, dimensions = _canonical_robust_centroid_extent(
1748
- points, up_axis
1749
- )
1750
- record = dict(item)
1751
- record.update({"centroid": centroid, "size": size, "dims": dimensions})
1752
- measured.append(record)
1753
- instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis)
1754
- for class_name, items in instances.items():
1755
- stats.setdefault(class_name, {})
1756
- stats[class_name]["merged"] = len(items)
1757
- return instances, stats
1758
-
1759
-
1760
- def instance_source_track_ids(scene):
1761
- """Return {emitted_class_name: [oids_for_instance_1, oids_for_instance_2, ...]},
1762
- one ordered list of raw SAM3 masklet ids per FINAL consolidated instance -- in
1763
- EXACTLY the rank order build_compact_spatial_code() emits instances in (same
1764
- (n, nframes)-descending sort, same class-name aliasing), so index i here IS the
1765
- "<class> {i+1}" instance id the strong correspondence overlay stamps. A raw-only
1766
- lookup: reruns nothing but the consolidation build_compact_spatial_code() already
1767
- does, just exposing the "oids" field that pipeline discards before emission (the
1768
- on-disk schema never carries SAM3 ids -- this function is the only place that does).
1769
- """
1770
- alias = {"coat hanger": "coat rack"}
1771
- raw_inputs = scene.get("raw_inputs")
1772
- if raw_inputs is None:
1773
- raise ValueError(
1774
- "instance_source_track_ids needs raw depth/intr/c2w inputs; this geometry "
1775
- "cache carries only canonical points (no SAM3 track ids to recover)"
1776
- )
1777
- up_vec, up_ax = room_gravity(
1778
- raw_inputs["depth"],
1779
- raw_inputs["intr"],
1780
- raw_inputs["c2w"],
1781
- raw_inputs.get("conf"),
1782
- )
1783
- instances, _stats = _compact_instances(scene, up_ax)
1784
- out = {}
1785
- for class_name, items in instances.items():
1786
- emitted_name = alias.get(class_name, class_name)
1787
- ranked = sorted(
1788
- items,
1789
- key=lambda item: (item.get("n", 0), item.get("nframes", 0)),
1790
- reverse=True,
1791
- )
1792
- out.setdefault(emitted_name, []).extend(item.get("oids", []) for item in ranked)
1793
- return out
1794
-
1795
-
1796
- def build_compact_spatial_code(scene):
1797
- """Build reusable OBB, visibility-time, and floor-boundary primitives."""
1798
- alias = {"coat hanger": "coat rack"}
1799
- raw_inputs = scene.get("raw_inputs")
1800
- if raw_inputs is not None:
1801
- up_vec, up_ax = room_gravity(
1802
- raw_inputs["depth"],
1803
- raw_inputs["intr"],
1804
- raw_inputs["c2w"],
1805
- raw_inputs.get("conf"),
1806
- )
1807
- u, v, g = _floor_basis(up_vec)
1808
- else:
1809
- up_vec, up_ax = _canonical_room_gravity(
1810
- scene["scene_pts"], scene.get("cameras")
1811
- )
1812
- u, v, g = _canonical_floor_basis(up_vec)
1813
- instances, stats = _compact_instances(scene, up_ax)
1814
- all_points = np.concatenate(
1815
- [item["pts"] for values in instances.values() for item in values], axis=0
1816
- )
1817
- floor_level = _floor_level(all_points, g)
1818
- objects = {}
1819
- for class_name, items in instances.items():
1820
- emitted_name = alias.get(class_name, class_name)
1821
- ranked = sorted(
1822
- items,
1823
- key=lambda item: (item.get("n", 0), item.get("nframes", 0)),
1824
- reverse=True,
1825
- )
1826
- count = int(stats.get(class_name, {}).get("peak", 0))
1827
- ranked = ranked[: max(count, 1)]
1828
- objects.setdefault(emitted_name, []).extend(
1829
- {
1830
- "3D oriented bounding box": _compact_oriented_box(
1831
- item, u, v, g, floor_level
1832
- ),
1833
- "first visible time": round(float(item["first_time"]), 2),
1834
- }
1835
- for item in ranked
1836
- )
1837
- code = {
1838
- "objects": objects,
1839
- "room": {
1840
- "floor boundary polygons": _compact_floor_boundary_polygons(
1841
- _compact_scene_points(scene), u, v
1842
- )
1843
- },
1844
- }
1845
- return code, instances, stats, up_ax, up_vec, None
1846
-
1847
-
1848
- # ==========================================================================================
1849
- # EXPLICIT SPATIAL CODE -- a strict derivation of the compact schema above. Every object
1850
- # position/dimension/count/appearance-order value is read directly off compact's own oriented
1851
- # boxes and "first visible time" (a direct subset, not independently recomputed); the distance
1852
- # table is the one thing compact never stores, so it is computed here purely from compact's own
1853
- # 3D oriented boxes -- exact surface-to-surface separation via bounded least squares (same
1854
- # convex, closed-form-adjacent optimization symbolic/adapters.py's solver-side derivation
1855
- # already used for compact input, now the ACTUAL on-disk construction for explicit too, so the
1856
- # two schemas can never independently disagree about the same scene's geometry).
1857
- # ==========================================================================================
1858
-
1859
-
1860
- EXPLICIT_SPATIAL_CODE_SCHEMA = {
1861
- "objects": {
1862
- "<object class>": {
1863
- "count": {
1864
- "unit": None,
1865
- "description": (
1866
- "number of instances of this class in the compact spatial code "
1867
- "(that schema's per-class oriented-box list length)"
1868
- ),
1869
- },
1870
- "instances": [
1871
- {
1872
- "position": {
1873
- "x coordinate": {
1874
- "unit": "meters",
1875
- "description": (
1876
- "x coordinate of this instance's compact 3D oriented "
1877
- "bounding box center"
1878
- ),
1879
- },
1880
- "y coordinate": {
1881
- "unit": "meters",
1882
- "description": (
1883
- "y coordinate of this instance's compact 3D oriented "
1884
- "bounding box center"
1885
- ),
1886
- },
1887
- "height above floor": {
1888
- "unit": "meters",
1889
- "description": (
1890
- "height coordinate of this instance's compact 3D oriented "
1891
- "bounding box center"
1892
- ),
1893
- },
1894
- },
1895
- "longest dimension": {
1896
- "unit": "meters",
1897
- "description": (
1898
- "longest of this instance's compact 3D oriented bounding box "
1899
- "dimensions"
1900
- ),
1901
- },
1902
- }
1903
- ],
1904
- }
1905
- },
1906
- "room": {
1907
- "floor area": {
1908
- "unit": "square meters",
1909
- "description": (
1910
- "shoelace area of the compact spatial code's floor boundary polygons, "
1911
- "with every interior hole subtracted"
1912
- ),
1913
- }
1914
- },
1915
- "closest classes distance meters from": {
1916
- "<object class>": {
1917
- "<other object class>": {
1918
- "distance": {
1919
- "unit": "meters",
1920
- "description": (
1921
- "estimated distance in meters between an object of this class "
1922
- "and an object of the other class"
1923
- ),
1924
- },
1925
- "closeness rank": {
1926
- "unit": None,
1927
- "description": (
1928
- "1 = the nearest other class to this one, 2 = second-nearest, "
1929
- "and so on; ranked by nearest-instance proximity, so use the "
1930
- "rank (not the distance values) to compare which class is "
1931
- "closest"
1932
- ),
1933
- },
1934
- }
1935
- }
1936
- },
1937
- "appearance order": {
1938
- "unit": None,
1939
- "description": (
1940
- "class names ordered by earliest compact 'first visible time' across all of "
1941
- "that class's instances"
1942
- ),
1943
- },
1944
- }
1945
-
1946
-
1947
- def _compact_box_distance(box_a, box_b):
1948
- """Return the true minimum Euclidean separation of two compact 3D oriented boxes.
1949
-
1950
- Verbatim derivation from symbolic/adapters.py's oriented_box_distance(): the six box
1951
- coefficients form one convex bounded least-squares problem, solved exactly by BVLS -- no
1952
- center, corner, or longest-dimension shortcut, so touching/intersecting boxes return zero.
1953
-
1954
- Orientation vectors are renormalized to unit length before use, exactly like
1955
- symbolic/adapters.py's _oriented_box() -- compact's on-disk vectors are rounded to 2
1956
- decimals, so they are no longer *exactly* unit length, and the matrix below implicitly
1957
- assumes they are (each column is dimension/2 along that axis). Skipping this step is a
1958
- real source of error, not just a rounding artifact: it measurably shifted computed
1959
- distances in testing (up to ~0.01 m on real scenes), and would make explicit silently
1960
- disagree with what the solver derives from the identical compact box at read time.
1961
- """
1962
- from scipy.optimize import lsq_linear
1963
-
1964
- center_a = np.asarray(
1965
- box_a["3D oriented bounding box center coordinates"], np.float64
1966
- )
1967
- dimensions_a = np.asarray(box_a["3D oriented bounding box dimensions"], np.float64)
1968
- orientation_a = np.asarray(
1969
- box_a["3D oriented bounding box orientation unit vectors"], np.float64
1970
- )
1971
- orientation_a = orientation_a / np.linalg.norm(orientation_a, axis=1, keepdims=True)
1972
- center_b = np.asarray(
1973
- box_b["3D oriented bounding box center coordinates"], np.float64
1974
- )
1975
- dimensions_b = np.asarray(box_b["3D oriented bounding box dimensions"], np.float64)
1976
- orientation_b = np.asarray(
1977
- box_b["3D oriented bounding box orientation unit vectors"], np.float64
1978
- )
1979
- orientation_b = orientation_b / np.linalg.norm(orientation_b, axis=1, keepdims=True)
1980
- matrix = np.column_stack(
1981
- [
1982
- *(dimensions_a[index] * orientation_a[index] / 2 for index in range(3)),
1983
- *(-dimensions_b[index] * orientation_b[index] / 2 for index in range(3)),
1984
- ]
1985
- )
1986
- result = lsq_linear(
1987
- matrix,
1988
- center_b - center_a,
1989
- bounds=(-1, 1),
1990
- method="bvls",
1991
- lsq_solver="exact",
1992
- tol=1e-12,
1993
- max_iter=200,
1994
- )
1995
- if not result.success:
1996
- raise RuntimeError(
1997
- f"oriented-box distance optimization failed: {result.message}"
1998
- )
1999
- distance = float(np.linalg.norm(matrix @ result.x + center_a - center_b))
2000
- return 0.0 if distance < 1e-10 else distance
2001
-
2002
-
2003
- def _compact_class_distance(instances_a, instances_b):
2004
- """Return the minimum compact oriented-box distance across every cross-class instance pair."""
2005
- return min(
2006
- _compact_box_distance(
2007
- a["3D oriented bounding box"], b["3D oriented bounding box"]
2008
- )
2009
- for a in instances_a
2010
- for b in instances_b
2011
- )
2012
-
2013
-
2014
- def _primary_instance_distance_floor(instances_a, instances_b):
2015
- """A sphere-approximation floor on the two classes' PRIMARY (instance[0]) distance:
2016
- 3D center-to-center distance minus each primary box's longest dimension / 2, floored
2017
- at 0. Mirrors symbolic/solver.py's _primary_instance_distance_estimate exactly (the
2018
- same correction, applied at ENCODING time so the table value a reader looks up
2019
- already carries it -- see _corrected_class_distance below)."""
2020
- box_a = instances_a[0]["3D oriented bounding box"]
2021
- box_b = instances_b[0]["3D oriented bounding box"]
2022
- center_a = box_a["3D oriented bounding box center coordinates"]
2023
- center_b = box_b["3D oriented bounding box center coordinates"]
2024
- center_distance = (
2025
- sum((float(a) - float(b)) ** 2 for a, b in zip(center_a, center_b)) ** 0.5
2026
- )
2027
- radius_a = max(box_a["3D oriented bounding box dimensions"]) / 2
2028
- radius_b = max(box_b["3D oriented bounding box dimensions"]) / 2
2029
- return max(0.0, center_distance - (radius_a + radius_b))
2030
-
2031
-
2032
- def _corrected_class_distance(instances_a, instances_b):
2033
- """max(min-across-pairs surface distance, primary-instance sphere floor) -- the
2034
- combination symbolic/solver.py applies at ANSWER time for ABSOLUTE-distance
2035
- questions. TRIED AND REVERTED as the table's stored value (2026-07-25, see
2036
- preregistration.md): baking it in re-derived the closeness RANKS from
2037
- corrected distances, and closest-of-class ranking is exactly where the raw
2038
- min-across-instances is the semantically correct quantity -- solver relative-
2039
- distance accuracy fell 59.2 -> 47.5 on real perceived codes and the VLM pilot
2040
- dropped in the same direction.
2041
-
2042
- REINSTATED (2026-07-25, second amendment, see preregistration.md) as the
2043
- table's PRINTED distance only, with the fix the first attempt lacked: closeness
2044
- ranks stay computed from the raw min-across-instances distance (the correct
2045
- closest-of-class quantity), and the solver's relative-distance answer reads the
2046
- rank field rather than comparing printed values. The printed value IS the solver's
2047
- absolute-distance answer, making abs-distance a pure lookup for any reader."""
2048
- return max(
2049
- _compact_class_distance(instances_a, instances_b),
2050
- _primary_instance_distance_floor(instances_a, instances_b),
2051
- )
2052
-
2053
-
2054
- def _compact_polygon_area(coordinates):
2055
- """Return the unsigned shoelace area of one ordered compact floor-boundary polygon."""
2056
- if len(coordinates) < 3:
2057
- return 0.0
2058
- return abs(
2059
- sum(
2060
- coordinates[index][0] * coordinates[(index + 1) % len(coordinates)][1]
2061
- - coordinates[(index + 1) % len(coordinates)][0] * coordinates[index][1]
2062
- for index in range(len(coordinates))
2063
- )
2064
- / 2
2065
- )
2066
-
2067
-
2068
- def _compact_room_floor_area(polygons):
2069
- """Sum outer areas and subtract every interior hole across compact's floor regions."""
2070
- area = 0.0
2071
- for polygon in polygons:
2072
- area += _compact_polygon_area(polygon.get("outer boundary coordinates", []))
2073
- area -= sum(
2074
- _compact_polygon_area(hole)
2075
- for hole in polygon.get("interior hole boundary coordinates", [])
2076
- )
2077
- return max(0.0, area)
2078
-
2079
-
2080
- def _compact_box_axis_bounds(box):
2081
- center = np.asarray(box["3D oriented bounding box center coordinates"], np.float64)
2082
- dimensions = np.asarray(box["3D oriented bounding box dimensions"], np.float64)
2083
- orientation = np.asarray(
2084
- box["3D oriented bounding box orientation unit vectors"], np.float64
2085
- )
2086
- orientation = orientation / np.linalg.norm(orientation, axis=1, keepdims=True)
2087
- offsets = []
2088
- for sx in (-1.0, 1.0):
2089
- for sy in (-1.0, 1.0):
2090
- for sz in (-1.0, 1.0):
2091
- offsets.append(
2092
- sx * dimensions[0] * orientation[0] / 2
2093
- + sy * dimensions[1] * orientation[1] / 2
2094
- + sz * dimensions[2] * orientation[2] / 2
2095
- )
2096
- corners = center + np.asarray(offsets)
2097
- return [
2098
- [
2099
- round(float(corners[:, axis].min()), 2),
2100
- round(float(corners[:, axis].max()), 2),
2101
- ]
2102
- for axis in range(3)
2103
- ]
2104
-
2105
-
2106
- def _compact_outline_for_v2(compact_code):
2107
- polygons = compact_code.get("room", {}).get("floor boundary polygons", [])
2108
- if not polygons:
2109
- return []
2110
- outline = []
2111
- for x, y in polygons[0].get("outer boundary coordinates", []):
2112
- outline.append(
2113
- {"floor_x_meters": round(float(x), 1), "floor_y_meters": round(float(y), 1)}
2114
- )
2115
- return outline
2116
-
2117
-
2118
- def _explicit_from_compact(compact_code):
2119
- """Derive a V2 explicit spatial code from an already-built compact spatial code.
2120
-
2121
- This is used for canonical adapter geometry and ground truth. It mirrors the V2 envelope
2122
- used by the raw encoder path: no embedded legend, numeric closest-class table, V2 room
2123
- keys, and compact "appearance order".
2124
- """
2125
- compact_objects = compact_code["objects"]
2126
-
2127
- objects = {}
2128
- first_visible = {}
2129
- for class_name, items in compact_objects.items():
2130
- rendered = []
2131
- for item in items:
2132
- box = item["3D oriented bounding box"]
2133
- center = box["3D oriented bounding box center coordinates"]
2134
- dimensions = box["3D oriented bounding box dimensions"]
2135
- bounds = _compact_box_axis_bounds(box)
2136
- rendered.append(
2137
- {
2138
- "position": {
2139
- "floor_x_meters": round(float(center[0]), 2),
2140
- "floor_y_meters": round(float(center[1]), 2),
2141
- "height_above_floor_meters": round(float(center[2]), 2),
2142
- },
2143
- "longest_dimension_meters": round(float(max(dimensions)), 2),
2144
- "bounding_box": {
2145
- "floor_x_meters": bounds[0],
2146
- "floor_y_meters": bounds[1],
2147
- "height_above_floor_meters": bounds[2],
2148
- },
2149
- "dimensions_meters": [
2150
- round(float(value), 2) for value in dimensions
2151
- ],
2152
- }
2153
- )
2154
- time = item["first visible time"]
2155
- if time is not None:
2156
- first_visible[class_name] = min(
2157
- first_visible.get(class_name, float("inf")), float(time)
2158
- )
2159
- objects[class_name] = {"count": len(items), "instances": rendered}
2160
-
2161
- classes = [name for name, items in compact_objects.items() if items]
2162
- raw_distances = {class_name: {} for class_name in classes}
2163
- printed_distances = {class_name: {} for class_name in classes}
2164
- for index, class_name in enumerate(classes):
2165
- for other in classes[index + 1 :]:
2166
- raw = _compact_class_distance(
2167
- compact_objects[class_name], compact_objects[other]
2168
- )
2169
- printed = _corrected_class_distance(
2170
- compact_objects[class_name], compact_objects[other]
2171
- )
2172
- raw_distances[class_name][other] = raw
2173
- raw_distances[other][class_name] = raw
2174
- printed_distances[class_name][other] = printed
2175
- printed_distances[other][class_name] = printed
2176
- closest = {}
2177
- for class_name, distances in raw_distances.items():
2178
- ranked = sorted(distances.items(), key=lambda item: (item[1], item[0]))
2179
- closest[class_name] = {
2180
- other: {
2181
- "closeness_rank": rank + 1,
2182
- "distance_meters": round(printed_distances[class_name][other], 2),
2183
- }
2184
- for rank, (other, _raw) in enumerate(ranked)
2185
- }
2186
-
2187
- floor_area = round(
2188
- _compact_room_floor_area(
2189
- compact_code["room"].get("floor boundary polygons", [])
2190
- ),
2191
- 1,
2192
- )
2193
-
2194
- return {
2195
- "objects": objects,
2196
- "room": {
2197
- "outline": _compact_outline_for_v2(compact_code),
2198
- "floor_area_square_meters": floor_area,
2199
- },
2200
- "closest_classes_from": closest,
2201
- "appearance order": sorted(
2202
- classes, key=lambda name: first_visible.get(name, float("inf"))
2203
- ),
2204
- }, floor_area
2205
-
2206
-
2207
- def _build_reference_v2_spatial_code(raw_inputs):
2208
- """Build the raw encoder spatial code exactly like the reference V2 branch."""
2209
- alias = {"coat hanger": "coat rack"}
2210
- per = {
2211
- alias.get(class_name, class_name): frames
2212
- for class_name, frames in raw_inputs["per"].items()
2213
- }
2214
- depth = raw_inputs["depth"]
2215
- intr = raw_inputs["intr"]
2216
- c2w = raw_inputs["c2w"]
2217
- conf = raw_inputs.get("conf")
2218
- frame_times = raw_inputs["ftimes"]
2219
-
2220
- up_vec, up_axis = room_gravity(depth, intr, c2w, conf)
2221
- instances, stats = build_instances(
2222
- per, depth, intr, c2w, conf, frame_times, up_axis=up_axis
2223
- )
2224
- u, v, g = _floor_basis(up_vec)
2225
- all_points = np.concatenate(
2226
- [item["pts"] for values in instances.values() for item in values], axis=0
2227
- )
2228
- floor_level = float(np.percentile(all_points @ g, 2))
2229
- floor_area = compute_floor_area(depth, intr, c2w, conf, None, up_vec=up_vec)
2230
- code = _reference_to_spatial_code(
2231
- instances, stats, floor_area, up_axis, up_vec, floor_level
2232
- )
2233
- classes = list(instances.keys())
2234
- class_first = {
2235
- class_name: min(item["first_time"] for item in values)
2236
- for class_name, values in instances.items()
2237
- }
2238
-
2239
- for class_name in classes:
2240
- ranked = sorted(
2241
- instances[class_name],
2242
- key=lambda item: (item["n"], item.get("nframes", 0)),
2243
- reverse=True,
2244
- )
2245
- for record, item in zip(code["objects"][class_name]["instances"], ranked):
2246
- record["seen_in_video_frames"] = int(
2247
- item.get("nframes", len(item.get("frames", ())))
2248
- )
2249
-
2250
- closest = {}
2251
- for class_name in classes:
2252
- distances = sorted(
2253
- (
2254
- round(
2255
- answer_closest_distance(instances[class_name], instances[other]), 2
2256
- ),
2257
- other,
2258
- )
2259
- for other in classes
2260
- if other != class_name
2261
- )
2262
- closest[class_name] = {
2263
- other: {"closeness_rank": rank + 1, "distance_meters": distance}
2264
- for rank, (distance, other) in enumerate(distances)
2265
- }
2266
- code["closest_classes_from"] = closest
2267
-
2268
- waypoints = []
2269
- next_time = 0.0
2270
- for index, time_seconds in enumerate(np.asarray(frame_times, np.float64)):
2271
- if time_seconds + 1e-9 < next_time:
2272
- continue
2273
- next_time = float(time_seconds) + 5.0
2274
- position = c2w[index][:3, 3]
2275
- forward = c2w[index][:3, 2]
2276
- waypoints.append(
2277
- {
2278
- "time_seconds": round(float(time_seconds), 1),
2279
- "floor_x_meters": round(float(position @ u), 2),
2280
- "floor_y_meters": round(float(position @ v), 2),
2281
- "heading_degrees": round(
2282
- float(np.degrees(np.arctan2(forward @ v, forward @ u)))
2283
- ),
2284
- }
2285
- )
2286
- code["camera_trajectory"] = {
2287
- "sample_interval_seconds": 5,
2288
- "waypoints": waypoints,
2289
- }
2290
- code["room"] = {
2291
- "outline": _room_outline(depth, intr, c2w, conf, u, v),
2292
- "floor_area_square_meters": code["room"]["floor_area_square_meters"],
2293
- }
2294
- code["appearance order"] = [
2295
- class_name
2296
- for class_name, _time in sorted(class_first.items(), key=lambda item: item[1])
2297
- ]
2298
- return code, instances, stats, up_axis, up_vec, floor_area
2299
-
2300
-
2301
- def build_explicit_spatial_code(scene):
2302
- """Build the selected explicit code.
2303
-
2304
- Raw encoder inputs follow the original geometric V2 spatial-code construction. Canonical
2305
- geometry keeps the compact-derived schema used by ground-truth and non-raw adapters.
2306
- """
2307
- raw_inputs = scene.get("raw_inputs")
2308
- if raw_inputs is not None:
2309
- return _build_reference_v2_spatial_code(raw_inputs)
2310
-
2311
- compact_code, instances, stats, up_ax, up_vec, _ = build_compact_spatial_code(scene)
2312
- code, floor_area = _explicit_from_compact(compact_code)
2313
- return code, instances, stats, up_ax, up_vec, floor_area
2314
-
2315
-
2316
- # ==========================================================================================
2317
- # MODEL-AGNOSTIC ENTRY POINT
2318
- # ==========================================================================================
2319
-
2320
-
2321
- def build_spatial_code(scene, spatial_code_format="explicit"):
2322
- """Build one selected spatial-code schema from canonical scene geometry.
2323
-
2324
- Compact is built directly from raw depth/pose/mask bundles or canonical world-space
2325
- geometry (build_compact_spatial_code() handles that duality). Explicit is always a
2326
- derivation of compact (build_explicit_spatial_code() calls build_compact_spatial_code()
2327
- first), so there is no separate raw/canonical branch for explicit any more.
2328
- """
2329
- if spatial_code_format == "compact":
2330
- return build_compact_spatial_code(scene)
2331
- if spatial_code_format != "explicit":
2332
- raise ValueError(f"unknown spatial-code format {spatial_code_format!r}")
2333
- return build_explicit_spatial_code(scene)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/ground_truth.py DELETED
@@ -1,280 +0,0 @@
1
- """Ground-truth spatial codes: the same compact/explicit schemas encoder/geometric.py
2
- produces from the perception pipeline (SAM3 + Depth Anything 3), but built directly from
3
- the dataset's own annotated 3D object boxes and room size instead -- perfect geometry,
4
- zero perception error, for isolating "does the VLM's spatial reasoning improve when the
5
- input geometry is exactly right" from "is the encoder's perception good enough."
6
-
7
- Sourced from thinking-in-space's meta_info (the same ground truth thinking-in-space's own
8
- official VSI-Bench scorer trains/evaluates against): per-scene `object_bbox` (each
9
- instance's centroid/axesLengths/normalizedAxes -- a full 3D oriented box) and `room_size`
10
- (the room's true floor area). Two things meta_info does NOT carry, because they are
11
- properties of a specific camera walkthrough rather than of the scene's static geometry:
12
-
13
- - Room SHAPE (only the scalar area is annotated): represented as a single axis-aligned
14
- square floor polygon of exactly that area, centered at the scene's own `room_center` --
15
- the honest floor-shape representation the data supports, matching real area exactly
16
- under the same shoelace derivation compact/explicit already use, without inventing a
17
- boundary the annotations don't contain.
18
- - Per-object "first visible time" (when a class first appears on camera -- inherently a
19
- property of the video, not the 3D scan): there is no such ground truth for the average
20
- object, but VSI-Bench's own `obj_appearance_order` questions DO carry genuine human
21
- ground truth ordering for the specific classes they ask about. Every appearance-order
22
- question for a scene contributes a same-scene ordering constraint (see
23
- _appearance_order_ranks); classes never covered by any such question for that scene
24
- get "first visible time": null (no fabricated number) and sort after every timed class
25
- in "appearance order".
26
-
27
- Coordinate convention: thinking-in-space's meta_info coordinates are already gravity-
28
- aligned per-scene (z is up; verified empirically -- `room_center` z is tightly clustered
29
- near a small non-negative range across every scannet scene, unlike x/y, and ARKitScenes'
30
- axis-locked object boxes carry an exact [0, 0, 1] orientation row), so -- unlike the real
31
- encoder pipeline, which must estimate gravity from a noisy reconstructed point cloud --
32
- ground truth's own x, y, z pass straight through as the compact schema's own (x, y,
33
- height above floor) room frame; only a floor reference (z of the annotations' own lowest
34
- point) needs to be established.
35
- """
36
-
37
- from __future__ import annotations
38
-
39
- import json
40
- from functools import lru_cache
41
- from pathlib import Path
42
-
43
- import numpy as np
44
-
45
- from encoder import config
46
- from encoder.geometric import (
47
- COMPACT_SPATIAL_CODE_SCHEMA,
48
- _compact_room_floor_area,
49
- _explicit_from_compact,
50
- _rounded_list,
51
- dump_spatial_code,
52
- )
53
-
54
- META_INFO_DIR = Path(config.DATA_ROOT) / "thinking-in-space" / "data" / "meta_info"
55
- META_INFO_DATASETS = ("scannet", "arkitscenes", "scannetpp")
56
-
57
-
58
- @lru_cache(maxsize=1)
59
- def load_meta_info():
60
- """Return {scene: record} merged across every dataset's meta_info file, each record
61
- carrying its own "dataset" key (scannet / arkitscenes / scannetpp)."""
62
- merged = {}
63
- for dataset in META_INFO_DATASETS:
64
- path = META_INFO_DIR / f"{dataset}_meta_info_val.json"
65
- with open(path, encoding="utf-8") as stream:
66
- records = json.load(stream)
67
- for scene, record in records.items():
68
- merged[str(scene)] = {**record, "dataset": dataset}
69
- return merged
70
-
71
-
72
- @lru_cache(maxsize=1)
73
- def _appearance_order_ranks_by_scene():
74
- """Return {scene: {class_name: rank}} decoded from every real
75
- ``obj_appearance_order`` question's ground_truth answer in test.jsonl -- a DAG of
76
- "class X appears no later than class Y" edges per scene, topologically ranked (DFS,
77
- back-edges from any inconsistent question ignored rather than raising, since a rank
78
- is still useful even if two annotators' four-item orderings can't be perfectly
79
- reconciled). Classes never named by any appearance-order question for that scene are
80
- simply absent from the returned mapping.
81
- """
82
- edges_by_scene = {}
83
- with open(config.JSONL, encoding="utf-8") as stream:
84
- for line in stream:
85
- question = json.loads(line)
86
- if question.get("question_type") != "obj_appearance_order":
87
- continue
88
- scene = str(question["scene_name"])
89
- index = ord(question["ground_truth"]) - ord("A")
90
- option = question["options"][index]
91
- classes = [name.strip() for name in option.split(".", 1)[1].split(",")]
92
- edges = edges_by_scene.setdefault(scene, {})
93
- for earlier, later in zip(classes, classes[1:]):
94
- edges.setdefault(earlier, set()).add(later)
95
-
96
- ranks_by_scene = {}
97
- for scene, edges in edges_by_scene.items():
98
- nodes = set(edges) | {
99
- node for successors in edges.values() for node in successors
100
- }
101
- order = []
102
- visited, in_progress = set(), set()
103
-
104
- def visit(node):
105
- if node in visited or node in in_progress:
106
- return
107
- in_progress.add(node)
108
- for successor in sorted(edges.get(node, ())):
109
- visit(successor)
110
- in_progress.discard(node)
111
- visited.add(node)
112
- order.append(node)
113
-
114
- for node in sorted(nodes):
115
- visit(node)
116
- order.reverse()
117
- ranks_by_scene[scene] = {name: rank for rank, name in enumerate(order)}
118
- return ranks_by_scene
119
-
120
-
121
- def _floor_level(object_bbox):
122
- """Return the lowest z any annotated object's oriented box reaches: the support of
123
- each box along -z, i.e. centroid_z minus the box's half-extent projected onto z
124
- (sum of half-dimension * |axis . z| across all three axes -- the true lowest corner
125
- of a tilted box, not just its centroid)."""
126
- lowest = []
127
- for instances in object_bbox.values():
128
- for instance in instances:
129
- centroid_z = float(instance["centroid"][2])
130
- dims = np.asarray(instance["axesLengths"], np.float64)
131
- axes = np.asarray(instance["normalizedAxes"], np.float64).reshape(3, 3)
132
- axes = axes / np.linalg.norm(axes, axis=1, keepdims=True)
133
- half_extent_z = float(np.sum(dims / 2 * np.abs(axes[:, 2])))
134
- lowest.append(centroid_z - half_extent_z)
135
- return min(lowest) if lowest else 0.0
136
-
137
-
138
- def _gt_oriented_box(instance, floor_level):
139
- """Return one compact "3D oriented bounding box" dict straight from a meta_info
140
- object_bbox instance -- centroid/axesLengths/normalizedAxes pass through as this
141
- dataset's own gravity-aligned x, y, z (see module docstring), only re-based so the
142
- third component is height above this scene's own floor reference."""
143
- centroid = np.asarray(instance["centroid"], np.float64)
144
- dims = np.asarray(instance["axesLengths"], np.float64)
145
- axes = np.asarray(instance["normalizedAxes"], np.float64).reshape(3, 3)
146
- axes = axes / np.linalg.norm(axes, axis=1, keepdims=True)
147
- center = [float(centroid[0]), float(centroid[1]), float(centroid[2]) - floor_level]
148
- return {
149
- "3D oriented bounding box center coordinates": _rounded_list(center),
150
- "3D oriented bounding box dimensions": _rounded_list(dims.tolist()),
151
- "3D oriented bounding box orientation unit vectors": [
152
- _rounded_list(row.tolist()) for row in axes
153
- ],
154
- }
155
-
156
-
157
- def _gt_floor_boundary_polygons(room_size, room_center):
158
- """A single axis-aligned square of exactly area ``room_size`` centered at
159
- ``room_center``'s (x, y) -- the floor-SHAPE stand-in the annotations actually
160
- support (see module docstring); no holes, since meta_info carries no boundary
161
- detail to place one from."""
162
- half_side = float(np.sqrt(max(room_size, 0.0))) / 2
163
- cx, cy = float(room_center[0]), float(room_center[1])
164
- corners = [
165
- [cx - half_side, cy - half_side],
166
- [cx + half_side, cy - half_side],
167
- [cx + half_side, cy + half_side],
168
- [cx - half_side, cy + half_side],
169
- ]
170
- return [
171
- {
172
- "outer boundary coordinates": [_rounded_list(corner) for corner in corners],
173
- "interior hole boundary coordinates": [],
174
- }
175
- ]
176
-
177
-
178
- def build_compact_ground_truth_spatial_code(scene):
179
- """Build the compact spatial code for ``scene`` directly from its dataset annotation
180
- (meta_info), in the exact COMPACT_SPATIAL_CODE_SCHEMA shape/legend build_compact_
181
- spatial_code() produces from the perception pipeline."""
182
- meta = load_meta_info()
183
- if scene not in meta:
184
- raise KeyError(f"no meta_info ground truth for scene {scene!r}")
185
- record = meta[scene]
186
- object_bbox = record["object_bbox"]
187
- floor_level = _floor_level(object_bbox)
188
- ranks = _appearance_order_ranks_by_scene().get(scene, {})
189
-
190
- objects = {}
191
- for class_name, instances in object_bbox.items():
192
- rank = ranks.get(class_name)
193
- objects[class_name] = [
194
- {
195
- "3D oriented bounding box": _gt_oriented_box(instance, floor_level),
196
- "first visible time": float(rank) if rank is not None else None,
197
- }
198
- for instance in instances
199
- ]
200
-
201
- return {
202
- "objects": objects,
203
- "room": {
204
- "floor boundary polygons": _gt_floor_boundary_polygons(
205
- record["room_size"], record["room_center"]
206
- )
207
- },
208
- }
209
-
210
-
211
- def build_explicit_ground_truth_spatial_code(scene):
212
- """Build the explicit spatial code for ``scene`` as the exact same strict derivation
213
- of a compact code that build_explicit_spatial_code() uses for encoder-built codes,
214
- applied to build_compact_ground_truth_spatial_code()'s output instead."""
215
- compact_code = build_compact_ground_truth_spatial_code(scene)
216
- code, _floor_area = _explicit_from_compact(compact_code)
217
- return code
218
-
219
-
220
- def build_ground_truth_spatial_code(scene, spatial_code_format="explicit"):
221
- """Dispatch to the compact or explicit ground-truth builder, mirroring
222
- encoder.geometric.build_spatial_code's format switch."""
223
- if spatial_code_format == "compact":
224
- return build_compact_ground_truth_spatial_code(scene)
225
- if spatial_code_format == "explicit":
226
- return build_explicit_ground_truth_spatial_code(scene)
227
- raise ValueError(
228
- f"unknown spatial-code format {spatial_code_format!r}; expected 'compact' or 'explicit'"
229
- )
230
-
231
-
232
- def build_and_write(scene, spatial_code_format="explicit"):
233
- """Build one scene's ground-truth spatial code and write it to its on-disk path
234
- (encoder.config.ground_truth_spatial_code_path), creating parent directories as
235
- needed. Returns the path written."""
236
- code = build_ground_truth_spatial_code(scene, spatial_code_format)
237
- path = config.ground_truth_spatial_code_path(scene, spatial_code_format)
238
- Path(path).parent.mkdir(parents=True, exist_ok=True)
239
- dump_spatial_code(code, path)
240
- return path
241
-
242
-
243
- def scenes():
244
- """Every scene meta_info has ground truth for (a superset of every scene any
245
- perception-built spatial code could ever cover, since this needs no SAM3/DA3 cache).
246
- """
247
- return sorted(load_meta_info())
248
-
249
-
250
- def build_all(spatial_code_formats=("explicit", "compact"), scene_list=None):
251
- """Build and write ground-truth spatial codes for every scene (or ``scene_list``)
252
- in both formats by default. Returns the list of paths written."""
253
- written = []
254
- for scene in scene_list if scene_list is not None else scenes():
255
- for spatial_code_format in spatial_code_formats:
256
- written.append(build_and_write(scene, spatial_code_format))
257
- return written
258
-
259
-
260
- if __name__ == "__main__":
261
- import argparse
262
-
263
- parser = argparse.ArgumentParser()
264
- parser.add_argument(
265
- "--scenes", help="comma-separated scenes (default: every scene)"
266
- )
267
- parser.add_argument(
268
- "--formats",
269
- default="explicit,compact",
270
- help="comma-separated spatial-code formats",
271
- )
272
- args = parser.parse_args()
273
- scene_list = (
274
- [scene.strip() for scene in args.scenes.split(",") if scene.strip()]
275
- if args.scenes
276
- else None
277
- )
278
- formats = tuple(fmt.strip() for fmt in args.formats.split(",") if fmt.strip())
279
- paths = build_all(formats, scene_list)
280
- print(f"wrote {len(paths)} ground-truth spatial codes")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/launch.py DELETED
@@ -1,301 +0,0 @@
1
- """Persistent CPU-parallel batch driver for the VSI encoder.
2
-
3
- Without a scene argument, processes manifest scenes with all required inference caches.
4
- CPU-bound encoding defaults to one worker per available CPU, with nested numerical
5
- threads budgeted across workers.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
- import argparse
11
- import json
12
- import multiprocessing as mp
13
- import os
14
- from pathlib import Path
15
- import subprocess
16
- import sys
17
- import traceback
18
-
19
- WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
20
- if str(WORKSPACE_ROOT) not in sys.path:
21
- sys.path.insert(0, str(WORKSPACE_ROOT))
22
-
23
- from encoder import config # noqa: E402
24
-
25
-
26
- def _scenes():
27
- with open(config.JSONL) as f:
28
- return list(dict.fromkeys(str(json.loads(line)["scene_name"]) for line in f))
29
-
30
-
31
- def _video_cache_files(scene, depth, tracking):
32
- """Return full-video perception-cache files for the selected axes."""
33
- return (
34
- Path(config.video_da3_cache_file(scene, depth)),
35
- Path(config.video_sam3_cache_file(scene, tracking)),
36
- )
37
-
38
-
39
- def _has_required_caches(
40
- scene, depth, input_selection, tracking, frame_count, video=False
41
- ):
42
- """Return whether all inference caches needed for encoding exist."""
43
- if video:
44
- paths = _video_cache_files(scene, depth, tracking)
45
- else:
46
- paths = (
47
- config.sam3_cache_file(scene, input_selection, tracking, frame_count),
48
- config.da3_cache_file(scene, depth, input_selection, frame_count),
49
- )
50
- return all(os.path.isfile(path) for path in paths)
51
-
52
-
53
- def _scenes_with_required_caches(
54
- depth, input_selection, tracking, frame_count, video=False
55
- ):
56
- """Return manifest scenes having every cache required by this encoder run."""
57
- return [
58
- scene
59
- for scene in _scenes()
60
- if _has_required_caches(
61
- scene, depth, input_selection, tracking, frame_count, video
62
- )
63
- ]
64
-
65
-
66
- def _available_cpu_count():
67
- """Return the CPUs available to this process, respecting affinity and overrides."""
68
- configured = os.environ.get("VSI_CPU_WORKERS")
69
- if configured is not None:
70
- count = int(configured)
71
- if count < 1:
72
- raise ValueError("VSI_CPU_WORKERS must be positive")
73
- return count
74
- try:
75
- return max(1, len(os.sched_getaffinity(0)))
76
- except AttributeError:
77
- return max(1, os.cpu_count() or 1)
78
-
79
-
80
- def _visible_gpus():
81
- configured = os.environ.get("CUDA_VISIBLE_DEVICES")
82
- if configured is not None:
83
- return [
84
- x.strip() for x in configured.split(",") if x.strip() and x.strip() != "-1"
85
- ]
86
- try:
87
- out = subprocess.check_output(
88
- ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader"],
89
- text=True,
90
- stderr=subprocess.DEVNULL,
91
- )
92
- return [line.strip() for line in out.splitlines() if line.strip()]
93
- except (FileNotFoundError, subprocess.SubprocessError):
94
- return []
95
-
96
-
97
- def _worker(
98
- task_queue,
99
- result_queue,
100
- depth,
101
- input_selection,
102
- tracking,
103
- frame_count,
104
- rebuild,
105
- cpu_threads,
106
- video,
107
- ):
108
- for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
109
- os.environ[variable] = str(cpu_threads)
110
- import cv2
111
-
112
- cv2.setNumThreads(cpu_threads)
113
- os.environ["VSI_KD_WORKERS"] = str(cpu_threads)
114
- # torch ignores the OMP/MKL/OPENBLAS env vars above (and sched_getaffinity/cgroup
115
- # limits) -- it defaults both its intra-op and inter-op pools to the machine's full
116
- # logical core count. adapters._load_native_sam3 imports torch to read the SAM3
117
- # cache, so every worker would otherwise spin up its own full-width thread pool on
118
- # top of the budget already enforced for numpy/cv2/scipy.
119
- import torch
120
-
121
- torch.set_num_threads(cpu_threads)
122
- try:
123
- torch.set_num_interop_threads(cpu_threads)
124
- except RuntimeError:
125
- pass # already used/set once in this process; not worth failing the worker over
126
- from encoder import render
127
- from encoder.adapters import EmptySceneError
128
-
129
- while True:
130
- scene = task_queue.get()
131
- if scene is None:
132
- return
133
- try:
134
- _, how, path = render.write_spatial_code_for(
135
- scene,
136
- depth,
137
- input_selection,
138
- tracking,
139
- frame_count,
140
- rebuild,
141
- video,
142
- )
143
- result_queue.put((scene, "done", f"{how} -> {path}"))
144
- except EmptySceneError:
145
- result_queue.put((scene, "skipped", "cache produced no instances"))
146
- except Exception:
147
- result_queue.put((scene, "failed", traceback.format_exc()))
148
-
149
-
150
- def _launch(args, selected):
151
- label = (
152
- f"{args.depth}/{args.tracking}/video"
153
- if args.video
154
- else f"{args.depth}/{args.tracking}/{args.input_selection}/{args.frames}"
155
- )
156
- pending = []
157
- completed = 0
158
- for scene in selected:
159
- output_exists = os.path.exists(
160
- config.spatial_code_path(
161
- scene,
162
- args.depth,
163
- args.input_selection,
164
- args.tracking,
165
- args.frame_count,
166
- "explicit",
167
- )
168
- )
169
- if output_exists and not args.rebuild:
170
- completed += 1
171
- print(f"[{label} {completed}/{len(selected)}] {scene}: skipped", flush=True)
172
- else:
173
- pending.append(scene)
174
- if not pending:
175
- print(f"[{label}] DONE: {len(selected)} ok, 0 failed")
176
- return
177
-
178
- cpu_count = _available_cpu_count()
179
- worker_count = args.workers or cpu_count
180
- if worker_count < 1:
181
- raise ValueError("--workers must be positive or zero for automatic")
182
- worker_count = min(worker_count, len(pending))
183
- cpu_threads = max(1, cpu_count // worker_count)
184
- for variable in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
185
- os.environ[variable] = str(cpu_threads)
186
- print(
187
- f"[{label}] starting {worker_count} persistent CPU worker(s); "
188
- f"threads per worker={cpu_threads}",
189
- flush=True,
190
- )
191
-
192
- context = mp.get_context("spawn")
193
- tasks, results = context.Queue(), context.Queue()
194
- for scene in pending:
195
- tasks.put(scene)
196
- for _ in range(worker_count):
197
- tasks.put(None)
198
- processes = [
199
- context.Process(
200
- target=_worker,
201
- args=(
202
- tasks,
203
- results,
204
- args.depth,
205
- args.input_selection,
206
- args.tracking,
207
- args.frame_count,
208
- args.rebuild,
209
- cpu_threads,
210
- args.video,
211
- ),
212
- )
213
- for _ in range(worker_count)
214
- ]
215
- for process in processes:
216
- process.start()
217
-
218
- failed = []
219
- skipped = 0
220
- for _ in pending:
221
- scene, status, detail = results.get()
222
- completed += 1
223
- if status == "failed":
224
- failed.append(scene)
225
- elif status == "skipped":
226
- skipped += 1
227
- display_status = "FAILED" if status == "failed" else status
228
- print(
229
- f"[{label} {completed}/{len(selected)}] {scene}: "
230
- f"{display_status}\n{detail}",
231
- flush=True,
232
- )
233
- for process in processes:
234
- process.join()
235
- succeeded = len(selected) - len(failed) - skipped
236
- print(
237
- f"[{label}] DONE: {succeeded} ok, {skipped} skipped, " f"{len(failed)} failed"
238
- )
239
- if failed:
240
- raise SystemExit(1)
241
-
242
-
243
- def main():
244
- parser = argparse.ArgumentParser()
245
- parser.add_argument("scene", nargs="?")
246
- parser.add_argument("--depth", choices=config.DEPTH_VARIANTS)
247
- parser.add_argument(
248
- "--input",
249
- choices=config.INPUT_SELECTIONS,
250
- dest="input_selection",
251
- )
252
- input_mode = parser.add_mutually_exclusive_group(required=True)
253
- input_mode.add_argument("--frames", type=int)
254
- input_mode.add_argument(
255
- "--video",
256
- action="store_true",
257
- help="use full-video DA3 and SAM3 caches",
258
- )
259
- parser.add_argument("--tracking", choices=config.TRACKING_MODES)
260
- parser.add_argument(
261
- "--workers",
262
- type=int,
263
- default=0,
264
- help="persistent workers (default: all available CPUs)",
265
- )
266
- parser.add_argument("--rebuild", action="store_true")
267
- args = parser.parse_args()
268
- if args.depth is None:
269
- parser.error("--depth is required")
270
- if args.tracking is None:
271
- parser.error("--tracking is required")
272
- if args.video:
273
- if args.input_selection is not None:
274
- parser.error("--input cannot be used with --video")
275
- args.input_selection = config.VIDEO_INPUT_SELECTION
276
- elif args.input_selection is None:
277
- parser.error("--input is required with --frames")
278
- if args.frames is not None and args.frames < 1:
279
- parser.error("--frames must be positive")
280
- args.frame_count = args.frames
281
- if args.workers < 0:
282
- parser.error("--workers must be positive or zero for automatic")
283
- selected = (
284
- [args.scene]
285
- if args.scene
286
- else _scenes_with_required_caches(
287
- args.depth,
288
- args.input_selection,
289
- args.tracking,
290
- args.frame_count,
291
- args.video,
292
- )
293
- )
294
- if not selected:
295
- print("DONE: no manifest scenes have all required caches")
296
- return
297
- _launch(args, selected)
298
-
299
-
300
- if __name__ == "__main__":
301
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/render.py DELETED
@@ -1,73 +0,0 @@
1
- """Build and write one final spatial-code JSON file per scene."""
2
-
3
- from __future__ import annotations
4
-
5
- import os
6
-
7
- from encoder import config
8
- from encoder import geometric as geometry_math
9
- from encoder import run as perceive
10
-
11
-
12
- def build_spatial_code_for(
13
- scene,
14
- depth,
15
- input_selection,
16
- tracking,
17
- frame_count=config.FRAMES_PER_VIDEO,
18
- rebuild=False,
19
- video=False,
20
- da3_path=None,
21
- sam3_path=None,
22
- ):
23
- """Build a spatial code from cached or newly adapted scene geometry."""
24
- if video:
25
- input_selection = config.VIDEO_INPUT_SELECTION
26
- kwargs = {"video": video}
27
- if da3_path is not None:
28
- kwargs["da3_path"] = da3_path
29
- if sam3_path is not None:
30
- kwargs["sam3_path"] = sam3_path
31
- geometry, how = perceive.cache_or_load(
32
- scene, depth, input_selection, tracking, frame_count, rebuild, **kwargs
33
- )
34
- code, *_ = geometry_math.build_spatial_code(geometry, "explicit")
35
- return code, how
36
-
37
-
38
- def write_spatial_code_for(
39
- scene,
40
- depth,
41
- input_selection,
42
- tracking,
43
- frame_count=config.FRAMES_PER_VIDEO,
44
- rebuild=False,
45
- video=False,
46
- da3_path=None,
47
- sam3_path=None,
48
- ):
49
- """Build and write one scene's spatial-code JSON."""
50
- if video:
51
- input_selection = config.VIDEO_INPUT_SELECTION
52
- code, how = build_spatial_code_for(
53
- scene,
54
- depth,
55
- input_selection,
56
- tracking,
57
- frame_count,
58
- rebuild,
59
- video,
60
- da3_path,
61
- sam3_path,
62
- )
63
- path = config.spatial_code_path(
64
- scene,
65
- depth,
66
- input_selection,
67
- tracking,
68
- frame_count,
69
- "explicit",
70
- )
71
- os.makedirs(os.path.dirname(path), exist_ok=True)
72
- geometry_math.dump_spatial_code(code, path)
73
- return code, how, path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
encoder/run.py DELETED
@@ -1,276 +0,0 @@
1
- """Load or build one flat per-scene cache file for the selected model."""
2
-
3
- from __future__ import annotations
4
-
5
- import argparse
6
- import gzip
7
- import hashlib
8
- import os
9
- from pathlib import Path
10
- import pickle
11
- import sys
12
-
13
- # Single-scene CLI runs (unlike launch.py's budgeted batch workers) otherwise inherit
14
- # whatever thread defaults numpy/BLAS/scipy pick -- typically "use every core" -- which
15
- # thrashes when geometric.py makes many small parallel-dispatched calls (cv2 ops per
16
- # mask, KD-tree queries per class pair). setdefault() so launch.py's explicit
17
- # per-worker budget (set before it imports this module via render.py) always wins.
18
- for _var in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
19
- os.environ.setdefault(_var, "1")
20
- os.environ.setdefault("VSI_KD_WORKERS", "1")
21
-
22
- WORKSPACE_ROOT = Path(__file__).resolve().parent.parent
23
- if str(WORKSPACE_ROOT) not in sys.path:
24
- sys.path.insert(0, str(WORKSPACE_ROOT))
25
-
26
- from encoder import adapters # noqa: E402
27
- from encoder import config # noqa: E402
28
-
29
- PROVENANCE_KEY = "source_provenance"
30
- PROVENANCE_VERSION = 1
31
-
32
-
33
- def _source_record(path):
34
- """Describe one native cache without copying its payload."""
35
- source = Path(path)
36
- size = source.stat().st_size
37
- digest = hashlib.sha256()
38
- with source.open("rb") as stream:
39
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
40
- digest.update(chunk)
41
- return {"path": str(source), "size": size, "sha256": digest.hexdigest()}
42
-
43
-
44
- def _source_provenance(scene, mode, paths):
45
- """Record the exact native caches used to derive a combined cache."""
46
- return {
47
- "format_version": PROVENANCE_VERSION,
48
- "scene": scene,
49
- "mode": mode,
50
- "sources": {name: _source_record(path) for name, path in paths.items()},
51
- }
52
-
53
-
54
- def _verify_source_provenance(provenance):
55
- """Ensure every referenced native cache still matches byte-for-byte."""
56
- if (
57
- not isinstance(provenance, dict)
58
- or provenance.get("format_version") != PROVENANCE_VERSION
59
- ):
60
- raise ValueError("combined cache has unsupported source provenance")
61
- sources = provenance.get("sources")
62
- if not isinstance(sources, dict) or set(sources) != {"sam3", "depth-anything-3"}:
63
- raise ValueError("combined cache source provenance is incomplete")
64
- for name, expected in sources.items():
65
- if not isinstance(expected, dict) or "path" not in expected:
66
- raise ValueError(f"combined cache source {name!r} has invalid provenance")
67
- try:
68
- actual = _source_record(expected["path"])
69
- except FileNotFoundError as exc:
70
- raise FileNotFoundError(
71
- f"combined cache source {name!r} is missing: {expected['path']}"
72
- ) from exc
73
- if actual["size"] != expected.get("size") or actual["sha256"] != expected.get(
74
- "sha256"
75
- ):
76
- raise ValueError(
77
- f"combined cache source {name!r} no longer matches its provenance"
78
- )
79
-
80
-
81
- def _video_cache_files(scene, depth, tracking):
82
- """Return the full-video DA3 + SAM3 cache pair for the selected axes."""
83
- return (
84
- config.video_da3_cache_file(scene, depth),
85
- config.video_sam3_cache_file(scene, tracking),
86
- )
87
-
88
-
89
- def _effective_dimensions(depth, input_selection, tracking, video):
90
- """Map video input onto its path branch without changing other axes."""
91
- if video:
92
- return depth, config.VIDEO_INPUT_SELECTION, tracking
93
- return depth, input_selection, tracking
94
-
95
-
96
- def _cache_source_paths(
97
- scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
98
- ):
99
- """Resolve the selected DA3/SAM3 source pair without changing adapter semantics."""
100
- if video:
101
- default_da3, default_sam3 = _video_cache_files(scene, depth, tracking)
102
- else:
103
- default_da3 = config.da3_cache_file(scene, depth, input_selection, frame_count)
104
- default_sam3 = config.sam3_cache_file(
105
- scene, input_selection, tracking, frame_count
106
- )
107
- return da3_path or default_da3, sam3_path or default_sam3
108
-
109
-
110
- def _combined_cache_file(
111
- scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
112
- ):
113
- """Return a combined-cache path isolated by source cache format and explicit paths."""
114
- if da3_path is None and sam3_path is None:
115
- return config.cache_file(scene, depth, input_selection, tracking, frame_count)
116
- label = config.VIDEO_INPUT_SELECTION if video else "custom"
117
- if da3_path is not None or sam3_path is not None:
118
- digest = hashlib.sha256()
119
- digest.update(str(da3_path or "").encode())
120
- digest.update(b"\0")
121
- digest.update(str(sam3_path or "").encode())
122
- label = f"{label}-{digest.hexdigest()[:12]}"
123
- directory = config.CACHE_ROOT / config.MODEL / depth / tracking / label
124
- if not video:
125
- directory = directory / str(frame_count)
126
- return str(directory / f"{scene}.pkl.gz")
127
-
128
-
129
- def cache_or_load(
130
- scene,
131
- depth,
132
- input_selection,
133
- tracking,
134
- frame_count=config.FRAMES_PER_VIDEO,
135
- rebuild=False,
136
- video=False,
137
- da3_path=None,
138
- sam3_path=None,
139
- ):
140
- """Return canonical geometry for one specific set of input dimensions."""
141
- depth, input_selection, tracking = _effective_dimensions(
142
- depth, input_selection, tracking, video
143
- )
144
- path = _combined_cache_file(
145
- scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
146
- )
147
- if os.path.exists(path) and not rebuild:
148
- with gzip.open(path, "rb") as stream:
149
- cached = pickle.load(stream)
150
- provenance = cached.get(PROVENANCE_KEY) if isinstance(cached, dict) else None
151
- if provenance is not None:
152
- _verify_source_provenance(provenance)
153
- return adapters.validate(cached), "loaded"
154
- # Legacy combined caches are rebuilt to attach exact source provenance.
155
-
156
- selected_da3_path, selected_sam3_path = _cache_source_paths(
157
- scene, depth, input_selection, tracking, frame_count, video, da3_path, sam3_path
158
- )
159
- raw_cache = {
160
- "scene": scene,
161
- "root": str(config.CACHE_ROOT),
162
- "rebuild": rebuild,
163
- "da3_path": selected_da3_path,
164
- "sam3_path": selected_sam3_path,
165
- }
166
- geometry = adapters.adapt(config.MODEL, **raw_cache)
167
- mode = f"{input_selection}:{frame_count}:{tracking}"
168
- geometry[PROVENANCE_KEY] = _source_provenance(
169
- scene,
170
- mode,
171
- {
172
- "sam3": raw_cache["sam3_path"],
173
- "depth-anything-3": raw_cache["da3_path"],
174
- },
175
- )
176
- geometry[PROVENANCE_KEY].update(
177
- {
178
- "depth": depth,
179
- "input": input_selection,
180
- "tracking": tracking,
181
- "frames": frame_count,
182
- "video": bool(video),
183
- }
184
- )
185
- _verify_source_provenance(geometry[PROVENANCE_KEY])
186
- os.makedirs(os.path.dirname(path), exist_ok=True)
187
- with gzip.open(path, "wb") as stream:
188
- pickle.dump(geometry, stream, protocol=pickle.HIGHEST_PROTOCOL)
189
- return geometry, "built"
190
-
191
-
192
- def main():
193
- parser = argparse.ArgumentParser()
194
- parser.add_argument("scene")
195
- parser.add_argument("--depth", choices=config.DEPTH_VARIANTS)
196
- parser.add_argument(
197
- "--input",
198
- choices=config.INPUT_SELECTIONS,
199
- dest="input_selection",
200
- )
201
- input_mode = parser.add_mutually_exclusive_group(required=True)
202
- input_mode.add_argument("--frames", type=int)
203
- input_mode.add_argument(
204
- "--video",
205
- action="store_true",
206
- help="use full-video DA3 and SAM3 caches",
207
- )
208
- parser.add_argument("--tracking", choices=config.TRACKING_MODES)
209
- parser.add_argument(
210
- "--da3-path", default=None, help="override the selected DA3 cache path"
211
- )
212
- parser.add_argument(
213
- "--sam3-path", default=None, help="override the selected SAM3 cache path"
214
- )
215
- parser.add_argument("--rebuild", action="store_true")
216
- args = parser.parse_args()
217
- if args.depth is None:
218
- parser.error("--depth is required")
219
- if args.tracking is None:
220
- parser.error("--tracking is required")
221
- if args.video:
222
- if args.input_selection is not None:
223
- parser.error("--input cannot be used with --video")
224
- args.input_selection = config.VIDEO_INPUT_SELECTION
225
- elif args.input_selection is None:
226
- parser.error("--input is required with --frames")
227
- if args.frames is not None and args.frames < 1:
228
- parser.error("--frames must be positive")
229
- frame_count = args.frames
230
- from encoder import render
231
-
232
- import cv2
233
-
234
- cv2.setNumThreads(1) # see thread-budget note near the top imports
235
-
236
- import torch # torch ignores the OMP/MKL/OPENBLAS env vars set above
237
-
238
- torch.set_num_threads(1)
239
- try:
240
- torch.set_num_interop_threads(1)
241
- except RuntimeError:
242
- pass
243
-
244
- geometry, how = cache_or_load(
245
- args.scene,
246
- args.depth,
247
- args.input_selection,
248
- args.tracking,
249
- frame_count,
250
- args.rebuild,
251
- args.video,
252
- args.da3_path,
253
- args.sam3_path,
254
- )
255
- count = sum(len(values) for values in geometry["instances"].values())
256
- print(
257
- f"[{args.scene}] depth={args.depth} input={args.input_selection} "
258
- f"frames={args.frames} tracking={args.tracking} video={args.video} cache={how} "
259
- f"classes={len(geometry['instances'])} instances={count}"
260
- )
261
- _, _, path = render.write_spatial_code_for(
262
- args.scene,
263
- args.depth,
264
- args.input_selection,
265
- args.tracking,
266
- frame_count,
267
- False,
268
- args.video,
269
- args.da3_path,
270
- args.sam3_path,
271
- )
272
- print(f"[{args.scene}] spatial_code={path}")
273
-
274
-
275
- if __name__ == "__main__":
276
- main()