diff --git a/README.md b/README.md index 73fcae14f567d24511a4c92de5325a383aa1da36..4dd36c96cd0032d2b20ce0ab4e8bb9db0cfb92ed 100644 --- a/README.md +++ b/README.md @@ -157,6 +157,36 @@ Important files: - `encoder/launch.py`: CPU-parallel batch driver - `encoder/ground_truth.py`: ground-truth compact/explicit code builder +### Experiments: Geometry Hypotheses + +```bash +# List available hypothesis forks. +python -m experiments.run --list + +# Build one hypothesis spatial code from existing caches only. +python -m experiments.run SCENE --hypothesis "Compute Gravity Before Building Object Instances" --depth metric --tracking tracking --input uniform --frames 64 --format explicit + +# Batch all scenes with existing combined or native SAM3/DA3 caches. +python -m experiments.launch --hypothesis "Compute Gravity Before Building Object Instances" --depth metric --tracking tracking --input uniform --frames 64 --format explicit + +# Evaluate generated experiment spatial codes with the symbolic scorer. +python -m experiments.evaluate --hypothesis "Compute Gravity Before Building Object Instances" --depth metric --tracking tracking --input uniform --frames 64 --format explicit --quiet --errors +``` + +Files: + +- `experiments/__init__.py`: experiments package marker +- `experiments/README.md`: experiment workflow notes +- `experiments/EXPERIMENT FINDINGS.md`: single consolidated findings report +- `experiments/hypotheses.md`: hypothesis index and notes +- `experiments/config.py`: experiment-local path construction +- `experiments/adapters.py`: build-call adapter for explicit and compact hypothesis forks +- `experiments/loader.py`: dynamic loader for human-readable hypothesis filenames +- `experiments/run.py`: one-scene cache-only hypothesis spatial-code builder +- `experiments/launch.py`: batch launcher over scenes with existing caches +- `experiments/evaluate.py`: symbolic evaluation of experiment spatial codes +- `experiments/hypotheses/*.py`: standalone geometry hypothesis forks; each exposes `build_spatial_code()` and `dump_spatial_code()` + ### Symbolic Solver ```bash @@ -411,6 +441,8 @@ Files: | `README.md` | This documentation | | `setup.sh` | Environment, package, data, model, and validation setup | | `backup.py` | Hugging Face dataset backup utility | +| `.gitattributes` | Git LFS attributes for large/binary artifact patterns | +| `.gitignore` | Excludes generated caches, notebooks, envs, and result folders | | `selective_frame_counts.csv` | Static frame-count/reference data used by selection workflows | | `bundles/spatial-codes.tar.gz` | Packed spatial-code artifact used by setup sync | @@ -644,6 +676,18 @@ The tests mirror source folders. They are written to run without real data, resu - `tests/test_encoder/test_render.py` - `tests/test_encoder/test_run.py` +### `tests/test_experiments/` + +- `tests/test_experiments/__init__.py` +- `tests/test_experiments/conftest.py` +- `tests/test_experiments/test_config.py` +- `tests/test_experiments/test_evaluate.py` +- `tests/test_experiments/test_experiments.py` +- `tests/test_experiments/test_hypotheses.py` +- `tests/test_experiments/test_launch.py` +- `tests/test_experiments/test_loader.py` +- `tests/test_experiments/test_run.py` + ### `tests/test_harness/` - `tests/test_harness/__init__.py` diff --git a/experiments/hypotheses/Bridge Floor To Wall Grazing Gap.py b/experiments/hypotheses/Bridge Floor To Wall Grazing Gap.py index 730ba87b6dec33e8abe53659c3241f8b1752de3a..2e946710e9e243d87d3790ad789dbe542a193d6a 100644 --- a/experiments/hypotheses/Bridge Floor To Wall Grazing Gap.py +++ b/experiments/hypotheses/Bridge Floor To Wall Grazing Gap.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1810,13 +1821,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1977,9 +1992,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2012,9 +2025,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Bridge Unobserved Floor With Room Scale Close.py b/experiments/hypotheses/Bridge Unobserved Floor With Room Scale Close.py index f09bb3c649d11f0e06081fe802c0e3404d60ba0f..79e032a921229201603903f9f6e219fb96b90055 100644 --- a/experiments/hypotheses/Bridge Unobserved Floor With Room Scale Close.py +++ b/experiments/hypotheses/Bridge Unobserved Floor With Room Scale Close.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1946,9 +1956,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1981,9 +1989,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV FloorClip 005.py b/experiments/hypotheses/CV FloorClip 005.py index 6437dda5a737e2cbf44b1c0111f6b0ebc7464df6..9602d6b641639345818be8bc7a7e4d5145a996ab 100644 --- a/experiments/hypotheses/CV FloorClip 005.py +++ b/experiments/hypotheses/CV FloorClip 005.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV FloorClip 05.py b/experiments/hypotheses/CV FloorClip 05.py index 3a524c9e7786dde912e0a691c70637b0be806241..739737a3bcdadb9a71badf4574ed474e17078e86 100644 --- a/experiments/hypotheses/CV FloorClip 05.py +++ b/experiments/hypotheses/CV FloorClip 05.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV Grazing 3.py b/experiments/hypotheses/CV Grazing 3.py index af980f7639515f2cba4c36daedd30a425054fcbb..607cdd1b365fea3e3b78eae144fb33c87797a835 100644 --- a/experiments/hypotheses/CV Grazing 3.py +++ b/experiments/hypotheses/CV Grazing 3.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV Grazing 7.py b/experiments/hypotheses/CV Grazing 7.py index 9dbbd264f5c4c9e9f9573eaa9428d31500d8a381..e7505b723f7e4875132144f50600fb9e909ff568 100644 --- a/experiments/hypotheses/CV Grazing 7.py +++ b/experiments/hypotheses/CV Grazing 7.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV LenAxis 075.py b/experiments/hypotheses/CV LenAxis 075.py index 7fb65da9424cb2e46c28ae411ec834dcc44b1125..f94f510cffee6eb09b2cddd0fdea9f0f6ebb6c8f 100644 --- a/experiments/hypotheses/CV LenAxis 075.py +++ b/experiments/hypotheses/CV LenAxis 075.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.75) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.75) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV LenAxis 10.py b/experiments/hypotheses/CV LenAxis 10.py index 9ff8729ba1bbef29236b3b08fecc161415ada608..bb513d4521b72eb8bd7512da1bdcd1be1bb731d8 100644 --- a/experiments/hypotheses/CV LenAxis 10.py +++ b/experiments/hypotheses/CV LenAxis 10.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 1.0) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 1.0) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV SOR 125.py b/experiments/hypotheses/CV SOR 125.py index 6a5f5dba8939d2bdeb8babc8406ae39ced3e057d..c51c23ae8fed6e0fc063749407447d2c708a8d9a 100644 --- a/experiments/hypotheses/CV SOR 125.py +++ b/experiments/hypotheses/CV SOR 125.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/CV SOR 20.py b/experiments/hypotheses/CV SOR 20.py index 16bb2d8f404c82ff2162d7249447d23fb72a8c94..be152f192f46afc8a7ee1ab7594055ca1bea9a15 100644 --- a/experiments/hypotheses/CV SOR 20.py +++ b/experiments/hypotheses/CV SOR 20.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Center Compact Boxes On Point Cloud Median.py b/experiments/hypotheses/Center Compact Boxes On Point Cloud Median.py index 68aefbbc3cb037328fd218dabf7673aded01dca0..94b4a29f7692d9e671ebb7835375a16b1528fc2b 100644 --- a/experiments/hypotheses/Center Compact Boxes On Point Cloud Median.py +++ b/experiments/hypotheses/Center Compact Boxes On Point Cloud Median.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1807,13 +1818,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1970,9 +1985,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2005,9 +2018,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Center Sigma 15.py b/experiments/hypotheses/Center Sigma 15.py index f13284186c7da29e4575ca2e4ba6b579ee0697fe..caadef1221a3152b5756d221fbc364a204f691b6 100644 --- a/experiments/hypotheses/Center Sigma 15.py +++ b/experiments/hypotheses/Center Sigma 15.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1665,7 +1671,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): weights = np.sqrt(np.asarray(weights, np.float64)) core_centers, core_dimensions, core_weights = centers, dimensions, weights if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1693,7 +1701,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = full_dimensions[consistent] weights = weights[consistent] box_center_local = np.array( - [_weighted_quantile(core_centers[:, axis], core_weights, 0.5) for axis in range(3)] + [ + _weighted_quantile(core_centers[:, axis], core_weights, 0.5) + for axis in range(3) + ] ) # Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents, # not the 75th. A partial/occluded/foreshortened view of an object can only measure a @@ -1738,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1837,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2006,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2041,9 +2057,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Center Sigma 25.py b/experiments/hypotheses/Center Sigma 25.py index 0c2f7280819b43f444b1b95f2ab4959918503d61..62b0922708a21be15b9652071ffb8ea305c67c6c 100644 --- a/experiments/hypotheses/Center Sigma 25.py +++ b/experiments/hypotheses/Center Sigma 25.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1665,7 +1671,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): weights = np.sqrt(np.asarray(weights, np.float64)) core_centers, core_dimensions, core_weights = centers, dimensions, weights if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1693,7 +1701,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = full_dimensions[consistent] weights = weights[consistent] box_center_local = np.array( - [_weighted_quantile(core_centers[:, axis], core_weights, 0.5) for axis in range(3)] + [ + _weighted_quantile(core_centers[:, axis], core_weights, 0.5) + for axis in range(3) + ] ) # Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents, # not the 75th. A partial/occluded/foreshortened view of an object can only measure a @@ -1738,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1837,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2006,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2041,9 +2057,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Clean Box Points At Sixtieth Confidence.py b/experiments/hypotheses/Clean Box Points At Sixtieth Confidence.py index 796e6847e40373cf049305320b4fc70ffed9d961..32e3fc349e24bd595830024404c9658b9f4aff7d 100644 --- a/experiments/hypotheses/Clean Box Points At Sixtieth Confidence.py +++ b/experiments/hypotheses/Clean Box Points At Sixtieth Confidence.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -518,7 +522,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -574,7 +579,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -629,7 +635,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1230,7 +1237,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1612,15 +1620,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1671,7 +1677,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1718,7 +1726,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1814,13 +1825,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1977,9 +1992,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2012,9 +2025,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Clean Distance Path Keep Raw Size Extent.py b/experiments/hypotheses/Clean Distance Path Keep Raw Size Extent.py index 9095304b58b6c244b24a6d2d4f9e37d15bd086c5..b72155f5c91a6505d8e2c833453ad234aeb9cbfe 100644 --- a/experiments/hypotheses/Clean Distance Path Keep Raw Size Extent.py +++ b/experiments/hypotheses/Clean Distance Path Keep Raw Size Extent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1643,7 +1647,8 @@ def _compact_oriented_box(instance, u, v, g, floor_level): # extremes; cleaning only the distance path gives the distance gain without the size cost. raw_proj = ( np.stack( - [observation @ u, observation @ v, observation @ g - floor_level], axis=1 + [observation @ u, observation @ v, observation @ g - floor_level], + axis=1, ) @ orientation.T ) @@ -1680,7 +1685,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1742,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1841,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2010,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2045,9 +2057,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Clean Distance Path Raw Size Select.py b/experiments/hypotheses/Clean Distance Path Raw Size Select.py index 4e411fc97a2cc328aa339f70f8e8a441aa94f368..d651b08963b60bb267eb3c6466b92d7c335e58d6 100644 --- a/experiments/hypotheses/Clean Distance Path Raw Size Select.py +++ b/experiments/hypotheses/Clean Distance Path Raw Size Select.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1643,7 +1647,8 @@ def _compact_oriented_box(instance, u, v, g, floor_level): # extremes; cleaning only the distance path gives the distance gain without the size cost. raw_proj = ( np.stack( - [observation @ u, observation @ v, observation @ g - floor_level], axis=1 + [observation @ u, observation @ v, observation @ g - floor_level], + axis=1, ) @ orientation.T ) @@ -1680,7 +1685,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1742,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() # select the longest axis from the RAW full extent (size's own signal), NOT the cleaned @@ -1845,13 +1855,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2014,9 +2028,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2049,9 +2061,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Clean Each Observation Before Extent Tight.py b/experiments/hypotheses/Clean Each Observation Before Extent Tight.py index 64c26b8c3bfe75f53192f304b0e602e69f9eaaf3..c3fe8801e5e911a46ff3c2f1b82e24dac0e2722c 100644 --- a/experiments/hypotheses/Clean Each Observation Before Extent Tight.py +++ b/experiments/hypotheses/Clean Each Observation Before Extent Tight.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1659,7 +1663,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1675,7 +1681,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1737,7 +1745,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1836,13 +1847,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2005,9 +2020,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2040,9 +2053,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Clean Each Observation Before Extent.py b/experiments/hypotheses/Clean Each Observation Before Extent.py index 6c16a6057004fa5b9dbded1a908a8ac6b4f08fdf..561c688497e4351eacef088f81d702e4f0c5c036 100644 --- a/experiments/hypotheses/Clean Each Observation Before Extent.py +++ b/experiments/hypotheses/Clean Each Observation Before Extent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1659,7 +1663,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1675,7 +1681,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1737,7 +1745,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1836,13 +1847,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2005,9 +2020,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2040,9 +2053,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Confidence Weighted Box Frames.py b/experiments/hypotheses/Confidence Weighted Box Frames.py index a7c4ebb4c9766a3ddb7aa5d4064277466318aef4..a3f3796248c407dc586f1440ff7dd23103a37b4c 100644 --- a/experiments/hypotheses/Confidence Weighted Box Frames.py +++ b/experiments/hypotheses/Confidence Weighted Box Frames.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1226,7 +1233,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1606,15 +1614,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1658,9 +1662,15 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) _mc = 1.0 - if _obs_conf is not None and _oi < len(_obs_conf) and _obs_conf[_oi] is not None: + if ( + _obs_conf is not None + and _oi < len(_obs_conf) + and _obs_conf[_oi] is not None + ): _cf = np.asarray(_obs_conf[_oi], np.float64) _cf = _cf[finite] if len(_cf) == len(finite) else _cf if len(_cf): @@ -1680,7 +1690,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1742,7 +1754,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1841,13 +1856,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2010,9 +2029,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2045,9 +2062,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Confidence Weighted Percentile Short Axes.py b/experiments/hypotheses/Confidence Weighted Percentile Short Axes.py index 8122e429b3adb6b16289ab06a515ba6cfa4b4726..366503757aa7f565a6689e80dccaddfbed52567b 100644 --- a/experiments/hypotheses/Confidence Weighted Percentile Short Axes.py +++ b/experiments/hypotheses/Confidence Weighted Percentile Short Axes.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1226,7 +1233,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1603,7 +1611,8 @@ def _weighted_quantile(values, weights, quantile): def _weighted_percentile_axis(values, weights, q): """Per-column weighted percentile of an (N,3) array; q in [0,100]. Confidence weights let - low-confidence points (mask-bleed at depth boundaries) count less toward the extent.""" + low-confidence points (mask-bleed at depth boundaries) count less toward the extent. + """ out = np.empty(values.shape[1], np.float64) wsum = weights.sum() if wsum <= 0: @@ -1622,15 +1631,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1666,7 +1671,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): ) projected = observed @ orientation.T _cf = None - if _obs_conf is not None and _oi < len(_obs_conf) and _obs_conf[_oi] is not None: + if ( + _obs_conf is not None + and _oi < len(_obs_conf) + and _obs_conf[_oi] is not None + ): _cf = np.asarray(_obs_conf[_oi], np.float64) _cf = _cf[finite] if len(_cf) == len(finite) else None if _cf is not None and len(_cf) == len(projected) and len(projected) >= 8: @@ -1678,7 +1687,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1694,7 +1705,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1756,7 +1769,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1855,13 +1871,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2024,9 +2044,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2059,9 +2077,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Consensus Filter At Two Sigma.py b/experiments/hypotheses/Consensus Filter At Two Sigma.py index 9c12d4d6942eb05122fda37890295cdaf2ff824f..44d023ed9b2403c3df46b31049364feb41364393 100644 --- a/experiments/hypotheses/Consensus Filter At Two Sigma.py +++ b/experiments/hypotheses/Consensus Filter At Two Sigma.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 030.py b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 030.py index decc75bfc961a05136eb22cdff6b8baff1ce27a2..841e63dacf7a3dbb6cd8c2d2df64562fe4f164bd 100644 --- a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 030.py +++ b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 030.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.3) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 040.py b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 040.py index 2ddd208d29c8bd8dacdeb0315762b52b7b37ab53..9311fe285d8bb032a9690df5228bd4b63eaa418a 100644 --- a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 040.py +++ b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 040.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.4) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 050.py b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 050.py index 29731e49a0ce57960d73ecd4c30e816947ea66c5..f45a79d89e462fb962834669825532e7d376721d 100644 --- a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 050.py +++ b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 050.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 060.py b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 060.py index 6ba5e0905c2c7a0dbb978a55e2c48223334dca5a..25abf95ad405bdfb9719c15a58d195a90192fffc 100644 --- a/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 060.py +++ b/experiments/hypotheses/Decouple Tight Short Axes Stable Longest 060.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1723,7 +1731,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.6) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1822,13 +1833,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1991,9 +2006,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2026,9 +2039,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Depth Edge Bleed Cut Alone.py b/experiments/hypotheses/Depth Edge Bleed Cut Alone.py index b43f0025a558bda933c9b19e3d12cfe2bcacb90f..2ee9b46328f03bcab7c9cca3f7d370db061e8e2a 100644 --- a/experiments/hypotheses/Depth Edge Bleed Cut Alone.py +++ b/experiments/hypotheses/Depth Edge Bleed Cut Alone.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -64,7 +63,9 @@ CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0")) DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1" # cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed # -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need. -DEPTH_EDGE_REFINE = os.environ.get("VSI_DEPTH_EDGE_REFINE", "1") == "1" # HYPOTHESIS: ON -- cut mask-bleed at depth boundaries at the source +DEPTH_EDGE_REFINE = ( + os.environ.get("VSI_DEPTH_EDGE_REFINE", "1") == "1" +) # HYPOTHESIS: ON -- cut mask-bleed at depth boundaries at the source # MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that # depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1. MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1" @@ -118,7 +119,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +213,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +439,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +455,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +492,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +519,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +576,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +632,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1234,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1615,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1654,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1672,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2044,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Depth Edge Bleed Cut With Short Axis Median.py b/experiments/hypotheses/Depth Edge Bleed Cut With Short Axis Median.py index 3d891ebb8e508444f0c8fbefeec5fe9c342963b8..39a190622f179f2aab1215c55eb553d7103d3f3f 100644 --- a/experiments/hypotheses/Depth Edge Bleed Cut With Short Axis Median.py +++ b/experiments/hypotheses/Depth Edge Bleed Cut With Short Axis Median.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -64,7 +63,9 @@ CONF_PCT = float(os.environ.get("VSI_CONF_PCT", "0")) DEPTH_COHERENCE = os.environ.get("VSI_DEPTH_COHERENCE", "1") == "1" # cut mask-bleed at per-frame depth edges. Default OFF: it's a NO-OP on the dominant failure (same-depth bleed # -- adjacent objects at similar range have no depth edge), and only helps depth-SEPARATED bleed. Enable per-need. -DEPTH_EDGE_REFINE = os.environ.get("VSI_DEPTH_EDGE_REFINE", "1") == "1" # HYPOTHESIS: ON -- cut mask-bleed at depth boundaries at the source +DEPTH_EDGE_REFINE = ( + os.environ.get("VSI_DEPTH_EDGE_REFINE", "1") == "1" +) # HYPOTHESIS: ON -- cut mask-bleed at depth boundaries at the source # MASK_REFINE (appearance-guided boundary snap): uses the RGB color edge to clip same-depth mask bleed that # depth can't see. Principled + cheap (CPU, no model). Default OFF until validated; enable via VSI_MASK_REFINE=1. MASK_REFINE = os.environ.get("VSI_MASK_REFINE", "0") == "1" @@ -118,7 +119,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +213,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +439,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +455,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +492,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +519,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +576,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +632,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1234,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1615,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1654,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1672,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2044,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Estimate Room Area From Convex Hull Of Coverage.py b/experiments/hypotheses/Estimate Room Area From Convex Hull Of Coverage.py index ffb1f52451a636d82aed561b108d4d007f347625..5dad87b371fd51c0b6623501ee6ae98cf8dab6b5 100644 --- a/experiments/hypotheses/Estimate Room Area From Convex Hull Of Coverage.py +++ b/experiments/hypotheses/Estimate Room Area From Convex Hull Of Coverage.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,20 +1784,26 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] # HYPOTHESIS: model the room floor as the CONVEX HULL of all observed floor + # object-footprint points, rather than the concave morphological region. Partial camera # coverage leaves concave gaps (unvisited corners, occluded strips) that the hull fills in; # the hull of the observed extent bounds the room and recovers area the concave region # drops, attacking the measured room-area underestimate (ratio ~0.82). No fitted constant. - _allpts = np.concatenate([floor_points, footprint_points], axis=0).astype(np.float32) + _allpts = np.concatenate([floor_points, footprint_points], axis=0).astype( + np.float32 + ) if len(_allpts) >= 3: _hull = cv2.convexHull(_allpts)[:, 0, :] if len(_hull) >= 3: @@ -1957,9 +1969,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1992,9 +2002,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Estimate Room Area From Oriented Bounding Rectangle Of Floor.py b/experiments/hypotheses/Estimate Room Area From Oriented Bounding Rectangle Of Floor.py index 740485c099acadc68061a38777060f303369e37e..3364800b39d35afcc4e07675f576cd04687201e4 100644 --- a/experiments/hypotheses/Estimate Room Area From Oriented Bounding Rectangle Of Floor.py +++ b/experiments/hypotheses/Estimate Room Area From Oriented Bounding Rectangle Of Floor.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] # HYPOTHESIS: model the room as the MINIMUM-AREA ORIENTED RECTANGLE enclosing all observed # floor + object-footprint points, rather than the concave morphological floor region. @@ -1793,7 +1803,9 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): # into -- from partial observation, directly attacking the measured systematic room-area # underestimate (ratio ~0.82). No fitted constant: it is the tightest rectangle around this # scene's own observed points. - _allpts = np.concatenate([floor_points, footprint_points], axis=0).astype(np.float32) + _allpts = np.concatenate([floor_points, footprint_points], axis=0).astype( + np.float32 + ) if len(_allpts) >= 3: _rect = cv2.minAreaRect(_allpts) _box = cv2.boxPoints(_rect) @@ -1959,9 +1971,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1994,9 +2004,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Extend Box Height To Floor Contact.py b/experiments/hypotheses/Extend Box Height To Floor Contact.py index 35f0c3b3b7cc5cfbbe7bbf8dd9fab41564967a9e..f67339ea901596a02d70a8f0dc8b7350d5288165 100644 --- a/experiments/hypotheses/Extend Box Height To Floor Contact.py +++ b/experiments/hypotheses/Extend Box Height To Floor Contact.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1980,9 +1995,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2015,9 +2028,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Extend Compact Floor Coverage To Every Object Footprint.py b/experiments/hypotheses/Extend Compact Floor Coverage To Every Object Footprint.py index 68fe260d4aa6cb4ab3e9001cf54f937697a167f3..db59a201205404ee2a3eefd6122722010c523528 100644 --- a/experiments/hypotheses/Extend Compact Floor Coverage To Every Object Footprint.py +++ b/experiments/hypotheses/Extend Compact Floor Coverage To Every Object Footprint.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1765,13 +1771,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1929,9 +1939,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1964,9 +1972,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Fill Object Footprint Convex Hulls.py b/experiments/hypotheses/Fill Object Footprint Convex Hulls.py index e30807003834cf221c695dd168c98116f90351f0..8e905ef8b32a870748f04a37b3dc9fdb6231780b 100644 --- a/experiments/hypotheses/Fill Object Footprint Convex Hulls.py +++ b/experiments/hypotheses/Fill Object Footprint Convex Hulls.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1848,20 +1863,18 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint = np.asarray(footprint, np.float64) if not len(footprint): continue - projected_footprint = np.stack( - [footprint @ u, footprint @ v], axis=1 - ) + projected_footprint = np.stack([footprint @ u, footprint @ v], axis=1) projected_footprint = projected_footprint[ np.isfinite(projected_footprint).all(axis=1) ] if not len(projected_footprint): continue - cell_rows = ( - (projected_footprint[:, 0] - x_origin) / resolution - ).astype(np.int32) + 1 - cell_columns = ( - (projected_footprint[:, 1] - y_origin) / resolution - ).astype(np.int32) + 1 + cell_rows = ((projected_footprint[:, 0] - x_origin) / resolution).astype( + np.int32 + ) + 1 + cell_columns = ((projected_footprint[:, 1] - y_origin) / resolution).astype( + np.int32 + ) + 1 if len(projected_footprint) < 3: grid[cell_rows, cell_columns] = 1 continue @@ -2014,9 +2027,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2049,9 +2060,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Floor Contact Plus Tighter Consistency.py b/experiments/hypotheses/Floor Contact Plus Tighter Consistency.py index 0edb7f7d2927f84eff59985636ca8b0904183314..c66ce414da32ffa74fc86c21b6ce7766c79d8357 100644 --- a/experiments/hypotheses/Floor Contact Plus Tighter Consistency.py +++ b/experiments/hypotheses/Floor Contact Plus Tighter Consistency.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1980,9 +1995,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2015,9 +2028,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Fuller Robust Box By One Ninetynine Per Frame.py b/experiments/hypotheses/Fuller Robust Box By One Ninetynine Per Frame.py index e4669ded9698bf192d416345ce58f1e0eca9efaa..d5ee75e3ddb37f4b24becf5822def86c4561ca66 100644 --- a/experiments/hypotheses/Fuller Robust Box By One Ninetynine Per Frame.py +++ b/experiments/hypotheses/Fuller Robust Box By One Ninetynine Per Frame.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 99, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Increase Compact Room Floor Area by 20 Percent.py b/experiments/hypotheses/Increase Compact Room Floor Area by 20 Percent.py index a4ba349f339679db820fe6f2249bfa1a2ae46549..76cd259942150efc21b0be3da1bec3ce0294ae37 100644 --- a/experiments/hypotheses/Increase Compact Room Floor Area by 20 Percent.py +++ b/experiments/hypotheses/Increase Compact Room Floor Area by 20 Percent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1732,7 +1738,9 @@ def _compact_scene_points(scene): return np.concatenate(points, axis=0) if points else scene["scene_pts"] -_ROOM_AREA_FACTOR = 1.20 # HYPOTHESIS: correct the measured reconstruction-coverage undershoot +_ROOM_AREA_FACTOR = ( + 1.20 # HYPOTHESIS: correct the measured reconstruction-coverage undershoot +) def _scale_polygon_from_centroid(coordinates, linear_factor): @@ -1747,7 +1755,8 @@ def _scale_polygon_from_centroid(coordinates, linear_factor): structurally a lower bound on true floor area, never an overestimate. Scaling the boundary outward from its own centroid is a cheap, shape-preserving way to correct that measured bias; since area scales with the SQUARE of a linear scale factor, linear_factor here is - sqrt(_ROOM_AREA_FACTOR) so the resulting polygon's area increases by _ROOM_AREA_FACTOR.""" + sqrt(_ROOM_AREA_FACTOR) so the resulting polygon's area increases by _ROOM_AREA_FACTOR. + """ pts = np.asarray(coordinates, dtype=np.float64) if len(pts) < 3: return coordinates @@ -1819,8 +1828,7 @@ def _compact_floor_boundary_polygons(points, u, v): linear_factor, ), "interior hole boundary coordinates": [ - _scale_polygon_from_centroid(hole, linear_factor) - for hole in holes + _scale_polygon_from_centroid(hole, linear_factor) for hole in holes ], } ) @@ -1927,9 +1935,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1962,9 +1968,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Keep More Floor Extent By Wider Clip.py b/experiments/hypotheses/Keep More Floor Extent By Wider Clip.py index 50dcc790e3820bc66eabedd793f7f403e3e7a657..2dc4bc965a485f73551b29f36bc7591f7e27b6d4 100644 --- a/experiments/hypotheses/Keep More Floor Extent By Wider Clip.py +++ b/experiments/hypotheses/Keep More Floor Extent By Wider Clip.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Keep Smaller Observed Floor Patches.py b/experiments/hypotheses/Keep Smaller Observed Floor Patches.py index badcf880303cb633eb9e077c37202890a43b5ab7..c2ba13990adddb0f48131b3c3efb0ef984a8c53a 100644 --- a/experiments/hypotheses/Keep Smaller Observed Floor Patches.py +++ b/experiments/hypotheses/Keep Smaller Observed Floor Patches.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1810,13 +1821,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1976,9 +1991,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2011,9 +2024,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Longest Axis Full Max Post Decouple.py b/experiments/hypotheses/Longest Axis Full Max Post Decouple.py index c4e6f0c7d26f68fa045bf98f143d220e72d4b914..3e45a207432d429450d052ca231b78fdf2703a1b 100644 --- a/experiments/hypotheses/Longest Axis Full Max Post Decouple.py +++ b/experiments/hypotheses/Longest Axis Full Max Post Decouple.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1728,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): # longest-axis extent now recovered at the FULL max across frames (distance is decoupled # onto the tightened short axes, so inflating the longest axis no longer costs distance). full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 1.0) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 1.0) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1827,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1996,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2031,9 +2044,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Longest Axis View Union Full Post Decouple.py b/experiments/hypotheses/Longest Axis View Union Full Post Decouple.py index 256944b501997b9a5c7b45bc835a8b3520f27e84..2bd9f519f27cf880e154ace276872328a862ccf1 100644 --- a/experiments/hypotheses/Longest Axis View Union Full Post Decouple.py +++ b/experiments/hypotheses/Longest Axis View Union Full Post Decouple.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) # longest axis also considers the UNION of all views (all clean points at once), which # spans the object even when no single frame does. Only the longest axis (size); distance @@ -1832,13 +1843,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2001,9 +2016,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2036,9 +2049,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Longest Axis View Union Robust Post Decouple.py b/experiments/hypotheses/Longest Axis View Union Robust Post Decouple.py index f4e5c79e073679d70b7a75e661d4fe817bdf7c92..88d7b233b71963cc4a7e0ecfb4c5c1722a310e0a 100644 --- a/experiments/hypotheses/Longest Axis View Union Robust Post Decouple.py +++ b/experiments/hypotheses/Longest Axis View Union Robust Post Decouple.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,13 +1734,18 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) # longest axis also considers the UNION of all views (all clean points at once), which # spans the object even when no single frame does. Only the longest axis (size); distance # is on the tightened short axes. robust 1/99 union. _proj_all = room_points @ orientation.T - _union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile(_proj_all, 1, axis=0) + _union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile( + _proj_all, 1, axis=0 + ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) box_dimensions[longest_axis] = max( @@ -1832,13 +1845,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2001,9 +2018,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2036,9 +2051,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Merge Never-Co-Observed Overlapping Same-Class Tracks.py b/experiments/hypotheses/Merge Never-Co-Observed Overlapping Same-Class Tracks.py index bb991552e355fdf6074497ab31b76d3e13a7aca8..cb9650f8b4cad37546cd6d27cbd1bbff30fafde8 100644 --- a/experiments/hypotheses/Merge Never-Co-Observed Overlapping Same-Class Tracks.py +++ b/experiments/hypotheses/Merge Never-Co-Observed Overlapping Same-Class Tracks.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1811,7 +1817,8 @@ def _compact_duplicate_groups(instances): tracked data (no benchmark-fit constant, no scene-relative distance cutoff). Motivated by the abs_distance ground-truth comparison (thinking-in-space meta_info object_bbox): the worst distance errors concentrate specifically in class pairs with >1 tracked instance, - where a spuriously-close near-duplicate track can be picked as the "closest pair".""" + where a spuriously-close near-duplicate track can be picked as the "closest pair". + """ count = len(instances) parent = list(range(count)) @@ -1921,9 +1928,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1956,9 +1961,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Merge Same-Class Instances With Contained Centers.py b/experiments/hypotheses/Merge Same-Class Instances With Contained Centers.py index a8f56c3c41827949553eec171e3b8c3ea171263e..d3f86bb04bb1857271f079dbb18824088d732eb4 100644 --- a/experiments/hypotheses/Merge Same-Class Instances With Contained Centers.py +++ b/experiments/hypotheses/Merge Same-Class Instances With Contained Centers.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1861,7 +1867,8 @@ def _compact_duplicate_groups(instances): np.all(centers[first] >= lower_b) and np.all(centers[first] <= upper_b) ) center_b_in_a = bool( - np.all(centers[second] >= lower_a) and np.all(centers[second] <= upper_a) + np.all(centers[second] >= lower_a) + and np.all(centers[second] <= upper_a) ) if overlap >= 0.8 or center_a_in_b or center_b_in_a: union(first, second) @@ -1934,9 +1941,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1969,9 +1974,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Orient Compact Boxes By Minimum Area Rectangle.py b/experiments/hypotheses/Orient Compact Boxes By Minimum Area Rectangle.py index d693396fa936f7bbc18ecf487a9870db3a4635d6..6f69d7640d9b1c3e0d6344b9da36eb0a3866d9a7 100644 --- a/experiments/hypotheses/Orient Compact Boxes By Minimum Area Rectangle.py +++ b/experiments/hypotheses/Orient Compact Boxes By Minimum Area Rectangle.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] # HYPOTHESIS: orient the box by the MINIMUM-AREA enclosing rectangle of the horizontal # footprint (cv2.minAreaRect / rotating calipers), not the SVD principal axis. The # tightest enclosing rectangle is the most faithful box orientation for a rigid object; @@ -1661,7 +1665,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1784,13 +1790,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1947,9 +1957,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1982,9 +1990,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Recover Length Axis From View Union Full.py b/experiments/hypotheses/Recover Length Axis From View Union Full.py index 7a0654fd5d97653c473d08e86b81157a37fd145a..6cdc71c65a5fec01858fbd8f27c5413ed6a02029 100644 --- a/experiments/hypotheses/Recover Length Axis From View Union Full.py +++ b/experiments/hypotheses/Recover Length Axis From View Union Full.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) # HYPOTHESIS: recover the longest axis from the UNION of all views, not the fullest single # frame. full_axis_dimensions above takes the biggest single frame's extent -- but when no @@ -1821,13 +1832,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1984,9 +1999,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2019,9 +2032,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Recover Length Axis From View Union Robust.py b/experiments/hypotheses/Recover Length Axis From View Union Robust.py index 460cb9b78189c347a061e5c635eaeab700ad172f..9576abc73ebea23d3d8a637261f8043db4f20c88 100644 --- a/experiments/hypotheses/Recover Length Axis From View Union Robust.py +++ b/experiments/hypotheses/Recover Length Axis From View Union Robust.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) # HYPOTHESIS: recover the longest axis from the UNION of all views, not the fullest single # frame. full_axis_dimensions above takes the biggest single frame's extent -- but when no @@ -1721,7 +1732,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): # straight off that combined cloud (robust 1/99 percentile span, so a stray point can't # inflate it). Vertical/side axes untouched, so abs_distance is unaffected. _proj_all = room_points @ orientation.T - _union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile(_proj_all, 1, axis=0) + _union_ext = np.percentile(_proj_all, 99, axis=0) - np.percentile( + _proj_all, 1, axis=0 + ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) box_dimensions[longest_axis] = max( @@ -1821,13 +1834,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1984,9 +2001,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2019,9 +2034,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Recover Length Axis Keep Robust Width Depth.py b/experiments/hypotheses/Recover Length Axis Keep Robust Width Depth.py index 3f4f0528baf365dddf6c66af0cfb0da1a7aeee78..b9291026c3af7d953ada8d5ae70ad3738829f495 100644 --- a/experiments/hypotheses/Recover Length Axis Keep Robust Width Depth.py +++ b/experiments/hypotheses/Recover Length Axis Keep Robust Width Depth.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1707,7 +1715,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1803,13 +1814,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1966,9 +1981,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2001,9 +2014,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Recover Length Axis To Full Max.py b/experiments/hypotheses/Recover Length Axis To Full Max.py index 58a26c6125fd48cb9fb8f800a45da79441ff005e..07482e9fc6a6312458fbcfa5d4ad80a679cca45b 100644 --- a/experiments/hypotheses/Recover Length Axis To Full Max.py +++ b/experiments/hypotheses/Recover Length Axis To Full Max.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 1.0) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 1.0) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Recover Longest Two Axes To Full Extent.py b/experiments/hypotheses/Recover Longest Two Axes To Full Extent.py index 9eef304fecff549bb7740de1d3e1151fd3e23221..5c1772602e3189e7aa8221277d675ea56552c5a6 100644 --- a/experiments/hypotheses/Recover Longest Two Axes To Full Extent.py +++ b/experiments/hypotheses/Recover Longest Two Axes To Full Extent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) # HYPOTHESIS variant: recover full extent on the longest TWO axes, not just the single # longest -- when the two largest axes are close, "which is longest" is noisy, and the size @@ -1807,13 +1818,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1970,9 +1985,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2005,9 +2018,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Reject Below-Floor Compact Box Observations.py b/experiments/hypotheses/Reject Below-Floor Compact Box Observations.py index c2f057ebd4407bfd7f723998f3761d3c307def53..f721d03f6c30f60cc9b42f5358911da7c9f689e8 100644 --- a/experiments/hypotheses/Reject Below-Floor Compact Box Observations.py +++ b/experiments/hypotheses/Reject Below-Floor Compact Box Observations.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1676,7 +1680,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1919,9 +1925,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1954,9 +1958,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Reject Below-Floor Observations Only When Minority.py b/experiments/hypotheses/Reject Below-Floor Observations Only When Minority.py index 7ab3e68c3b292c15f4069296ca3eafd3c77f7bce..cb6035e556391f69dbc8af2634ba8107a783283d 100644 --- a/experiments/hypotheses/Reject Below-Floor Observations Only When Minority.py +++ b/experiments/hypotheses/Reject Below-Floor Observations Only When Minority.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1678,7 +1682,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1921,9 +1927,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1956,9 +1960,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Retain All Consolidated Track Instances Regardless Of Peak.py b/experiments/hypotheses/Retain All Consolidated Track Instances Regardless Of Peak.py index dfc4afae52b1ea03e29fa6f7a66443029499c539..cfe7348aa51e9f0a7658d3e993b64bfe0ab3dd49 100644 --- a/experiments/hypotheses/Retain All Consolidated Track Instances Regardless Of Peak.py +++ b/experiments/hypotheses/Retain All Consolidated Track Instances Regardless Of Peak.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1931,9 +1937,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Retain Disjoint Instances Beyond Peak.py b/experiments/hypotheses/Retain Disjoint Instances Beyond Peak.py index c46aa04ce8a6c80412dde0b81036d7cea2294556..1a13e992f5741a38d127afd2f13e7c6d57f6ab1b 100644 --- a/experiments/hypotheses/Retain Disjoint Instances Beyond Peak.py +++ b/experiments/hypotheses/Retain Disjoint Instances Beyond Peak.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2012,9 +2027,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2047,9 +2060,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Room Bridge Gap Plus Keep Patches.py b/experiments/hypotheses/Room Bridge Gap Plus Keep Patches.py index 3b719d320d12bb8096ea4cffe7e27ee71995134b..aa9a49a30728730d77eeb01b7a848dc1b533e328 100644 --- a/experiments/hypotheses/Room Bridge Gap Plus Keep Patches.py +++ b/experiments/hypotheses/Room Bridge Gap Plus Keep Patches.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1711,7 +1719,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1810,13 +1821,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1973,9 +1988,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2008,9 +2021,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Room Dense Sampling Plus Hull Fill.py b/experiments/hypotheses/Room Dense Sampling Plus Hull Fill.py index a00531e4ae289099520c7163c9cd5bc1814684dc..b2c4dcb3784932cfaf34ddf81f47d1c1935e90e5 100644 --- a/experiments/hypotheses/Room Dense Sampling Plus Hull Fill.py +++ b/experiments/hypotheses/Room Dense Sampling Plus Hull Fill.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1848,20 +1863,18 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint = np.asarray(footprint, np.float64) if not len(footprint): continue - projected_footprint = np.stack( - [footprint @ u, footprint @ v], axis=1 - ) + projected_footprint = np.stack([footprint @ u, footprint @ v], axis=1) projected_footprint = projected_footprint[ np.isfinite(projected_footprint).all(axis=1) ] if not len(projected_footprint): continue - cell_rows = ( - (projected_footprint[:, 0] - x_origin) / resolution - ).astype(np.int32) + 1 - cell_columns = ( - (projected_footprint[:, 1] - y_origin) / resolution - ).astype(np.int32) + 1 + cell_rows = ((projected_footprint[:, 0] - x_origin) / resolution).astype( + np.int32 + ) + 1 + cell_columns = ((projected_footprint[:, 1] - y_origin) / resolution).astype( + np.int32 + ) + 1 if len(projected_footprint) < 3: grid[cell_rows, cell_columns] = 1 continue @@ -2014,9 +2027,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2049,9 +2060,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Sample Floor Support Every Fourth Pixel.py b/experiments/hypotheses/Sample Floor Support Every Fourth Pixel.py index e26c8189b0d642e16b004483e72978118b491c96..8097e52ad05273d76d63e51ee3932853880350fa 100644 --- a/experiments/hypotheses/Sample Floor Support Every Fourth Pixel.py +++ b/experiments/hypotheses/Sample Floor Support Every Fourth Pixel.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1994,9 +2009,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2029,9 +2042,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Select Distance Instances Using Centroid Stability Across Frames.py b/experiments/hypotheses/Select Distance Instances Using Centroid Stability Across Frames.py index bb4692109bec50dee74244d98e63d300bbc76650..d0e59b184bb160fced2b40b822a26c6bcde4dabc 100644 --- a/experiments/hypotheses/Select Distance Instances Using Centroid Stability Across Frames.py +++ b/experiments/hypotheses/Select Distance Instances Using Centroid Stability Across Frames.py @@ -323,7 +323,14 @@ def _find_cls(name, classes): def _rep(insts): """Prefer the track whose frame centroids are most spatially stable.""" - return min(insts, key=lambda i: (i.get("centroid_stability", float("inf")), -i.get("nframes", len(i.get("frames", ()))), -i["n"])) + return min( + insts, + key=lambda i: ( + i.get("centroid_stability", float("inf")), + -i.get("nframes", len(i.get("frames", ()))), + -i["n"], + ), + ) def answer_rel_direction(point_a, point_b, point_c, up_vec, up_ax, mode="hard"): @@ -857,7 +864,9 @@ def merge_by_box_overlap(insts, up_axis=None): [insts[k]["observation_centroids"] for k in idxs], 0 ) centroid_core = np.median(observation_centroids, axis=0) - centroid_stability = float(np.median(np.linalg.norm(observation_centroids - centroid_core, axis=1))) + centroid_stability = float( + np.median(np.linalg.norm(observation_centroids - centroid_core, axis=1)) + ) c, longest, dims = robust_centroid_extent( best, up_axis ) # size+pos+3 oriented dims from best view (#2/#4) @@ -974,9 +983,13 @@ def build_instances( pts = np.concatenate(plist, 0) cpts = np.concatenate(conf_by_id[oid], 0) consistent = _consistent_observation_indices(plist) - observation_centroids = np.stack([robust_centroid_extent(points, None)[0] for points in plist]) + observation_centroids = np.stack( + [robust_centroid_extent(points, None)[0] for points in plist] + ) centroid_core = np.median(observation_centroids, axis=0) - centroid_stability = float(np.median(np.linalg.norm(observation_centroids - centroid_core, axis=1))) + centroid_stability = float( + np.median(np.linalg.norm(observation_centroids - centroid_core, axis=1)) + ) distance_pts = np.concatenate([plist[index] for index in consistent], 0) distance_conf = np.concatenate( [conf_by_id[oid][index] for index in consistent], 0 @@ -1490,7 +1503,14 @@ def _canonical_clean(inst, cap=4000): def _canonical_rep(insts): - return min(insts, key=lambda i: (i.get("centroid_stability", float("inf")), -i.get("nframes", 0), -i.get("n", len(i["pts"])))) + return min( + insts, + key=lambda i: ( + i.get("centroid_stability", float("inf")), + -i.get("nframes", 0), + -i.get("n", len(i["pts"])), + ), + ) def _canonical_answer_closest_distance(instances_a, instances_b, k=4000): diff --git a/experiments/hypotheses/Size Boxes By Full Per Frame And 75th Across.py b/experiments/hypotheses/Size Boxes By Full Per Frame And 75th Across.py index 1fcde33f5c0bffc77e5e96214d492fee0dacb39f..8e0fbdf2cf4b1c8971c4bf51061731cd730dca56 100644 --- a/experiments/hypotheses/Size Boxes By Full Per Frame And 75th Across.py +++ b/experiments/hypotheses/Size Boxes By Full Per Frame And 75th Across.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1941,9 +1951,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1976,9 +1984,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Size Boxes By Full Per Frame And Median Across.py b/experiments/hypotheses/Size Boxes By Full Per Frame And Median Across.py index 07084a71dbeb4a5b1ae287f010045351f1c719c1..ba5941f69aa34cf38d4b8ba975632a0d9ae2d065 100644 --- a/experiments/hypotheses/Size Boxes By Full Per Frame And Median Across.py +++ b/experiments/hypotheses/Size Boxes By Full Per Frame And Median Across.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1941,9 +1951,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1976,9 +1984,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Size Compact Boxes By Full Per Frame Extent.py b/experiments/hypotheses/Size Compact Boxes By Full Per Frame Extent.py index 0aa021d04e51336d08bcb35f0738fbbc2dcb2a33..be7923833c737c43ed3b6ace816c85a8d6a5ee31 100644 --- a/experiments/hypotheses/Size Compact Boxes By Full Per Frame Extent.py +++ b/experiments/hypotheses/Size Compact Boxes By Full Per Frame Extent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1941,9 +1951,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1976,9 +1984,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Size Compact Boxes By Fuller Per Frame Extent.py b/experiments/hypotheses/Size Compact Boxes By Fuller Per Frame Extent.py index 61b7255f93ec6aaa63ca6743380310ccb43b2eef..1d4b64d3041b531c6d6ccbb3cb2cc03ce64f3b67 100644 --- a/experiments/hypotheses/Size Compact Boxes By Fuller Per Frame Extent.py +++ b/experiments/hypotheses/Size Compact Boxes By Fuller Per Frame Extent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1778,13 +1784,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1941,9 +1951,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1976,9 +1984,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Size Compact Boxes By Fullest Observed Extent.py b/experiments/hypotheses/Size Compact Boxes By Fullest Observed Extent.py index 2249f7fe24f259f06c9f4140aeada90b98942c06..dcb6a3ed6d2235dd7d8858784a9611ae0f784133 100644 --- a/experiments/hypotheses/Size Compact Boxes By Fullest Observed Extent.py +++ b/experiments/hypotheses/Size Compact Boxes By Fullest Observed Extent.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1910,9 +1916,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1945,9 +1949,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Size Compact Boxes By High Observed Extent Percentile.py b/experiments/hypotheses/Size Compact Boxes By High Observed Extent Percentile.py index c703079b596698d42f66fca94beb02a35335ea9b..f902641e8d6975478e02e55fc5669913ec83e622 100644 --- a/experiments/hypotheses/Size Compact Boxes By High Observed Extent Percentile.py +++ b/experiments/hypotheses/Size Compact Boxes By High Observed Extent Percentile.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1655,7 +1659,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1910,9 +1916,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1945,9 +1949,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighten Box Observation Consistency Filter.py b/experiments/hypotheses/Tighten Box Observation Consistency Filter.py index 8c795b0a8804ff68fb4da88f72754207efd62012..e7dd62b705054795fd7104cb65a5763fb4a2d985 100644 --- a/experiments/hypotheses/Tighten Box Observation Consistency Filter.py +++ b/experiments/hypotheses/Tighten Box Observation Consistency Filter.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighten Short Axes At Quantile 050.py b/experiments/hypotheses/Tighten Short Axes At Quantile 050.py index 489fe0c2621b8fb8d8fe077580e715469df105c7..f0318a1aae9e8b921cd4a9b0084aa761c3f84a9a 100644 --- a/experiments/hypotheses/Tighten Short Axes At Quantile 050.py +++ b/experiments/hypotheses/Tighten Short Axes At Quantile 050.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1718,7 +1726,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1986,9 +2001,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2021,9 +2034,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighten Short Axes At Quantile 060.py b/experiments/hypotheses/Tighten Short Axes At Quantile 060.py index 3a84054bdc4f5425383cad1dafccc9ee07589337..b71a57972e272f54d2a420f7318a68203e126feb 100644 --- a/experiments/hypotheses/Tighten Short Axes At Quantile 060.py +++ b/experiments/hypotheses/Tighten Short Axes At Quantile 060.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1718,7 +1726,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.6) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1986,9 +2001,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2021,9 +2034,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighten Short Axes At Quantile 075.py b/experiments/hypotheses/Tighten Short Axes At Quantile 075.py index 3b4f6edb778f6e6e1aa949b5622d24dad03d550c..b1cb19085a127650dab47568008d5a1585fcad23 100644 --- a/experiments/hypotheses/Tighten Short Axes At Quantile 075.py +++ b/experiments/hypotheses/Tighten Short Axes At Quantile 075.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1718,7 +1726,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.75) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1986,9 +2001,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2021,9 +2034,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighter Depth Coherence Fence 10.py b/experiments/hypotheses/Tighter Depth Coherence Fence 10.py index b221ece8a890453309e60c3be92c93ba4fc95dbe..4286086935f09fd9dbf8a003cfb6eb8aa42854bf 100644 --- a/experiments/hypotheses/Tighter Depth Coherence Fence 10.py +++ b/experiments/hypotheses/Tighter Depth Coherence Fence 10.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1227,7 +1234,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1607,15 +1615,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1650,7 +1654,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1666,7 +1672,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1728,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1827,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1996,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2031,9 +2044,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighter Depth Coherence Fence 125.py b/experiments/hypotheses/Tighter Depth Coherence Fence 125.py index 810fd022bc302710ed8fc9cb36d5abdac2914148..70145b638cf01be024fbcca947ef59eb561aa4db 100644 --- a/experiments/hypotheses/Tighter Depth Coherence Fence 125.py +++ b/experiments/hypotheses/Tighter Depth Coherence Fence 125.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1227,7 +1234,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1607,15 +1615,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1650,7 +1654,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1666,7 +1672,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1728,7 +1736,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1827,13 +1838,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1996,9 +2011,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2031,9 +2044,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Tighter Statistical Outlier Removal.py b/experiments/hypotheses/Tighter Statistical Outlier Removal.py index 0bca719708f40d209feb234b21810fcef7c9b685..992a81757d2ab401369980996a05f50208015c20 100644 --- a/experiments/hypotheses/Tighter Statistical Outlier Removal.py +++ b/experiments/hypotheses/Tighter Statistical Outlier Removal.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Trim Mask Bleed By Centroid Distance.py b/experiments/hypotheses/Trim Mask Bleed By Centroid Distance.py index 31d12b1e62f9dcdf28575a6f7e68215442c4d6fb..315e2adcee070ee56bd2943938eed858032d448c 100644 --- a/experiments/hypotheses/Trim Mask Bleed By Centroid Distance.py +++ b/experiments/hypotheses/Trim Mask Bleed By Centroid Distance.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1615,15 +1623,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1658,7 +1662,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1674,7 +1680,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1721,7 +1729,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1817,13 +1828,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1980,9 +1995,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2015,9 +2028,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Two Sigma Center Only.py b/experiments/hypotheses/Two Sigma Center Only.py index 049981111094b8d074284cbe3111e9ca24b1a88a..dce3703963af0e6398b44dfd6f5b4d5f76687e61 100644 --- a/experiments/hypotheses/Two Sigma Center Only.py +++ b/experiments/hypotheses/Two Sigma Center Only.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1665,7 +1671,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): weights = np.sqrt(np.asarray(weights, np.float64)) core_centers, core_dimensions, core_weights = centers, dimensions, weights if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1693,7 +1701,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = full_dimensions[consistent] weights = weights[consistent] box_center_local = np.array( - [_weighted_quantile(core_centers[:, axis], core_weights, 0.5) for axis in range(3)] + [ + _weighted_quantile(core_centers[:, axis], core_weights, 0.5) + for axis in range(3) + ] ) # Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents, # not the 75th. A partial/occluded/foreshortened view of an object can only measure a @@ -1738,7 +1749,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1837,13 +1851,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2006,9 +2024,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2041,9 +2057,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Two Sigma Core Three Sigma Length.py b/experiments/hypotheses/Two Sigma Core Three Sigma Length.py index d009dd08a4f6c2edd8ba0e074b0fd91566e3a19d..8cfa1c300cf9131f0862baf008e3921833197e31 100644 --- a/experiments/hypotheses/Two Sigma Core Three Sigma Length.py +++ b/experiments/hypotheses/Two Sigma Core Three Sigma Length.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1665,7 +1671,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): weights = np.sqrt(np.asarray(weights, np.float64)) core_centers, core_dimensions, core_weights = centers, dimensions, weights if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1693,7 +1701,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = full_dimensions[consistent] weights = weights[consistent] box_center_local = np.array( - [_weighted_quantile(core_centers[:, axis], core_weights, 0.5) for axis in range(3)] + [ + _weighted_quantile(core_centers[:, axis], core_weights, 0.5) + for axis in range(3) + ] ) # Size each axis by a HIGH percentile (0.90) of the mutually-consistent observed extents, # not the 75th. A partial/occluded/foreshortened view of an object can only measure a @@ -1735,10 +1746,16 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) tight_dimensions = np.array( - [_weighted_quantile(core_dimensions[:, axis], core_weights, 0.5) for axis in range(3)] + [ + _weighted_quantile(core_dimensions[:, axis], core_weights, 0.5) + for axis in range(3) + ] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1837,13 +1854,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2006,9 +2027,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2041,9 +2060,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Two Sigma Plus Disjoint Retention.py b/experiments/hypotheses/Two Sigma Plus Disjoint Retention.py index 54d7d0158e067440fe9f10d7694a17fde9d6bb12..ffdbc2306313ef4d77bec2448d2f3c657f73f7ab 100644 --- a/experiments/hypotheses/Two Sigma Plus Disjoint Retention.py +++ b/experiments/hypotheses/Two Sigma Plus Disjoint Retention.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1605,15 +1613,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1648,7 +1652,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1664,7 +1670,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1726,7 +1734,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.5) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = tight_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1825,13 +1836,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -2012,9 +2027,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2047,9 +2060,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Weight Compact Box Consensus By Frame Not Point Count.py b/experiments/hypotheses/Weight Compact Box Consensus By Frame Not Point Count.py index 2ab24f80be883a8264113afa559ab1b0f2b6de97..e06cd5dc42bdec08d28ef1072a385cadaee36ed2 100644 --- a/experiments/hypotheses/Weight Compact Box Consensus By Frame Not Point Count.py +++ b/experiments/hypotheses/Weight Compact Box Consensus By Frame Not Point Count.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1664,7 +1668,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): dimensions = np.asarray(dimensions) weights = np.asarray(weights, np.float64) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1907,9 +1913,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -1942,9 +1946,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis) diff --git a/experiments/hypotheses/Wider Floor Clip Plus Tighter SOR.py b/experiments/hypotheses/Wider Floor Clip Plus Tighter SOR.py index 37fb3d5ef5c68ddc0cfd21ceabac7330964fd2c9..1d88ba82c541f59a3ce17ec8494c54d7c95481e6 100644 --- a/experiments/hypotheses/Wider Floor Clip Plus Tighter SOR.py +++ b/experiments/hypotheses/Wider Floor Clip Plus Tighter SOR.py @@ -24,7 +24,6 @@ import json import numpy as np import cv2 - # ========================================================================================== # CONSTANTS -- geometry-cleanup knobs, merged in from perceptual.py. Env-tunable levers that # affect only the math below (build_instances/backproject_frame/etc.), never model inference. @@ -118,7 +117,8 @@ def room_gravity( ): """Robust UP vector = normal of the RANSAC floor plane (a real physical plane), oriented toward the cameras. Works when the reconstruction is tilted/drifted (ScanNet++) where argmin-extent fails. - Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis).""" + Floor = large planar support with most non-inlier mass on ONE side. Returns (gravity_unit_vec, axis). + """ points = [] for f in range(0, len(depth), fstride): height, width = depth[f].shape @@ -211,7 +211,8 @@ def _floor_basis(up_vec): floor_x world axis projected onto the gravity plane (v the old floor_y axis), so this frame differs from the old axis-drop frame ONLY by the tilt correction -- NO arbitrary in-plane rotation (aligned scenes stay put; only tilt gets corrected). Objects / camera / room_outline - all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too.""" + all share this one gravity-plane frame; floor_area is rotation-invariant so it matches too. + """ g = np.asarray(up_vec, np.float64) g = g / (np.linalg.norm(g) + 1e-12) up_ax = int(np.argmax(np.abs(g))) @@ -436,7 +437,8 @@ def answer_route(ql, cents, up_vec, up_ax): def _sor(pts, k=16, std=2.0, cap=4000): """Statistical outlier removal: drop points whose mean distance to their k nearest neighbors exceeds mean + std*sigma. Removes mask-bleed / depth-speckle points that corrupt a literal closest-point min. - k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob).""" + k=16 and std=2 are universal robust-statistics defaults -- NOT tuned to VSI (no benchmark-fit knob). + """ from scipy.spatial import cKDTree if len(pts) < k + 2: @@ -451,7 +453,8 @@ def _sor(pts, k=16, std=2.0, cap=4000): def _main_cluster(pts): """Keep the object's dominant spatial cluster. Coherent mask-bleed onto a SPATIALLY-SEPARATED adjacent object forms a disconnected component (a gap separates two objects); the true object is the largest one. - Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance.""" + Linkage scale self-calibrates from the cloud's own nearest-neighbor spacing -- no fixed distance. + """ from scipy.spatial import cKDTree if len(pts) < 30: @@ -487,7 +490,8 @@ def _clean(inst, cap=4000): (1) per-point DA3 confidence: boundary mask-bleed = depth discontinuity = LOW conf -> drop below the object's OWN median confidence (data-derived cut); (2) statistical density outlier removal on the survivors; - (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster.""" + (3) dominant spatial cluster: coherent bleed onto a separated adjacent object is a disconnected cluster. + """ if inst.get("_cleanpts") is not None: return inst["_cleanpts"] pts = inst["pts"] @@ -513,7 +517,8 @@ def answer_closest_distance(instances_a, instances_b, k=4000): """Closest distance between the two objects' point clouds ('closest point of each object'). Points are cleaned by _clean (self-calibrated per-object confidence + density) then exact nearest-neighbor min via KD-tree, so mask-bleed/speckle can't collapse the answer. NOTE: VSI's GT is box-to-box on CLEAN annotation - boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring.""" + boxes; the residual gap is object-segmentation quality (bleed), not this formula -- see _clean docstring. + """ points_a = _clean(_rep(instances_a), cap=k) points_b = _clean(_rep(instances_b), cap=k) if len(points_a) == 0 or len(points_b) == 0: @@ -569,7 +574,8 @@ def refine_mask(mask, rgb): """Snap a coarse SAM3 mask boundary to the RGB color edge (appearance-guided). This clips the same-depth bleed that depth CANNOT see: where the halo crosses onto a differently-colored neighbor, the color edge cuts it. Params are DERIVED, not tuned -- radius from frame scale, smoothness from the image's own color - variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode.""" + variance (same MAD-style principle as depth_edges). No model, no GPU. Falls back to grabCut, then erode. + """ if mask.shape[:2] != rgb.shape[:2]: mask = cv2.resize( mask.astype(np.uint8), @@ -624,7 +630,8 @@ def backproject_frame( valid_f: optional precomputed (isfinite & >0) depth mask, reused across all masks of a frame. return_conf: also return the (M,) DA3 confidence of each kept point (for per-point noise-aware cleaning). edges_f: optional per-frame depth-edge map; if given, keep the mask's largest depth-coherent component - (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection).""" + (cuts mask-bleed onto adjacent objects at the depth boundary, per frame, before back-projection). + """ height, width = depth_f.shape empty = ( (np.empty((0, 3), np.float32), np.empty((0,), np.float32)) @@ -1225,7 +1232,8 @@ def dump_spatial_code(code, path): "appearance order" is written as one compact line instead of one line per entry -- it's a single ordered sequence meant to be scanned, not structured data meant to be read field by field like the rest of the code. Every writer of spatial_code.json should go through this - (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart.""" + (not a bare json.dump) so the on-disk format and the prompt-time format never drift apart. + """ body = dict(code) ao = body.pop("appearance order", None) text = json.dumps(body, indent=1).rstrip() @@ -1602,15 +1610,11 @@ def _compact_oriented_box(instance, u, v, g, floor_level): points = _canonical_clean(instance) if not len(points): points = instance["pts"] - room_points = np.stack( - [points @ u, points @ v, points @ g - floor_level], axis=1 - ) + room_points = np.stack([points @ u, points @ v, points @ g - floor_level], axis=1) horizontal = room_points[:, :2] centered = horizontal - np.median(horizontal, axis=0) if len(centered) > 5000: - centered = centered[ - np.random.RandomState(0).choice(len(centered), 5000, False) - ] + centered = centered[np.random.RandomState(0).choice(len(centered), 5000, False)] try: _, _, rotation = np.linalg.svd( centered - centered.mean(axis=0), full_matrices=False @@ -1645,7 +1649,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): upper = np.percentile(projected, 98, axis=0) centers.append((lower + upper) / 2) dimensions.append(np.maximum(upper - lower, 0.0)) - full_dimensions.append(np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0)) + full_dimensions.append( + np.maximum(projected.max(axis=0) - projected.min(axis=0), 0.0) + ) weights.append(len(observation)) if not centers: projected = room_points @ orientation.T @@ -1661,7 +1667,9 @@ def _compact_oriented_box(instance, u, v, g, floor_level): full_dimensions = np.asarray(full_dimensions) weights = np.sqrt(np.asarray(weights, np.float64)) if len(centers) >= 4: - features = np.concatenate([centers, np.log(np.maximum(dimensions, 1e-4))], axis=1) + features = np.concatenate( + [centers, np.log(np.maximum(dimensions, 1e-4))], axis=1 + ) median = np.median(features, axis=0) deviation = np.abs(features - median) scale = 1.4826 * np.median(deviation, axis=0) @@ -1708,7 +1716,10 @@ def _compact_oriented_box(instance, u, v, g, floor_level): [_weighted_quantile(dimensions[:, axis], weights, 0.9) for axis in range(3)] ) full_axis_dimensions = np.array( - [_weighted_quantile(full_dimensions[:, axis], weights, 0.9) for axis in range(3)] + [ + _weighted_quantile(full_dimensions[:, axis], weights, 0.9) + for axis in range(3) + ] ) box_dimensions = robust_dimensions.copy() longest_axis = int(np.argmax(robust_dimensions)) @@ -1804,13 +1815,17 @@ def _compact_floor_boundary_polygons(points, u, v, object_points=None): footprint_points = np.zeros((0, 2), np.float64) if object_points: stacked = [ - np.stack([np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1) + np.stack( + [np.asarray(p, np.float64) @ u, np.asarray(p, np.float64) @ v], axis=1 + ) for p in object_points if len(p) ] if stacked: footprint_points = np.concatenate(stacked, axis=0) - footprint_points = footprint_points[np.isfinite(footprint_points).all(axis=1)] + footprint_points = footprint_points[ + np.isfinite(footprint_points).all(axis=1) + ] resolution = 0.1 combined_for_bounds = np.concatenate([floor_points, footprint_points], axis=0) @@ -1967,9 +1982,7 @@ def _consolidate_compact_instances(instances, stats, up_axis): instance["centroid"] - fragment["centroid"] ), ) - nearest["first_time"] = min( - nearest["first_time"], fragment["first_time"] - ) + nearest["first_time"] = min(nearest["first_time"], fragment["first_time"]) consolidated[class_name] = retained return consolidated @@ -2002,9 +2015,7 @@ def _compact_instances(scene, up_axis): points, up_axis ) record = dict(item) - record.update( - {"centroid": centroid, "size": size, "dims": dimensions} - ) + record.update({"centroid": centroid, "size": size, "dims": dimensions}) measured.append(record) instances[class_name] = _canonical_merge_by_box_overlap(measured, up_axis) instances = _consolidate_compact_instances(instances, stats, up_axis)