Publish experiment 495a67210c5c4cbfab91d013239f7ce9 (rollouts)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/config/a2bdf8f682362ee9bafb36b3d1bdc03c4d3fc5b4f08b36fe8c78f565a8bacd76/config.yamlAdded+12
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/metrics/3e339b42db14cf70581d003c1cebb9ce0838d0f8f97fc19c55765000cb16ce1d/metrics.jsonAdded+12
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522/tracking.pyAdded+93
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/011fe12780cb14ed6ca52c3bffeeb19165164085c948d5c94cb8568ec02a6837/run_geometry_aware_sampling.pyAdded+891
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f/experiment_artifacts.pyAdded+470
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a/benchmark_pca_cuda.pyAdded+92
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/1ff3e91546d35ba17d82119dca0b4398b14ab558b4dbb307b6b2f07abfee071d/selection_report.mdAdded+579
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2164f666f870d868b0464ba58f6c4c4646e15ea89cacc328166e0ab35bd00817/independent_regions.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/24802893205b36414f5d4ce3ca662c9ed320492bec087336786f816bedbc2d3a/html_preview.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252/initialization.pyAdded+77
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866/test_geometry_evaluation.pyAdded+82
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3/run_tracking.pyAdded+254
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diffAdded+259
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb/benchmark_pca_streaming.pyAdded+146
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.pyAdded+81
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2d8489eb8857c37a7c9a954d2aedf9346d473e1bd826ddd710af5f53ec829d7d/selection_attempt_failure.jsonAdded+7
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/34fffe7fbc42ba52159cb5743b92009c3e1f2a4d67278ece35414d9f7d5eaecc/patch_and_selection.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.pyAdded+255
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a/run_rgbd.pyAdded+445
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692/normal_estimators.pyAdded+2
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b/grounding.pyAdded+90
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ce95cd70f328d83ff9d4d79625be38f6a2f3aa28271ec62776a981752c98a74/03g_geometry_aware_sampling.mdAdded+585
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9/run_adaptive_node_budget.pyAdded+745
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890/pca_optimized.pyAdded+2
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ecc0eb1b878568e30590afca24d3445840b70f1c341659b9e52dbeb350bde29/source_hashes.jsonAdded+385
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b/run_pca_optimization.pyAdded+206
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.pyAdded+266
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4b435cbe234dafea7403249306348388206d4afd5e391c613a4b4392ffb5fef5/surface_depth_tradeoff.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942/test_rgbd_evaluation.pyAdded+160
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f/run_local_structural_sampling.pyAdded+944
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4fbb605112f319103364b475ad185d07fdca56cd64e81248b7da0490be0008d6/selection_verification.jsonAdded+134
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/505329aaaab54bdd976a315454e4f5b8624f7a7b68e7e2016be99886e020e2ce/geometry_aware_sampling.npzAdded+3
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/54a9b838fc7128ab7c15ed145fb7ae3ab01bacc38c0a8f476bc50c58c989d429/candidate_3d_ecdf_tail.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a/test_priority_fps_trace.pyAdded+64
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4/test_normal_diagnostics.pyAdded+111
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.pyAdded+475
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/691ce0b1d4a587bdf3cb39cf83b9e036d8745056c1667f04c8e3d1f8f2d45c09/candidate_XZ_coverage.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692/pca_triton.pyAdded+173
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645/test_priority_fps_seed_control.pyAdded+244
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482/pca_torch.pyAdded+150
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/6fcfd638a929e793ba920297942f2b85eb6b00b066058dd0133d32a358648276/run_geometry_aware_sampling.pyAdded+993
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45/experiment_logger.pyAdded+237
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/7978ecae2395dee91aa7ab70c193fee4149cfeb16f08bf9b505259d8276efc59/selection_before_gt.npzAdded+3
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.pyAdded+258
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/7b9cbf88d81131233518433afb3318958353668a6912935d05616afca8450c37/peg_GT_auxiliary.pngAdded
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/83d1edbe90ac4f24b122887bf193183acce6c8b18bb304e6cf256aaf9cf5c0aa/verification.jsonAdded+236
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.pyAdded+206
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d/run_grounding.pyAdded+223
- visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/875b83c1132752313b12b50ae8b6957c9de11a519bee06ce92073b33bd34ade2/patch_diagnostics_before_selection.jsonAdded
123456789101112{ "actual_FPS_calls": 0, "evaluation_calls": 0, "numeric_npz_sha256": "505329aaaab54bdd976a315454e4f5b8624f7a7b68e7e2016be99886e020e2ce", "selection_run_id": "2c3d733de35c4532b2b81a0a751b7ebf", "source_run_id": "7f657cf88baf4f1f89e594252e243e1c", "source_sha256": { "visual/runtime/test/run_geometry_aware_sampling.py": "6fcfd638a929e793ba920297942f2b85eb6b00b066058dd0133d32a358648276", "visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f" }, "task": "03-G report recovery"}123456789101112[ { "metrics": { "eval/task03g_saved_selection/box/candidate_p95_mm": 30.71006532944713, "eval/task03g_saved_selection/box/final_refs": 9, "eval/task03g_saved_selection/peg/candidate_p95_mm": 5.663919174070641, "eval/task03g_saved_selection/peg/final_refs": 149 }, "run_id": "495a67210c5c4cbfab91d013239f7ce9", "step": 0 }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""SAM2 video tracking for runtime visual pipelines.
Example::
tracker = SAM2Tracker() state = tracker.start(video_path, {1: [x1, y1, x2, y2]}) for frame_idx, masks in tracker.track(state): ... tracker.reset(state)
``video_path`` is a directory of RGB frames accepted by SAM2. Boxes use pixelcoordinates in ``[x1, y1, x2, y2]`` format and integer object IDs. Returnedmasks are keyed by tracker ID; each value is a boolean Torch tensor with shape``[height, width]``. ``visual.runtime.rgbd.attach_rgbd`` joins this iterator torecorded RGB-D, camera calibration, and TCP poses. The Visual output includesexplicit conversion from tracker IDs to the object IDs consumed by Graph."""
from __future__ import annotations
from collections.abc import Iterator, Mapping, Sequencefrom pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]DEFAULT_CONFIG = "configs/sam2.1/sam2.1_hiera_s.yaml"DEFAULT_CHECKPOINT = ROOT / "checkpoints" / "sam2.1_hiera_small.pt"
class SAM2Tracker: """Load a SAM2 video predictor once and track prompted objects in videos.
Args: device: Torch device for SAM2 inference. Defaults to ``"cuda"`` to match the existing Visual pipeline. config: SAM2 Hydra config path, relative to the SAM2 package config directory or an absolute path. checkpoint: Model checkpoint path. hydra_overrides: Optional SAM2 model configuration overrides. predictor: Existing SAM2-compatible predictor, useful when another pipeline owns model construction. When provided, model arguments are ignored. """
def __init__(self, device: str = "cuda", config: str = DEFAULT_CONFIG, checkpoint: str | Path = DEFAULT_CHECKPOINT, hydra_overrides: Sequence[str] | None = None, predictor=None): self.device = device if predictor is None: from sam2.build_sam import build_sam2_video_predictor
predictor = build_sam2_video_predictor( config, str(checkpoint), device=device, hydra_overrides_extra=list(hydra_overrides or ()), ) self.predictor = predictor
def start(self, video_path: str | Path, boxes: Mapping[int, Sequence[float]], frame_idx: int = 0) -> dict: """Create a video state and prompt each object with its initial box.""" state = self.predictor.init_state(video_path=str(video_path)) for object_id, box in boxes.items(): coords = np.asarray(box, dtype=np.float32) if coords.shape != (4,): self.predictor.reset_state(state) raise ValueError(f"box for object {object_id} must have four coordinates") self.predictor.add_new_points_or_box( state, frame_idx=frame_idx, obj_id=int(object_id), box=coords ) return state
def track(self, state: dict, start_frame: int = 0) -> Iterator[tuple[int, dict[int, object]]]: """Yield ``(frame_index, {object_id: boolean_mask})`` for each frame.""" for frame_idx, object_ids, logits in self.predictor.propagate_in_video( state, start_frame_idx=start_frame ): masks = { int(object_id): logits[i, 0] > 0 for i, object_id in enumerate(object_ids) } yield int(frame_idx), masks
def reset(self, state: dict) -> None: """Release the predictor's per-video tracking state.""" self.predictor.reset_state(state)
# Keep the concise spelling available alongside the descriptive class name.Tracker = SAM2Tracker123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891"""Task03-G: one offline Frame0 feasibility rule, never a production sampler.
WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_geometry_aware_sampling --original-state DIRNo normal/candidate extraction, baseline FPS replay, sweep or synthetic performance run."""from __future__ import annotations
import argparsefrom dataclasses import fieldsimport htmlfrom html.parser import HTMLParserimport jsonimport osfrom pathlib import Pathimport platformimport reimport shutilimport subprocessimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport numpy as npfrom scipy.sparse import coo_matrixfrom scipy.sparse.csgraph import connected_components
from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digests, register_existing_outputfrom visual.runtime.edge_evidence import PairEvidencefrom visual.runtime.geometry import GeometryParametersfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_local_structural_sampling as previousfrom visual.runtime.test import run_priority_fps_metric_control as priorfrom visual.runtime.test.run_rim_bottleneck import require_equal, write_json, validate_saved_selection
REPO = prior.REPOSTEM = 'geometry_aware_sampling'REPORT = REPO/'docs/visual-graph-integration/03g_geometry_aware_sampling.md'UV_RUN = '1f7ad262dd2e4b2fb0ac805a4eda5278'UV_DIR = REPO/'experiments'/UV_RUNTESTS = ['visual.runtime.test.'+s for s in ( 'test_geometry_aware_sampling', 'test_local_structural_sampling', 'test_priority_fps_metric_control', 'test_sampling', 'test_sampling_geometry', 'test_sampling_evaluation', 'test_priority_fps_trace', 'test_priority_fps_seed_control')]RULES = dict(threshold_deg=20., priority=32, total=256, structural_ratio=.25, patch='X components: same-object support at both ends, no overlap, no depth jump, finite angle <=20 deg', ordering='patch minimum flat ascending; candidate rows flat ascending', weight='Euclidean diagonal of candidate XYZ axis-aligned bbox; zero for empty/singleton/coincident', quota='reserve whole-C seeded anchor; remaining 31 capacity-capped largest remainder; ties patch order', saturation='floor capped by residual capacity, then fractional remainder once per eligible patch; repeat', zero_weight='no minimum quota, no merge, no relaxed gate; leftover goes to global fallback', priority_metric='original XYZ 3D Euclidean within patches; same object seed for each patch', anchor='anchor patch first, initial anchor; remaining patches minimum flat ascending', fallback='current C global lambda=0 FPS order (camera Z zeroed), skip already selected; optional verified saved prefix', surface='original whole X 3D FPS initialized with all P', gt='evaluation only after selection_before_gt.npz; same-pair 2px AND 3mm', comparison='grouping, span allocation, per-patch initialization and distance metric change together', synthetic='seven existing performance fixtures N/A: dense X and PairEvidence absent', adoption='Frame0 feasibility only; no policy adoption or generalization claim')
def ordered_source(flat, shape): previous.uv_from_flat(flat, shape) if len(flat) and not np.all(flat[:-1] < flat[1:]): raise ValueError('source rows must be ascending')
def patch_labels(support_flat, pair): """Temporary observation components only; retain isolated and C-free X rows.""" support_flat = np.asarray(support_flat) ordered_source(support_flat, pair.shape) pixels = np.asarray(pair.pixels) if pixels.ndim != 2 or pixels.shape[1] != 2: raise ValueError('pair pixels require [N,2]') if ((pixels < 0) | (pixels >= np.prod(pair.shape))).any(): raise ValueError('pair outside raster') delta = pixels[:, 1]-pixels[:, 0] right = (delta == 1) & (pixels[:, 0]//pair.shape[1] == pixels[:, 1]//pair.shape[1]) down = delta == pair.shape[1] if not (right | down).all() or len(np.unique(pixels, axis=0)) != len(pixels): raise ValueError('unique right/down pair contract required') expected = np.isin(pixels, support_flat) np.testing.assert_array_equal(pair.supported, expected) gate = (pair.supported.all(1) & ~pair.overlap.any(1) & ~pair.depth_jump & np.isfinite(pair.normal_angle_deg) & (pair.normal_angle_deg <= RULES['threshold_deg'])) rows = np.searchsorted(support_flat, pixels[gate]) graph = coo_matrix((np.ones(len(rows), bool), (rows[:, 0], rows[:, 1])), shape=(len(support_flat), len(support_flat))).tocsr() count, labels = connected_components(graph, directed=False) # scipy normally discovers in row order; explicitly impose minimum source order. minima = np.full(count, np.iinfo(np.int64).max, np.int64) np.minimum.at(minima, labels, support_flat) order = np.argsort(minima, kind='stable') relabel = np.empty(count, np.int64); relabel[order] = np.arange(count) return relabel[labels], gate
def allocate_span(capacity, weights, count): """No zero-span minimum. Returns quota plus unallocated fallback slots.""" cap, w = np.asarray(capacity), np.asarray(weights, float) if cap.ndim != 1 or cap.dtype.kind not in 'iu' or w.shape != cap.shape: raise ValueError('integer capacities and aligned weights required') if (cap < 0).any() or not np.isfinite(w).all() or (w < 0).any() or count < 0: raise ValueError('nonnegative finite allocation inputs required') out = np.zeros(len(cap), np.int64); left = int(count) while left: active = (out < cap) & (w > 0) if not active.any(): break scaled = np.where(active, w/w[active].max(), 0.) real = left*scaled/scaled.sum() take = np.minimum(cap-out, np.floor(real).astype(np.int64)) out += take; left -= int(take.sum()) for g in np.argsort(-(real-np.floor(real)), kind='stable'): if left and active[g] and out[g] < cap[g]: out[g] += 1; left -= 1 return out, left
def prepare(case, pair): """Freeze fragmentation, bbox extrema, weight, capacity and quota before FPS.""" c, x = case['candidate_flat'], case['support_flat'] ordered_source(c, pair.shape); ordered_source(x, pair.shape) cr = np.searchsorted(x, c) if (cr >= len(x)).any() or not np.array_equal(x[cr], c): raise ValueError('C outside X') np.testing.assert_array_equal(case['support_xyz'][cr], case['candidate_xyz']) if not np.isfinite(case['support_xyz']).all(): raise ValueError('finite XYZ required') labels, gate = patch_labels(x, pair) cm = labels[cr]; ng = int(labels.max())+1 if len(labels) else 0 cap = np.bincount(cm, minlength=ng); xn = np.bincount(labels, minlength=ng) spans = np.zeros(ng); rows = [] for g in range(ng): xr, rr = np.flatnonzero(labels == g), np.flatnonzero(cm == g) xx, cc = case['support_xyz'][xr], case['candidate_xyz'][rr] bbox = lambda a: dict(min_xyz_m=a.min(0).tolist(), max_xyz_m=a.max(0).tolist(), span_m=float(np.linalg.norm(a.max(0)-a.min(0)))) if len(a) else None cb = bbox(cc); spans[g] = cb['span_m'] if cb else 0. extreme = np.unique(np.r_[cc.argmin(0), cc.argmax(0)]) if len(cc) else np.empty(0, int) # Sensitivity diagnostic only: never changes weights or selection. loo = [] for i in extreme: remaining = np.delete(cc, i, axis=0) span = float(np.linalg.norm(remaining.max(0)-remaining.min(0))) if len(remaining) else 0. loo.append(dict(source=int(c[rr[i]]), span_without_point_m=span, span_reduction_m=float(spans[g]-span))) rows.append(dict(patch=g, min_flat=int(x[xr[0]]), X=int(xn[g]), C=int(cap[g]), X_bbox=bbox(xx), C_bbox=cb, extrema_leave_one_out=loo)) target = min(RULES['priority'], len(c)) quota = np.zeros(ng, np.int64); ag = None if target: ar = np.flatnonzero(c == case['first']) if len(ar) != 1: raise ValueError('anchor must be in C exactly once') require_equal(int(c[np.random.default_rng(case['seed']).integers(len(c))]), int(case['first']), 'whole-C anchor') ag = int(cm[ar[0]]); quota[ag] = 1 additional, left = allocate_span(cap-quota, spans, target-int(quota.sum())) quota += additional for g, row in enumerate(rows): row.update(weight=float(spans[g]), capacity=int(cap[g]), residual_capacity_after_anchor=int(cap[g]-(g == ag)), anchor_reserved=int(g == ag), additional_allocation=int(additional[g]), quota=int(quota[g])) zero = (cap > 0) & (spans == 0) singleton = xn == 1 return dict(support_patch=labels, candidate_patch=cm, connection_gate=gate, patches=rows, weight=spans, capacity=cap, quota=quota, anchor_patch=ag, fallback_slots=left, diagnostics=dict(X_patches=ng, candidate_patches=int((cap > 0).sum()), X_singleton_patches=int(singleton.sum()), X_singleton_candidates=int(cap[singleton].sum()), candidate_singleton_patches=int((cap == 1).sum()), zero_span_candidate_patches=int(zero.sum()), zero_span_candidates=int(cap[zero].sum()), zero_span_candidate_fraction=float(cap[zero].sum()/len(c)) if len(c) else None, singleton_or_zero_span_patches=int((singleton | zero).sum()), singleton_or_zero_span_candidates=int(cap[singleton | zero].sum()), singleton_or_zero_span_candidate_fraction=float(cap[singleton | zero].sum()/len(c)) if len(c) else None, zero_quota_candidate_patches=int(((cap > 0) & (quota == 0)).sum()), zero_quota_candidates=int(cap[quota == 0].sum()), anchor_patch=ag, anchor_quota=int(quota[ag]) if ag is not None else 0, planned_fallback=left, quota_sum=int(quota.sum())))
def fallback_rows(flat, xyz, seed, anchor, selected, needed, saved_order=None): """Generic current-C global lambda=0 FPS fallback, with optional cached prefix.
A verified prefix is sufficient when it has `needed` unselected rows. Otherwise generate current-C order up to selected+needed; no Task03 artifact is required. """ if not needed: return np.empty(0, np.int64), 'unused' flat = np.asarray(flat); selected = np.asarray(selected, np.int64) if saved_order is not None: order = np.asarray(saved_order) if len(np.unique(order)) != len(order) or not np.isin(order, flat).all() or order[0] != anchor: raise ValueError('invalid verified cached fallback prefix') available = order[~np.isin(order, flat[selected])] if len(available) >= needed: return np.searchsorted(flat, available[:needed]), 'verified_saved_global_prefix' ar = np.flatnonzero(flat == anchor) metric = prior.metric_coordinates(xyz, 0.) order = fps_indices(metric, min(len(flat), len(selected)+needed), seed=seed, initial=ar) available = order[~np.isin(order, selected)] if len(available) < needed: raise ValueError('fallback capacity exhausted') return available[:needed], 'generated_current_C_global_order'
def select_geometry(case, prepared, saved_order=None): """Annotation-free selection. No object names, poses, ROI, scores or references.""" c, xyz = case['candidate_flat'], case['candidate_xyz'] cm, q = prepared['candidate_patch'], prepared['quota'] ag = prepared['anchor_patch'] order = ([ag] if ag is not None else [])+[g for g in range(len(q)) if g != ag and q[g]] selected = []; initial_source = np.full(len(q), -1, np.int64) for g in order: rows = np.flatnonzero(cm == g) initial = np.flatnonzero(c[rows] == case['first']) if g == ag else () local = fps_indices(xyz[rows], int(q[g]), seed=case['seed'], initial=initial) selected.extend(rows[local].tolist()); initial_source[g] = c[rows[local[0]]] before_fallback = np.asarray(selected, np.int64) extra, mode = fallback_rows(c, xyz, case['seed'], case['first'], before_fallback, prepared['fallback_slots'], saved_order) rows = np.r_[before_fallback, extra].astype(np.int64) p = c[rows] initial = np.searchsorted(case['support_flat'], p) frows = fps_indices(case['support_xyz'], case['budget'], seed=case['seed'], initial=initial) f = case['support_flat'][frows] return dict(P=p, S=f[len(p):], F=f, xyz=case['support_xyz'][frows], priority_rows=rows, patch_priority_count=np.bincount(cm[before_fallback], minlength=len(q)), actual_priority_count=np.bincount(cm[rows], minlength=len(q)), fallback_patch_count=np.bincount(cm[extra], minlength=len(q)), fallback_source=c[extra], fallback_mode=mode, patch_initial_source=initial_source)
def selection_input(case): return {k: case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz','seed','first','budget')}
def compatibility(frame, geometry, samples, cases, config, edges, normal): """Validate saved contracts only; never estimate normals or extract candidates.""" parameters = GeometryParameters() for path in (prior.TASK01/'geometry.json', prior.EDGES.parent/'comparison.json', prior.NORMAL.parent/'comparison.json'): cfg = json.loads(path.read_text())['config'] for key in ('input_sha256','masks_sha256','camera'): require_equal(cfg[key], config[key], 'evidence source '+key) if 'parameters' in cfg: require_equal(cfg['parameters'], dict(depth_jump_abs_m=.01, depth_jump_rel=.02), 'depth config') if 'depth_gate_abs_m' in cfg: require_equal((cfg['depth_gate_abs_m'], cfg['depth_gate_rel']), (.01,.02), 'pair depth config') with np.load(prior.TASK01/'f0000.npz', allow_pickle=False) as dense: require_equal(int(dense['source_frame']), 0, 'dense frame') require_equal(str(dense['camera']), config['camera'], 'dense camera') np.testing.assert_array_equal(dense['valid_depth'], np.isfinite(frame.depth) & (frame.depth > 0)) np.testing.assert_array_equal(dense['overlap_mask'], frame.masks[prior.OBJECTS['peg']] & frame.masks[prior.OBJECTS['box']]) for name, oid in prior.OBJECTS.items(): np.testing.assert_array_equal(dense[name+'/valid_points'], geometry.observed_mask(oid)) validate_saved_selection(samples, 'S3_n256_r0.25_t20_s0', frame, geometry) for archive in (edges, normal): require_equal(int(archive['source_frame']), 0, 'pair/normal frame') np.testing.assert_array_equal(archive['intrinsic'], frame.intrinsic) np.testing.assert_array_equal(archive['depth_m'], frame.depth) np.testing.assert_array_equal(edges['shape'], frame.depth.shape) pairs, checks = {}, {} h, w = frame.depth.shape indices = np.arange(h*w, dtype=np.int32).reshape(h, w) for name, case in cases.items(): oid = case['oid']; prefix = 'pca5/'+name+'/' pair = PairEvidence(**{f.name: tuple(edges[prefix+f.name]) if f.name == 'shape' else edges[prefix+f.name].copy() for f in fields(PairEvidence)}) require_equal(pair.shape, frame.depth.shape, 'pair shape') mask = geometry.object_masks[oid] right = mask[:, :-1] | mask[:, 1:]; down = mask[:-1] | mask[1:] expected = np.concatenate((np.column_stack((indices[:, :-1][right], indices[:, 1:][right])), np.column_stack((indices[:-1][down], indices[1:][down])))) np.testing.assert_array_equal(pair.pixels, expected) p = pair.pixels; valid = geometry.valid_depth.ravel()[p]; both = valid.all(1) np.testing.assert_array_equal(pair.supported, geometry.observed_mask(oid).ravel()[p]) np.testing.assert_array_equal(pair.overlap, geometry.overlap_mask.ravel()[p]) np.testing.assert_array_equal(pair.mask_boundary, mask.ravel()[p[:,0]] ^ mask.ravel()[p[:,1]]) np.testing.assert_array_equal(pair.invalid_depth_boundary, valid[:,0] ^ valid[:,1]) z = geometry.xyz[...,2].ravel()[p] delta = np.full(len(p), np.nan, np.float32); delta[both] = z[both,1]-z[both,0] np.testing.assert_array_equal(pair.signed_depth_delta_m, delta) jump = np.zeros(len(p), bool) jump[both] = np.abs(delta[both]) > parameters.depth_jump_abs_m+parameters.depth_jump_rel*z[both].min(1) np.testing.assert_array_equal(pair.depth_jump, jump) near = np.full(len(p), -1, np.int8); near[jump] = z[jump].argmin(1) np.testing.assert_array_equal(pair.near_endpoint, near) np.testing.assert_array_equal(pair.far_endpoint, np.where(jump, 1-near, -1)) for field, value in (('object_mask',mask), ('valid_points',geometry.observed_mask(oid))): np.testing.assert_array_equal(normal[prefix+field], value) nv = normal[prefix+'normal_valid'].ravel()[p].all(1) np.testing.assert_array_equal(np.isfinite(pair.normal_angle_deg), nv) # Recompute pair angles from SAVED reference normals only; no estimator. n = normal[prefix+'normals'].reshape(-1,3)[p[nv]] angle = np.rad2deg(np.arctan2(np.linalg.norm(np.cross(n[:,0],n[:,1]),axis=1), np.einsum('ij,ij->i',n[:,0],n[:,1]))) np.testing.assert_array_equal(pair.normal_angle_deg[nv], angle) endpoint = np.zeros(h*w, bool) high = pair.normal_angle_deg > 20. for k in (0,1): endpoint[p[high & pair.supported[:,k],k]] = True np.testing.assert_array_equal(endpoint.reshape(h,w), edges[prefix+'candidate20/orientation']) np.testing.assert_array_equal(np.flatnonzero(endpoint), case['candidate_flat']) normal_members = normal[prefix+'valid_points'] & (np.rad2deg(normal[prefix+'normal_variation_rad']) > 20.) np.testing.assert_array_equal(np.flatnonzero(normal_members), case['candidate_flat']) for field in ('normal_valid','valid_points','orientation_candidate'): saved = case['saved_features'][field] expected_feature = (endpoint if field == 'orientation_candidate' else normal[prefix+field].ravel())[case['saved_flat']] np.testing.assert_array_equal(saved, expected_feature) pairs[name] = pair checks[name] = dict(status='PASS',pairs=len(p),right=int(right.sum()),down=int(down.sum()), source_object_support_pixel_exact=True, depth_jump_strict_gt=True, reference_angles_exact_from_saved_reference_normals=True, candidate_threshold_membership_exact=True, saved_row_validity_membership_exact=True, optimized_pair_numeric_identity='N/A: full optimized PCA5 pair angles not stored', optimized_connection_gate_identity='N/A: endpoint candidate equality does not prove low-angle pair gate equality') return pairs, checks
def check_selection(case, chosen): c,x = case['candidate_flat'],case['support_flat'] require_equal((len(chosen['P']),len(chosen['F'])), (32,case['budget']), 'fixed budget') require_equal(int(chosen['P'][0]),case['first'],'anchor first') np.testing.assert_array_equal(chosen['F'],np.r_[chosen['P'],chosen['S']]) if not np.isin(chosen['P'],c).all() or not np.isin(c,x).all() or not np.isin(chosen['F'],x).all(): raise ValueError('P subset C subset X / F subset X') require_equal(len(np.unique(chosen['F'])),case['budget'],'unique P/S/F') np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(x,chosen['F'])])
def preserved(original): actual = prior.hashes([REPO/p for p in original]) require_equal(actual,original,'original source/input/artifact hashes') return dict(status='PASS',files=len(original),all_sha256_unchanged=True)
def serial(value): if isinstance(value,np.ndarray):return value.tolist() if isinstance(value,np.generic):return value.item() if isinstance(value,dict):return {k:serial(v) for k,v in value.items()} if isinstance(value,(tuple,list)):return [serial(v) for v in value] return value
def read_reference_selections(cases, baselines): """Read saved lambda=1 / UV controls. No reference selection is rerun.""" selections={} with np.load(UV_DIR/(previous.STEM+'.npz'),allow_pickle=False) as uv: for name,case in cases.items(): one={k:case['saved_flat'][sl].copy() for k,sl in ( ('P',slice(0,32)),('S',slice(32,None)),('F',slice(None)))} one['xyz']=case['support_xyz'][np.searchsorted(case['support_flat'],one['F'])] local={k:uv[f'{name}/local/{k}/flat_index'].copy() for k in ('P','S','F')} local['xyz']=uv[f'{name}/local/F/xyz'].copy() for k in ('P','S','F'): np.testing.assert_array_equal(uv[f'{name}/global/{k}/flat_index'],baselines[name][k]) selections[name]=dict(global0=baselines[name],global1=one,uv=local) for chosen in selections[name].values():check_selection(case,chosen) return selections
def evaluate(frame,geometry,samples,cases,selections,arrays,old,uv_old,input_config): # This function is called ONLY after selection_before_gt exists and is hashed. with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal: contexts=prior.evaluation_inputs(frame,geometry,samples,edges,normal) peg_labels,peg_members=prior.peg_labels(normal['evaluation/peg/face'],normal['evaluation/peg/gt_visible'], normal['evaluation/peg/seam_endpoints'],contexts['peg']['reference'][0]) with np.load(input_config['input'],allow_pickle=False) as episode: box_labels,box_specs,box_transform=prior.rim_labels(contexts['box']['reference'][1],frame.cam2world, episode['box_pose'][0],episode['box_hole_pose'][0],float(episode['box_hole_radii'])) actual={} for name,case in cases.items(): context=contexts[name];labels=peg_labels if name=='peg' else box_labels previous.add_arrays(arrays,'evaluation/'+name,dict(reference_uv=context['reference'][0], reference_xyz=context['reference'][1],observable=context['observable'],GT_reference_segment=labels)) row={} for method,chosen in selections[name].items(): pxyz=case['support_xyz'][np.searchsorted(case['support_flat'],chosen['P'])] spatial,raw=previous.spatial_metrics(case['candidate_flat'],case['candidate_xyz'],chosen['P'],pxyz, case['support_flat'],case['support_xyz'],frame.depth.shape) gt,data=prior.score_case(case,chosen,context,frame,labels, {} if name=='peg' else box_specs,None if name=='peg' else box_transform) previous.add_arrays(arrays,f'{name}/{method}/spatial',raw) previous.add_arrays(arrays,f'evaluation/{name}/{method}',data) row[method]=dict(spatial=spatial,gt=gt) reference = (old['cases']['S3/'+name]['conditions']['0.0'] if method=='global0' else uv_old['actual'][name]['local']['gt'] if method=='uv' else None) if reference is not None: for field in ('coverage','stages','surface_distance_mm','occupancy','feature_availability'): require_equal(gt[field],reference[field],name+'/'+method+' saved metric '+field) base,new=row['global0'],row['geometry'] row['delta_geometry_minus_global0']=dict( C_to_P_mm={k:new['spatial']['mm']['raw'][k]-base['spatial']['mm']['raw'][k] for k in ('mean','p50','p95','max')}, X_to_F_mm={k:new['gt']['surface_distance_mm'][k]-base['gt']['surface_distance_mm'][k] for k in ('mean','p95','max')}, unique_references={s:new['gt']['stages'][s]['unique_reference_count']-base['gt']['stages'][s]['unique_reference_count'] for s in ('C','P','S','F')}, negative_union={s:new['gt']['occupancy']['negative_roi']['known_negative_union'][s]['count']- base['gt']['occupancy']['negative_roi']['known_negative_union'][s]['count'] for s in ('P','S','F')}) actual[name]=row return actual,peg_members
def make_plots(output,frame,cases,prepared,selections,result,arrays): plt.rcParams.update({'font.size':9}) fig,axes=plt.subplots(2,3,figsize=(17,10),constrained_layout=True) for i,(name,case) in enumerate(cases.items()): a=prepared[name];xuv=previous.uv_from_flat(case['support_flat'],frame.depth.shape) cuv=previous.uv_from_flat(case['candidate_flat'],frame.depth.shape) axes[i,0].scatter(*xuv.T,c=a['support_patch']%20,cmap='tab20',s=2,alpha=.6) axes[i,0].scatter(*cuv.T,facecolors='none',edgecolors='black',s=11,lw=.35,label='C on X patches') zero=a['quota'][a['candidate_patch']]==0 axes[i,0].scatter(*cuv[zero].T,c='red',marker='x',s=15,label='C in quota=0 patch') axes[i,0].set_title(f'{name}: observation X patches (colours repeat)') for j,method in enumerate(('global0','geometry'),1): ax=axes[i,j];ax.scatter(*cuv.T,c='gray',s=5,alpha=.5) for stage,color,marker in [('S','#25a8b5','.'),('P','#ed7b24','o')]: uv=previous.uv_from_flat(selections[name][method][stage],frame.depth.shape) ax.scatter(*uv.T,c=color,marker=marker,s=14 if stage=='P' else 9,label=stage) worst=result['actual'][name][method]['spatial']['mm']['worst']['uv'] ax.scatter(*worst,c='red',marker='x',s=80,label='max 3D C->P source') ax.set_title(f'{name}: {method} P / S') for ax in axes[i]:ax.invert_yaxis();ax.set(xlabel='u (px)',ylabel='v (px)');ax.legend(fontsize=7) fig.savefig(output/'patch_and_selection.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(14,10),constrained_layout=True) for i,name in enumerate(cases): for method in ('global0','geometry','global1','uv'): d=arrays[f'{name}/{method}/spatial/ecdf_mm'] axes[i,0].plot(d,np.arange(1,len(d)+1)/len(d),label=method) axes[i,1].plot(d,np.arange(1,len(d)+1)/len(d),label=method) axes[i,0].set(title=f'{name}: all C->P original 3D',xlabel='mm',ylabel='ECDF') axes[i,1].set(title=f'{name}: distance tail',xlabel='mm',ylabel='ECDF',ylim=(.9,1.002)) for ax in axes[i]:ax.legend() fig.savefig(output/'candidate_3d_ecdf_tail.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(15,10),constrained_layout=True) for i,name in enumerate(cases): for j,kind in enumerate(('uv','xyz')): for method,off in [('global0',-.18),('geometry',.18)]: cells=result['actual'][name][method]['spatial']['grids'][kind]['cells'] vals=[c['distance_mm']['p95'] if c['distance_mm']['p95'] is not None else np.nan for c in cells] axes[i,j].bar(np.arange(len(cells))+off,vals,.34,label=method) axes[i,j].set(title=f'{name}: fixed independent {kind} regions',xlabel='region ID',ylabel='C->P p95 mm') axes[i,j].legend() fig.savefig(output/'independent_regions.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(16,10),constrained_layout=True) for i,name in enumerate(cases): rows=[r for r in prepared[name]['patches'] if r['C']] ids=[r['patch'] for r in rows];x=np.arange(len(ids)) axes[i,0].bar(x,[r['C'] for r in rows],label='candidate capacity',color='#b2b9c3') axes[i,0].bar(x,[r['quota'] for r in rows],label='quota',color='#ef7b22') axes[i,0].set(title=f'{name}: candidate patches incl. quota 0',ylabel='count',xticks=x,xticklabels=ids,xlabel='observation patch ID') axes[i,1].bar(x,[r['weight']*1000 for r in rows],color='#327fb7',label='C bbox span') axes[i,1].set(title=f'{name}: allocation weights (not structural length)',ylabel='span mm',xticks=x,xticklabels=ids,xlabel='observation patch ID') for ax in axes[i]:ax.legend();ax.tick_params(axis='x',labelrotation=90) fig.savefig(output/'patch_quota.png',dpi=140);plt.close(fig)
for name in cases: fig,axes=plt.subplots(2,2,figsize=(14,11),constrained_layout=True) refs=arrays[f'evaluation/{name}/reference_uv'] for i,method in enumerate(('global0','geometry')): for j,stage in enumerate(('P','F')): ax=axes[i,j];ax.imshow(frame.rgb) prefix=f'evaluation/{name}/{method}/{stage}' hit=arrays[prefix+'/covered'];matched=arrays[prefix+'/matched_node'] uv=arrays[prefix+'/pixels_vu'][:,::-1] ax.scatter(*refs[~hit].T,c='#d92e76',marker='x',s=18,label='missing GT reference') ax.scatter(*refs[hit].T,c='#1cb58c',s=16,label='covered GT reference') ax.scatter(*uv.T,facecolors='none',edgecolors='#eda420',s=28,label='selected node') ax.scatter(*uv[matched].T,facecolors='none',edgecolors='#2873dc',s=85,label='joint matching node') ax.set(xlim=(refs[:,0].min()-12,refs[:,0].max()+12),ylim=(refs[:,1].max()+12,refs[:,1].min()-12), title=f'{name} {method} {stage}: {matched.sum()} nodes / {hit.sum()} refs') ax.legend(fontsize=7) fig.suptitle('GT auxiliary evaluation labels; separate from observation patch IDs') fig.savefig(output/f'{name}_GT_auxiliary.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,3,figsize=(18,10),constrained_layout=True) for i,(name,case) in enumerate(cases.items()): for j,method in enumerate(('global0','geometry')): x=case['support_xyz'];ax=axes[i,j] ax.scatter(x[:,0]*1000,x[:,2]*1000,c='gray',s=.5,alpha=.3) for stage,color in [('P','#ed7b24'),('S','#20a6b7')]: xyz=x[np.searchsorted(case['support_flat'],selections[name][method][stage])] ax.scatter(xyz[:,0]*1000,xyz[:,2]*1000,c=color,s=15,label=stage) ax.set(title=f'{name} {method}: unfiltered X',xlabel='camera X mm',ylabel='camera Z mm');ax.legend() for method in ('global0','geometry'): d=np.sort(arrays[f'evaluation/{name}/{method}/surface_support_to_final_mm']) axes[i,2].plot(d,np.arange(1,len(d)+1)/len(d),label=method) axes[i,2].set(title=f'{name}: X->F Surface ECDF',xlabel='mm',ylabel='ECDF');axes[i,2].legend() fig.savefig(output/'surface_depth_tradeoff.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(14,10),constrained_layout=True) for i,(name,case) in enumerate(cases.items()): xyz=case['candidate_xyz']*1000 for j,method in enumerate(('global0','geometry')): ax=axes[i,j];d=arrays[f'{name}/{method}/spatial/distance_mm'] sc=ax.scatter(xyz[:,0],xyz[:,2],c=d,cmap='magma',s=14,vmin=0, vmax=max(result['actual'][name][m]['spatial']['mm']['raw']['max'] for m in ('global0','geometry'))) pxyz=case['support_xyz'][np.searchsorted(case['support_flat'],selections[name][method]['P'])]*1000 ax.scatter(pxyz[:,0],pxyz[:,2],facecolors='none',edgecolors='cyan',s=35,label='P') worst=result['actual'][name][method]['spatial']['mm']['worst']['xyz_m'] ax.scatter(worst[0]*1000,worst[2]*1000,c='lime',marker='x',s=80,label='worst source') ax.set(title=f'{name} {method}: original C XZ / distance mm',xlabel='camera X mm',ylabel='camera Z mm') ax.legend();fig.colorbar(sc,ax=ax) fig.savefig(output/'candidate_XZ_coverage.png',dpi=140);plt.close(fig)
def documents(output,result,tests): """Create both documents from the same exact tables and interpretation.""" md=['# Task03-G — Geometry-Aware Structural Sampling, Phase 1 Feasibility',''] page=['<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task03-G Frame0 feasibility</title>', '<style>body{font:16px/1.65 system-ui,sans-serif;max-width:1500px;margin:36px auto;padding:0 24px;color:#203047} ' 'table{border-collapse:collapse;font-size:13px;margin:18px 0;display:block;overflow:auto}th,td{border:1px solid #cbd5e1;padding:6px 9px;white-space:nowrap} ' 'th{background:#eaf1f8}img{width:100%;height:auto}pre{white-space:pre-wrap}a{color:#125caa}</style>', '<h1>Task03-G — Geometry-Aware Structural Sampling</h1>'] def section(title,text=''): md.extend(['## '+title,'',text,'']);page.extend(['<h2>'+html.escape(title)+'</h2>','<p>'+html.escape(text)+'</p>']) def paragraph(text):md.extend([text,'']);page.append('<p>'+html.escape(text)+'</p>') def fmt(v): if v is None:return 'N/A' if isinstance(v,float):return f'{v:.6g}' return str(v) def table(head,rows): rows=[[fmt(v) for v in r] for r in rows] md.extend(['| '+' | '.join(head)+' |','| '+' | '.join(['---']*len(head))+' |']) md.extend('| '+' | '.join(v.replace('|','/') for v in row)+' |' for row in rows);md.append('') page.append('<table><thead><tr>'+''.join('<th>'+html.escape(h)+'</th>' for h in head)+'</tr></thead><tbody>') page.extend('<tr>'+''.join('<td>'+html.escape(v)+'</td>' for v in row)+'</tr>' for row in rows);page.append('</tbody></table>') def plot(filename,caption): md.extend([f'','']) page.append(f'<figure><img src="{filename}" alt="{html.escape(caption)}"><figcaption>{html.escape(caption)}</figcaption></figure>') section('결과 범위와 재현 정보', f"새 ExperimentLogger UUID: {result['run_id']}. ep000 Frame 0 / base_camera / S3(PCA5), N=256, structural_ratio=.25, threshold=20°, seed=0. " 'Peg P/F=32/129, Box P/F=32/127. CPU NumPy/SciPy offline 실행만 수행했다. 일반화 알고리즘 채택 근거가 아닌 관측 patch 단위의 첫 feasibility 실험이다.') paragraph('주 비교는 Task03-E 7f657cf88baf4f1f89e594252e243e1c 저장 Global λ=0이다. Task03 2551448b0fae4c6bbce3caf48774275f Global λ=1과 ' 'Task03-F 1f7ad262dd2e4b2fb0ac805a4eda5278 UV는 참고 비교다. F 최종 UUID는 기존 수치 실행의 문서 후처리이며 독립 반복 실험으로 세지 않는다.') paragraph('선택 규칙은 same-object X의 right/down pair를 기존 4-neighbour 무방향 연결로 복원하고, 양 끝 support·overlap 없음·depth_jump=False·finite angle≤20°로 고정했다. ' 'C의 각 source는 정확히 하나의 X patch에 귀속한다. C-free patch도 X와 Surface에서 보존한다. Weight는 C bbox의 3D 대각선이다. ' '전체 C의 seeded anchor 1점을 보존한 뒤 남은 31점을 capacity-capped largest remainder로 배분하고, patch 내부 원본 3D FPS와 전체 X의 Surface FPS를 사용한다.') section('Evidence compatibility 관문', 'Task01 dense XYZ·validity·mask·overlap·camera·intrinsic·cam2world와 E의 C/X, Task02-C pair source/index/support를 대조했다. ' 'Right pair는 같은 행의 +1, down은 +width이며 각 pair는 한 번만 저장된다. Depth jump는 두 depth가 유효할 때 ' '|z₂−z₁| > .01 + .02×min(z₁,z₂)이다. Equality는 jump��� 아니다. Normal orientation 후보는 >20°, patch 연결은 finite ≤20°다. ' 'NaN angle은 연결하지 않는다. Normal-invalid X는 삭제하지 않는다.') table(['object','pairs','right','down','candidate/support/threshold','optimized pair identity'],[ [n,r['pairs'],r['right'],r['down'],'PASS','N/A'] for n,r in result['compatibility'].items()]) paragraph('Reference PCA5 pair angle은 저장 Task02-B normal에서 직접 재계산해 exact equality를 확인했다. 저장 orientation endpoint 및 normal variation의 >20° membership은 ' 'Task03 optimized PCA5의 저장 C와 일치했고, 저장 선택 행의 validity/candidate membership도 일치했다. ' '하지만 optimized PCA5 전체 pair angle은 저장되지 않았다. Candidate endpoint 집합의 일치가 low-angle pair별 연결 gate의 일치를 보장하지 않는다. ' '따라서 이번 patch는 Task02-C reference PCA5 evidence에서 구성했고 optimized PCA5와 bit-exact라고 주장하지 않는다. Normal estimator/candidate detector는 재실행하지 않았다.') section('선택 전 patch 분절과 allocation', '아래 patch ID는 GT-free 관측상 매끄럽게 연결된 표면 성분이다. Structural edge, physical component, 평가용 seam/rim label 또는 최종 graph edge를 뜻하지 않는다. ' 'Weight=0인 후보 patch에는 anchor 외 minimum quota가 없다. 실패를 보정하기 위한 병합·gate 변경·후보 삭제는 하지 않았다.') table(['object','X patches','C patches','X singleton','0-span C patches','0-span candidates / C','quota=0 C patches','quota=0 candidates','anchor patch/quota','fallback'],[ [n,d['X_patches'],d['candidate_patches'],d['X_singleton_patches'],d['zero_span_candidate_patches'], f"{d['zero_span_candidates']} / {result['counts'][n]['C']} ({d['zero_span_candidate_fraction']*100:.3f}%)", d['zero_quota_candidate_patches'],d['zero_quota_candidates'],f"{d['anchor_patch']} / {d['anchor_quota']}",d['actual_fallback']] for n,d in result['patch_diagnostics'].items()]) for n,d in result['patch_diagnostics'].items(): paragraph(f"{n}: singleton 또는 candidate 0-span patch {d['singleton_or_zero_span_patches']}개, 그 안의 후보 {d['singleton_or_zero_span_candidates']}개 " f"({d['singleton_or_zero_span_candidate_fraction']*100:.3f}%). Candidate가 1개인 patch {d['candidate_singleton_patches']}개, " f"X singleton에 속한 후보 {d['X_singleton_candidates']}개. 실제 fallback={d['actual_fallback']}점.") for name,rows in result['patches'].items(): paragraph(name+' 전체 X patch (C=0 포함): span은 bbox proxy이며 구조 길이가 아니다. Capacity는 전체 C 수, additional은 anchor 제외 배분이다.') table(['patch','min source','X','C/capacity','X span m','C span/weight m','anchor','additional','quota','actual P','fallback P'],[ [r['patch'],r['min_flat'],r['X'],r['C'],r['X_bbox']['span_m'],r['weight'],r['anchor_reserved'], r['additional_allocation'],r['quota'],r['actual_priority'],r['fallback_priority']] for r in rows]) plot('patch_and_selection.png','GT-free X patches, candidate attribution and Global/new P/S') plot('patch_quota.png','Candidate capacity, span weight, quota and zero quota patches') section('Primary — 원본 3D candidate·surface 보존', '모든 거리는 변환하지 않은 CV-camera XYZ의 Euclidean 최근접 거리(mm)다. P의 patch 내부 선택 metric과 독립적으로 평가했다. ' 'Grouping·span allocation·patch별 초기화·patch 내부 3D와 Global λ=0 metric 차이가 묶여 있다. 아래 차이는 선택 규칙 전체의 차이이며 개별 요소의 인과 효과가 아니다.') table(['object','method','C→P mean','p50','p95','max','X→F mean','p95','max'],[ [n,m,*[r[m]['spatial']['mm']['raw'][k] for k in ('mean','p50','p95','max')], *[r[m]['gt']['surface_distance_mm'][k] for k in ('mean','p95','max')]] for n,r in result['actual'].items() for m in ('global0','geometry','global1','uv')]) table(['object','Δ mean','Δ p50','Δ p95','Δ max','Δ Surface mean','Δ Surface p95'],[ [n,*[r['delta_geometry_minus_global0']['C_to_P_mm'][k] for k in ('mean','p50','p95','max')], *[r['delta_geometry_minus_global0']['X_to_F_mm'][k] for k in ('mean','p95')]] for n,r in result['actual'].items()]) table(['object','method','worst source','UV','XYZ m'],[ [n,m,r[m]['spatial']['mm']['worst']['flat_index'],r[m]['spatial']['mm']['worst']['uv'], r[m]['spatial']['mm']['worst']['xyz_m']] for n,r in result['actual'].items() for m in ('global0','geometry')]) plot('candidate_3d_ecdf_tail.png','C→P original 3D ECDF including tail; references are saved controls') plot('candidate_XZ_coverage.png','Candidate XYZ positions, distance tail and worst uncovered source') section('독립 평가 구역과 후보 밀도', 'Task03-F의 X bbox 기반 UV 4×4 및 XYZ 최대 2×2×2 경계와 helper를 그대로 사용했다. Candidate count, 선택률과 거리 분포를 함께 본다. ' 'Box X의 30.726m depth outlier 때문에 XYZ grid의 후보가 한 구역에 들어가는 한계를 보정하지 않았다. ' '전체 분위수는 후보 밀도의 영향을 받으며 구역 동등 가중 p95도 함께 기록한다. XYZ 공간 밀도의 공통 helper 값은 N/A이며 UV 밀도는 px²당 후보 수다.') table(['object','method','grid','C occupied','P=0 regions','equal-region mean p95 mm'],[ [n,m,k,r[m]['spatial']['grids'][k]['candidate_occupied_regions'],r[m]['spatial']['grids'][k]['empty_priority_region_ids'], r[m]['spatial']['grids'][k]['equal_region_mean_p95_mm']] for n,r in result['actual'].items() for m in ('global0','geometry') for k in ('uv','xyz')]) for n,r in result['actual'].items(): for kind in ('uv','xyz'): paragraph(n+' / '+kind+' independent regions:') table(['method','region','C','P','C density/px²','P/C','C→P mean mm','p95','max'],[ [m,c['id'],c['candidate_count'],c['priority_count'],c['candidate_density_per_px2'],c['selection_rate'], *[c['distance_mm'][k] for k in ('mean','p95','max')]] for m in ('global0','geometry') for c in r[m]['spatial']['grids'][kind]['cells']]) plot('independent_regions.png','Independent fixed UV/XYZ regions; empty candidate regions are blank') section('Secondary — GT 기반 보조 진단', '선택 및 selection_before_gt.npz 저장·hash 후 GT reference/pose/ROI를 평가에만 적용했다. ' '동일 point/reference pair가 2px AND 3mm를 만족해야 한다. Peg GT-visible 464개 중 관측 가능 462개, Box 103개 중 103개가 분모다. ' 'Matching node 수와 unique reference 수는 서로 다른 수량이다. 특정 Box rim 선분 개선은 성공 조건이 아니다.') table(['object','method','stage','nodes','matching nodes','unique refs'],[ [n,m,s,gt['gt']['stages'][s]['node_count'],gt['gt']['stages'][s]['structural_matching_nodes'], gt['gt']['stages'][s]['unique_reference_count']] for n,r in result['actual'].items() for m,gt in [(m,r[m]) for m in ('global0','geometry','global1','uv')] for s in ('C','P','S','F')]) table(['object','method','P refs','S refs','F refs','S added refs','P/S overlap refs'],[ [n,m,*[r[m]['gt']['stages'][s]['unique_reference_count'] for s in ('P','S','F')], len(set(r[m]['gt']['stages']['S']['covered_reference_ids'])-set(r[m]['gt']['stages']['P']['covered_reference_ids'])), len(set(r[m]['gt']['stages']['S']['covered_reference_ids'])&set(r[m]['gt']['stages']['P']['covered_reference_ids']))] for n,r in result['actual'].items() for m in ('global0','geometry')]) table(['object','method','stage','GT face-pair/rim segment','observed refs','covered refs','matching nodes'],[ [n,m,s,label,seg['observed_references'],seg['coverage_count'],seg['matching_node_count']] for n,r in result['actual'].items() for m in ('global0','geometry') for s in ('C','P','S','F') for label,seg in r[m]['gt']['stages'][s]['segments'].items()]) paragraph('Box의 verified line projection 간격과 missing-reference run은 JSON/NPZ에 기존 helper 정의로 저장했다. ' 'Peg face-pair 및 ambiguous reference의 물리적 선분 순서는 N/A다. Array 순서를 곡선 길이나 실제 연속 미보존 길이로 해석하지 않는다.') plot('peg_GT_auxiliary.png','Peg GT seam evaluation, separate from GT-free observation patches') plot('box_GT_auxiliary.png','Box GT rim evaluation, separate from GT-free observation patches') section('일반 Surface·negative ROI·depth·outlier trade-off', '일반 Surface는 전체 X→F로 평가한다. S만 따로 평가하거나 far point를 제거하지 않았다. ' 'Known-negative ROI union은 평가용이며 평면 Surface 점유를 자동 오선택이라고 분류하지 않는다. 원본 outlier·depth tail은 그대로 남긴다.') table(['object','method','negative P / 32','negative S','negative F','F exact feature rows','unavailable rows'],[ [n,m,*[r[m]['gt']['occupancy']['negative_roi']['known_negative_union'][s]['count'] for s in ('P','S','F')], r[m]['gt']['feature_availability']['exact_available_rows'],r[m]['gt']['feature_availability']['unavailable_rows']] for n,r in result['actual'].items() for m in ('global0','geometry')]) table(['object','method','stage','depth min m','median','p95','max'],[ [n,m,s,*[r[m]['gt']['occupancy']['depth_m'][s][k] for k in ('min','median','p95','max')]] for n,r in result['actual'].items() for m in ('global0','geometry') for s in ('X','C','P','S','F')]) paragraph('Feature는 같은 S3 조건에서 저장된 23개 field의 exact available 행만 compact gather하고 availability mask/positions를 저장했다. ' 'Missing feature는 근사 ���원하지 않았다. 완전한 production Vision Tensor 검증을 주장하지 않는다.') for name,rows in result['patches'].items(): sensitive=sorted([(e['span_reduction_m'],r,e) for r in rows for e in r['extrema_leave_one_out']],key=lambda x:-x[0])[:3] table(['object','patch','extreme source','original C span m','span without one point m','drop m','quota'],[ [name,r['patch'],e['source'],r['weight'],e['span_without_point_m'],drop,r['quota']] for drop,r,e in sensitive]) paragraph('각 patch의 C/X bbox min/max XYZ와 C extrema source별 leave-one-out span을 저장했다. 위 표는 한 극단점에 민감한 상위 사례다. ' '한 점 제거 span은 진단일 뿐 선택에 적용하지 않았다. Bbox span은 실제 구조 길이가 아니며 camera 축과 outlier에 민감하다.') plot('surface_depth_tradeoff.png','Unfiltered depth and whole X→F Surface trade-off') section('Synthetic 경계와 fallback 계약', '기존 Task03-F 7개 fixture에는 dense X 및 PairEvidence가 없어 새 full-rule performance는 전부 N/A다. ' '구조 label로 patch를 만들거나 새 detector/normal/fixture를 생성하지 않았다. 기존 Global/UV 결과를 새 방법의 검증 결과로 표시하지 않는다.') table(['existing fixture','new full-rule performance','reason'],[[n,'N/A',v['reason']] for n,v in result['synthetic'].items()]) paragraph('일반 fallback은 현재 C만으로 기존 fps_indices()의 Global λ=0 순서를 만들고 이미 선택된 point를 제외해 부족분을 채운다. ' '이번 고정 입력에서는 E의 기존 검증과 저장 순서를 재사용할 수 있으며 NPZ는 fallback 규칙의 필수 입력이 아니다. ' '두 실제 물체의 fallback은 0점이어서 새 결과가 fallback으로 Global FPS를 복제한 경우는 아니다. ' '작은 synthetic 계약 테스트는 입력 C만으로 fallback을 재현하고 depth/normal veto·분리·0-span·capacity·anchor·정렬·결정성·GT 독립성을 확인한다. ' '이 테스트는 실제 형상 또는 sensor noise에 대한 일반화 성능 검증이 아니다.') section('완료 판단 — 여섯 질문', '') for text in result['interpretation_ko']:paragraph(text) section('검증과 미실행 범위',tests) paragraph('Source/input/artifact hash 불변, 모든 C의 단일 patch 귀속, quota/capacity, P=32, F=129/127, ' 'P⊆C⊆X·F⊆X, pixel/XYZ/object/role 정렬, P/S 중복 없음, NPZ exact readback, saved baseline 평가 exact equality를 확인했다. ' 'GT annotation 변경에 따른 전체 선택 불변은 annotation-free 입력/함수 및 작은 full-rule 계약 테스트로 확인하고 실제 선택 전후 archive hash도 유지했다. ' '실제 Frame0 선택을 GT 변경 후 다시 실행하지 않았다. Optimized pair-level 동일성은 N/A다.') paragraph('공통 ExperimentLogger와 experiment_artifacts의 digests/register_existing_output 및 link_output 로컬 API를 재사용했다. ' '실행 소스 snapshot, 시작 dirty diff, 입력 hash, 구현 diff와 tests.log를 새 UUID에 보존했다. ' 'Simulator/renderer·GPU/CUDA/MPS/PCL·추가 frame/episode·normal/candidate 재계산·sweep·production·Graph/GNN/BC·외부 업로드·dependency 설치·commit은 실행하지 않았다. ' 'Adaptive Budget 결합, Task-Relevance, 다른 grouping과 다음 단계는 시작하지 않고 여기서 종료한다.') section('산출물과 원본 링크','') files=[STEM+'.html',STEM+'.json',STEM+'.npz','selection_before_gt.npz','patch_diagnostics_before_selection.json', 'verification.json','tests.log','source_hashes.json','original_hashes.json','preregistered_config.json','implementation.patch'] for filename in files: md.extend([f'[{filename}](../../experiments/{result["run_id"]}/{filename})','']) page.append(f'<p><a href="{filename}">{filename}</a></p>') for p,label in [(previous.BASELINE/(prior.STEM+'.html'),'Task03-E saved baseline'), (UV_DIR/(previous.STEM+'.html'),'Task03-F reference / existing synthetic evidence'), (REPO/'docs/visual-graph-integration/03g_geometry_aware_sampling_plan.md','approved plan')]: md.extend([f'[{label}]({os.path.relpath(p,REPORT.parent)})','']) page.append(f'<p><a href="{os.path.relpath(p,output)}">{label}</a></p>') page.append('<p><a href="../../docs/visual-graph-integration/03g_geometry_aware_sampling.md">Markdown report</a></p></html>') REPORT.write_text('\n'.join(md),encoding='utf-8') (output/'report.md').write_text('\n'.join(md),encoding='utf-8') (output/(STEM+'.html')).write_text('\n'.join(page),encoding='utf-8')
def interpretation(result): d=result['patch_diagnostics']; a=result['actual']; patches=result['patches'] lines=[f"1. 실제 C의 분리: Peg는 X patch {d['peg']['X_patches']}개 중 C patch {d['peg']['candidate_patches']}개, " f"Box��� {d['box']['X_patches']}개 중 {d['box']['candidate_patches']}개다. " '이는 관측 normal/depth gate로 연결된 표면이지 실제 구조의 독립 분해가 아니다.'] allocation=[] for name,rows in patches.items(): allocation.append(name+': '+', '.join(f"patch {r['patch']}={r['quota']}" for r in rows if r['quota'])) lines.append('2. 3D span quota: '+'; '.join(allocation)+'. Peg의 대부분 C는 하나의 큰 surface patch에 연결되어 독립 구조별 예산을 만들지 못했다. ' 'Box는 여러 patch에 배분되었지만 넓은 bbox를 가진 patch에 예산이 집중된다.') primary=[];secondary=[] for n,row in a.items(): b,z=row['global0'],row['geometry'];bg,zg=b['gt'],z['gt'] primary.append(f"{n} C→P mean/p95/max {b['spatial']['mm']['raw']['mean']:.3f}/{b['spatial']['mm']['raw']['p95']:.3f}/{b['spatial']['mm']['raw']['max']:.3f}" f"→{z['spatial']['mm']['raw']['mean']:.3f}/{z['spatial']['mm']['raw']['p95']:.3f}/{z['spatial']['mm']['raw']['max']:.3f}mm; " f"X→F mean/p95 {bg['surface_distance_mm']['mean']:.3f}/{bg['surface_distance_mm']['p95']:.3f}" f"→{zg['surface_distance_mm']['mean']:.3f}/{zg['surface_distance_mm']['p95']:.3f}mm") secondary.append(f"{n} P/F refs {bg['stages']['P']['unique_reference_count']}/{bg['stages']['F']['unique_reference_count']}" f"→{zg['stages']['P']['unique_reference_count']}/{zg['stages']['F']['unique_reference_count']}; " f"negative P/F {bg['occupancy']['negative_roi']['known_negative_union']['P']['count']}/{bg['occupancy']['negative_roi']['known_negative_union']['F']['count']}" f"→{zg['occupancy']['negative_roi']['known_negative_union']['P']['count']}/{zg['occupancy']['negative_roi']['known_negative_union']['F']['count']}") lines.append('3. Global λ=0 대비 3D 보존: '+'; '.join(primary)+'. 손익은 지표별로 해석하며 GT 보존으로 primary 손실을 상쇄하지 않는다.') lines.append('4. 국소 구조·negative ROI: '+'; '.join(secondary)+'. Face-pair/rim 전체 구간과 Surface 추가분·overlap은 위 표에 제시했다. ' '구간별 개선·손실을 합쳐 특정 Box 선분을 성공 기준으로 삼지 않았다.') lines.append(f"5. 제한 요인: Peg/Box의 0-span 후보 {d['peg']['zero_span_candidates']}/{d['box']['zero_span_candidates']}개는 " f"span quota를 받지 못하며 quota=0 후보 patch는 {d['peg']['zero_quota_candidate_patches']}/{d['box']['zero_quota_candidate_patches']}개다. " 'Normal 불연속 주변 후보가 작은 patch로 분절되면 중요한 구조라도 quota에서 사라질 수 있는 설계 취약성이다. ' '실제 fallback은 양쪽 0점이다. Bbox 극단점 민감도와 depth outlier는 제거하지 않았고 span을 구조 길이로 해석하지 않는다.') lines.append('6. 추가 검증 판단: Frame0에서 관측 patch가 어떻게 분리·배분되는지는 재현 가능하게 설명했지만, ' 'Peg의 단일 큰 patch, Box의 fragmentation/zero-quota, reference와 optimized PCA5 pair 차이의 미확인, ' '7개 full-rule synthetic N/A가 남는다. 현재 결과만으로 일반 geometry preservation 후보의 유용성·안정성을 확립하거나 production 채택을 정당화하지 않는다. ' '관측 patch의 유용성에는 제한된 근거만 있으며, 독립 관측·형상·camera에서 같은 고정 규칙의 별도 evidence가 필요하다. 이번에는 추가 검증을 시작하지 않는다.') return lines
def verify_documents(output): class Links(HTMLParser): def __init__(self):super().__init__();self.links=[] def handle_starttag(self,tag,attrs): self.links.extend(v for k,v in attrs if k in ('href','src')) parser=Links();content=(output/(STEM+'.html')).read_text();parser.feed(content) if re.search(r'<script|https?://',content):raise ValueError('HTML must be static and local') for target in parser.links: if not (output/target).is_file():raise ValueError('missing HTML link '+target) targets=re.findall(r'\]\(([^)]+)\)',REPORT.read_text()) for target in targets: if not (REPORT.parent/target).is_file():raise ValueError('missing Markdown link '+target) decoded={} for path in output.glob('*.png'): a=plt.imread(path) if a.ndim != 3 or min(a.shape[:2]) < 400 or a.std()<.01:raise ValueError('invalid PNG '+path.name) decoded[path.name]=list(a.shape) return dict(status='PASS',html_links=len(parser.links),markdown_links=len(targets),png_decoded=decoded)
def run(state_directory): if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required') if REPORT.exists():raise FileExistsError('refuse to overwrite existing report') state_directory=Path(state_directory) original=json.loads((state_directory/'hashes.json').read_text());preserved(original) sources=list((REPO/'visual/runtime').rglob('*.py'))+[REPO/'utils/experiment_logger.py',REPO/'utils/experiment_artifacts.py'] source_hashes=prior.hashes(sources) old=json.loads((previous.BASELINE/(prior.STEM+'.json')).read_text()) uv_old=json.loads((UV_DIR/(previous.STEM+'.json')).read_text()) require_equal(uv_old['run_id'],UV_RUN,'UV reference identity') for p,digest in old['config']['input_sha256'].items():require_equal(digests(REPO/p)[1],digest,'E saved input '+p) require_equal(json.loads((previous.BASELINE/'verification.json').read_text())['status'],'PASS','E baseline verified') input_paths=[REPO/p for p in old['config']['input_sha256']]+[ previous.BASELINE/(prior.STEM+'.npz'),previous.BASELINE/(prior.STEM+'.json'),previous.BASELINE/'verification.json', UV_DIR/(previous.STEM+'.npz'),UV_DIR/(previous.STEM+'.json'),UV_DIR/'verification.json', prior.EDGES.parent/'comparison.json',prior.NORMAL.parent/'comparison.json'] input_hashes=prior.hashes(input_paths) config=dict(task='03-G Phase1 Frame0 feasibility',rules=RULES,episode='ep000',frame=0, method='S3(PCA5)',seed=0,threshold_deg=20,structural_ratio=.25,num_points=256,priority_count=32,budgets=prior.BUDGET, source_run_id=previous.BASELINE_ID,task03=prior.SOURCE_RUN,task03f=UV_RUN, source_sha256=source_hashes,input_sha256=input_hashes,python=platform.python_version(),numpy=np.__version__, device='cpu',simulator_executed=False,gpu_executed=False,production_policy_adopted=False, baseline_FPS_replayed=False,synthetic_performance='N/A',parameters_swept=False) with ExperimentLogger(team='visual',config=config,seed=0,model='task03g_observation_patch_feasibility',job_type='evaluate') as logger: output=logger.directory try: write_json(output/'original_hashes.json',original) write_json(output/'preregistered_config.json',config);frozen_hash=digests(output/'preregistered_config.json')[1] for name in ('git_start.diff','git_status.txt'):shutil.copyfile(state_directory/name,output/name) for source in sources: dest=output/'source_snapshot'/source.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,dest) frame,geometry,samples,cases,baselines,loaded_old,input_config,contracts=previous.load_actual() require_equal(loaded_old,old,'baseline payload') with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal: pairs,gate=compatibility(frame,geometry,samples,cases,input_config,edges,normal) write_json(output/'compatibility.json',gate) selections=read_reference_selections(cases,baselines) prepared={name:prepare(selection_input(case),pairs[name]) for name,case in cases.items()} write_json(output/'patch_diagnostics_before_selection.json',serial(prepared)) print('Evidence compatibility PASS. Patch/weight/quota frozen before FPS.',flush=True) with (output/'tests.log').open('w') as log: tests=subprocess.run([sys.executable,'-m','unittest',*TESTS,'-v'],cwd=REPO,stdout=log,stderr=subprocess.STDOUT) if tests.returncode:raise RuntimeError('contract tests failed before actual selection') test_text=(output/'tests.log').read_text() test_summary=next(l for l in test_text.splitlines() if l.startswith('Ran '))+'; '+test_text.splitlines()[-1] print(test_summary,flush=True) arrays={};patches={};diagnostics={};counts={} for name,case in cases.items(): a=prepared[name] chosen=select_geometry(selection_input(case),a,baselines[name]['P']) check_selection(case,chosen) np.testing.assert_array_equal(chosen['patch_priority_count'],a['quota']) if (a['quota']>a['capacity']).any():raise ValueError('quota exceeds capacity') require_equal(int(a['quota'].sum())+len(chosen['fallback_source']),32,'quota plus fallback') selections[name]['geometry']=chosen counts[name]=dict(X=len(case['support_flat']),C=len(case['candidate_flat']),P=32,F=case['budget']) diagnostics[name]=dict(a['diagnostics'],actual_fallback=len(chosen['fallback_source']),fallback_mode=chosen['fallback_mode']) patches[name]=[dict(r,actual_priority=int(chosen['actual_priority_count'][i]), patch_FPS_priority=int(chosen['patch_priority_count'][i]),fallback_priority=int(chosen['fallback_patch_count'][i]), patch_initial_source=int(chosen['patch_initial_source'][i])) for i,r in enumerate(a['patches'])] previous.add_arrays(arrays,name,{k:case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz')}) previous.add_arrays(arrays,name+'/observation_patch',{k:a[k] for k in ( 'support_patch','candidate_patch','connection_gate','weight','capacity','quota')}) for f in fields(PairEvidence):arrays[f'{name}/observation_pair/{f.name}']=np.asarray(getattr(pairs[name],f.name)) previous.add_arrays(arrays,name+'/geometry/provenance',{k:chosen[k] for k in ( 'priority_rows','patch_priority_count','actual_priority_count','fallback_patch_count','fallback_source','patch_initial_source')}) for method,s in selections[name].items(): check_selection(case,s) for stage in ('P','S','F'): flat=s[stage] previous.add_arrays(arrays,f'{name}/{method}/{stage}',dict(flat_index=flat, pixels_vu=previous.uv_from_flat(flat,frame.depth.shape)[:,::-1], xyz=case['support_xyz'][np.searchsorted(case['support_flat'],flat)], object_id=np.full(len(flat),case['oid']), selection_role=np.full(len(flat),'Priority' if stage=='P' else 'Surface') if stage!='F' else np.where(np.arange(len(flat))<32,'Priority','Surface'))) available,positions,features=prior.feature_rows(case,s['F']) previous.add_arrays(arrays,f'{name}/{method}/F',dict(feature_available=available,feature_available_positions=positions)) previous.add_arrays(arrays,f'{name}/{method}/F/available_features',features) for method in ('global0','geometry','global1','uv'): f=np.concatenate([selections[n][method]['F'] for n in cases]) require_equal((len(f),len(np.unique(f))),(256,256),'cross-object unique budget') arrays['selection_input_hashes_json']=np.array(json.dumps(input_hashes,sort_keys=True)) np.savez_compressed(output/'selection_before_gt.npz',**arrays) before_gt_hash=digests(output/'selection_before_gt.npz')[1] print('Geometry selection fixed and saved before GT. No Global baseline FPS replay.',flush=True) actual,members=evaluate(frame,geometry,samples,cases,selections,arrays,old,uv_old,input_config) result=dict(run_id=logger.run_id,config=config,input_config=input_config,counts=counts, compatibility=gate,source_contract=contracts,patches=patches,patch_diagnostics=diagnostics, actual=actual,peg_memberships=members,selection_before_gt_sha256=before_gt_hash, synthetic={n:dict(status='N/A',reason='existing sparse C has no dense X or PairEvidence') for n in previous.FIXTURES['names']}, performance_success_required=False,contract_status='PASS',production_policy_adopted=False) result['interpretation_ko']=interpretation(result) write_json(output/(STEM+'.json'),serial(result));np.savez_compressed(output/(STEM+'.npz'),**arrays) with np.load(output/(STEM+'.npz'),allow_pickle=False) as saved: require_equal(set(saved.files),set(arrays),'NPZ key set') for k,v in arrays.items():np.testing.assert_array_equal(saved[k],v,err_msg=k) require_equal(digests(output/'selection_before_gt.npz')[1],before_gt_hash,'pre-GT archive unchanged') make_plots(output,frame,cases,prepared,selections,result,arrays) require_equal(prior.hashes(sources),source_hashes,'executed sources unchanged') require_equal(prior.hashes(input_paths),input_hashes,'input hashes unchanged') require_equal(digests(output/'preregistered_config.json')[1],frozen_hash,'frozen config') preservation=preserved(original) write_json(output/'source_hashes.json',dict(sources_before=source_hashes,sources_after=prior.hashes(sources), inputs_before=input_hashes,inputs_after=prior.hashes(input_paths),original_preservation=preservation, historical_task03e_sources=old['config']['source_sha256'])) verification=dict(status='PASS',compatibility=gate,original_preservation=preservation, required_tests=dict(summary=test_summary,modules=TESTS,failed=0), all_C_exactly_one_patch=True,quota_capacity_and_sum=True,fixed_P_F_budgets=True, P_subset_C_subset_X_F_subset_X=True,source_pixel_xyz_object_role_alignment=True, P_S_no_overlap=True,npz_exact_readback=True,pre_GT_archive_sha256_unchanged=True, GT_independence='full-rule synthetic annotation perturbation + annotation-free actual helpers; actual selection rerun=0', joint_matching_and_reference_denominators=True,baseline_and_UV_saved_metric_exact=True, optimized_pair_identity='N/A',synthetic_performance='N/A',source_input_hashes_unchanged=True, feature_unavailable_explicit=True,preregistered_config_sha256=frozen_hash, actual_fps_calls=dict(global_baseline=0,priority_patch=sum(int((p['quota']>0).sum()) for p in prepared.values()), global_fallback=sum(s['geometry']['fallback_mode']=='generated_current_C_global_order' for s in selections.values()),surface=2), no_generalization_or_adoption_claim=True, skipped=['simulator','renderer','GPU/CUDA/MPS/PCL','normal/candidate extraction','sweep','other frames/episodes', 'full-rule synthetic performance','feature reconstruction','production','external upload','install','commit']) write_json(output/'verification.json',verification) # Only this new run owns these targets; originals are never replaced. (output/'implementation.patch').touch() documents(output,result,test_summary) diff=b'' for path in (Path(__file__),Path(__file__).with_name('test_geometry_aware_sampling.py'),REPORT): proc=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,stdout=subprocess.PIPE) if proc.returncode!=1:raise ValueError('implementation diff capture failed') diff+=proc.stdout (output/'implementation.patch').write_bytes(diff) verification['document_checks']=verify_documents(output) write_json(output/'verification.json',verification) for path in sorted(output.rglob('*')): if path.is_file() and not path.name.endswith('.tracking.json') and path.name not in ('metadata.json','manifest.json','config.yaml','metrics.json'): logger.link_output(path,kind='reports') logger.link_output(REPORT,kind='reports') register_existing_output(output,output/(STEM+'.html'),kind='reports') logger.record(source_run_id=previous.BASELINE_ID,task03_source_run_id=prior.SOURCE_RUN, task03f_source_run_id=UV_RUN,selection_before_gt_sha256=before_gt_hash, simulator_executed=False,gpu_executed=False,production_policy_adopted=False) logger.log({n:dict(candidate_mean_mm=r['geometry']['spatial']['mm']['raw']['mean'], candidate_p95_mm=r['geometry']['spatial']['mm']['raw']['p95'], surface_mean_mm=r['geometry']['gt']['surface_distance_mm']['mean'], final_refs=r['geometry']['gt']['stages']['F']['unique_reference_count']) for n,r in actual.items()},step=0,prefix='eval/task03g') print(output,flush=True) except Exception as exc: write_json(output/'attempt_failure.json',dict(status='FAIL',exception_type=type(exc).__name__,reason=str(exc), no_automatic_reselection=True,existing_attempt_preserved=True)) print('Failed attempt preserved at '+str(output),flush=True) raise return output
def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--original-state',type=Path,required=True,help='pre-implementation hashes.json and git_start.diff directory') args=parser.parse_args();run(args.original_state)
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470"""Local artifact inventory and explicit Hugging Face publishing.
No network calls occur in the experiment logger. Team formats remain opaque."""from dataclasses import dataclassimport hashlibimport importlibimport ioimport jsonimport osfrom pathlib import Path, PurePosixPathimport reimport timefrom zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
from .experiment_logger import REPO, clean, load_env_file, write
ORGANIZATION = 'Graph-Recurrent-VLA'DEFAULT_HF_ENV_FILE = Path('/root/.secrets/hf.env')TEAMS = ('visual', 'graph', 'recurrent', 'integration')CATEGORIES = {'checkpoint': 'checkpoint_paths', 'rollouts': 'rollout_video_paths', 'episode_metadata': 'episode_metadata_paths', 'trajectory': 'trajectory_paths', 'metrics': 'additional_metrics_paths', 'reports': 'report_paths'}
@dataclass(frozen=True)class Repository: repo_id: str repo_type: str
DEFAULT_REPOSITORIES = { 'checkpoint': Repository(f'{ORGANIZATION}/graph-recurrent-models', 'model'), 'rollouts': Repository(f'{ORGANIZATION}/graph-recurrent-rollouts', 'dataset'),}
def validate_repositories(repositories): if set(repositories) != set(DEFAULT_REPOSITORIES): raise ValueError('only checkpoint and rollouts repositories are supported') for key, repo in repositories.items(): if not re.fullmatch(r'Graph-Recurrent-VLA/[A-Za-z0-9][A-Za-z0-9._-]*', repo.repo_id): raise ValueError('repositories must belong to Graph-Recurrent-VLA') if repo.repo_type != DEFAULT_REPOSITORIES[key].repo_type: raise ValueError('repository type does not match artifact kind')
def infer_kind(path): suffix = Path(path).suffix.lower() if suffix in ('.pt', '.pth', '.ckpt', '.safetensors', '.bin'): return 'checkpoint' if suffix in ('.mp4', '.webm', '.mov', '.avi', '.mkv'): return 'rollouts' if suffix in ('.h5', '.hdf5', '.npz', '.parquet'): return 'trajectory' if suffix == '.json': return 'metrics' return None
def save_manifest(directory, metadata=None): """Cheap inventory of registered outputs, without hashing or scanning folders.
References are relative to the experiment directory, including external files. Missing registered files remain visible and are validated only when selected. """ directory = Path(directory).resolve() metadata = metadata or json.loads((directory / 'metadata.json').read_text()) manifest = dict(schema_version=1, run_id=metadata['run_id'], team=metadata['team'], model_name=metadata.get('model'), task=metadata.get('task'), environment=metadata.get('environment'), git_commit=metadata.get('git_commit'), git_dirty=metadata.get('git_dirty'), random_seed=metadata.get('seed'), wandb_run_id=metadata['run_id'], config_path='config.yaml', metrics_path='metrics.json', **{field: [] for field in CATEGORIES.values()}) for value in metadata.get('outputs', []): path = Path(value) kind = metadata.get('artifact_kinds', {}).get(str(path)) or infer_kind(path) if kind: manifest[CATEGORIES[kind]].append(os.path.relpath(path, directory)) write(directory / 'manifest.json', manifest) return manifest
def encoded(value): return (json.dumps(clean(value), sort_keys=True, indent=2, allow_nan=False) + '\n').encode()
def digests(source): sha256, git = hashlib.sha256(), hashlib.sha1() size = len(source) if isinstance(source, bytes) else source.stat().st_size git.update(f'blob {size}\0'.encode()) if isinstance(source, bytes): sha256.update(source); git.update(source) else: with source.open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): sha256.update(block); git.update(block) return size, sha256.hexdigest(), git.hexdigest()
@dataclassclass UploadFile: path: str source: object size: int sha256: str git_sha1: str
def upload_file(prefix, category, name, source): size, sha256, git_sha1 = digests(source) return UploadFile(f'{prefix}/artifacts/{category}/{sha256}/{name}', source, size, sha256, git_sha1)
def register_existing_output(directory, path, *, kind): """Attach an explicitly selected artifact to a completed run, without a new ID.
This is also the migration path for a legacy HTML registered as metrics. Existing run identity, status and artifact bytes are retained. """ if kind not in CATEGORIES: raise ValueError('unknown artifact kind') directory, path = Path(directory).resolve(), Path(path).absolute() metadata = json.loads((directory / 'metadata.json').read_text()) if metadata.get('status') == 'running': raise ValueError('finish the experiment before registering post-run artifacts') if directory.name != metadata['run_id']: raise ValueError('experiment directory and run_id do not match') owner = _check_artifact(path, metadata) path = path.resolve() metadata.setdefault('artifact_kinds', {})[str(path)] = kind if str(path) not in metadata.setdefault('outputs', []): metadata['outputs'].append(str(path)) write(directory / 'metadata.json', metadata) if owner in (None, metadata['run_id']): write(path.with_name(path.name + '.tracking.json'), dict(run_id=metadata['run_id'], experiment_directory=str(directory), artifact=str(path))) save_manifest(directory, metadata) return path
def _check_artifact(path, metadata): if path.is_symlink(): raise ValueError('selected files must not be symlinks') if not path.is_file(): raise ValueError(f'missing selected artifact file: {path.name}') sidecar = path.with_name(path.name + '.tracking.json') owner = json.loads(sidecar.read_text()).get('run_id') if sidecar.exists() else None if owner not in (None, metadata['run_id'], metadata.get('source_run_id')): raise ValueError('artifact belongs to another run; refusing stale output link') return owner
def create_report_bundle(directory, selection): """Build a deterministic ZIP from explicit archive-name -> source selections.
No directory scan or new ExperimentLogger is used. Values are paths or {"source": path, "role": "result" | "input" | "dependency"}. JSON members use the shared credential redaction policy. Original files are read only. The content-addressed archive retains relative HTML/image/video paths. """ directory = Path(directory).resolve() metadata = json.loads((directory / 'metadata.json').read_text()) if metadata.get('status') == 'running': raise ValueError('finish the experiment before bundling reports') if directory.name != metadata['run_id']: raise ValueError('experiment directory and run_id do not match') files = selection.get('files', {}) if not isinstance(files, dict) or not files: raise ValueError('report selection requires an explicit nonempty files mapping') members, inventory = {}, [] for name, item in sorted(files.items()): archive = PurePosixPath(name) if (not name or not archive.parts or archive.is_absolute() or '..' in archive.parts or '\\' in name or name != archive.as_posix() or name == 'bundle_manifest.json' or archive.parts[0] == 'experiment'): raise ValueError('report member names must be safe, unique relative paths') spec = item if isinstance(item, dict) else {'source': item} role = spec.get('role', 'result') if role not in ('result', 'input', 'dependency'): raise ValueError('report member role must be result, input or dependency') source = Path(spec['source']).expanduser().absolute() # Inputs/dependencies may come from another run; preserve its known owner. owner_metadata = metadata if role != 'result': sidecar = source.with_name(source.name + '.tracking.json') owner = json.loads(sidecar.read_text()).get('run_id') if sidecar.exists() else None owner_metadata = dict(metadata, source_run_id=owner) owner = _check_artifact(source, owner_metadata) original = source.read_bytes() if not original: raise ValueError('report members must not be empty') body = encoded(json.loads(original)) if source.suffix.lower() == '.json' else original members[name] = body inventory.append(dict(path=name, role=role, source_run_id=owner, source_sha256=hashlib.sha256(original).hexdigest(), sha256=hashlib.sha256(body).hexdigest(), size=len(body))) entrypoint = selection.get('entrypoint') if entrypoint is not None and entrypoint not in members: raise ValueError('report entrypoint must be one of the selected files') # Keep execution identity separate from the later publication/source commit. provenance = {key: metadata.get(key) for key in ('run_id', 'team', 'git_commit', 'git_dirty', 'seed', 'source_run_id', 'dataset_sha256', 'masks_sha256', 'evaluation_device')} manifest = dict(schema_version=1, **provenance, entrypoint=entrypoint, description=selection.get('description'), publication_commit=selection.get('publication_commit'), files=inventory) members['bundle_manifest.json'] = encoded(manifest) for name in ('config.yaml', 'metrics.json'): members[f'experiment/{name}'] = encoded(json.loads((directory / name).read_text())) output = io.BytesIO() with ZipFile(output, 'w', compression=ZIP_DEFLATED, compresslevel=6) as archive: for name, body in sorted(members.items()): info = ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) info.compress_type = ZIP_DEFLATED info.external_attr = 0o100644 << 16 archive.writestr(info, body, compresslevel=6) body = output.getvalue() digest = hashlib.sha256(body).hexdigest() path = directory / 'reports' / f'report-{digest}.zip' if path.exists(): if digests(path)[1] != digest: raise ValueError('existing content-addressed report archive differs') else: path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(body) register_existing_output(directory, path, kind='reports') return path
def plan_upload(directory, include, repositories=None): """Validate only explicit selections; metadata/config accompany each target.""" directory = Path(directory).resolve() repositories = repositories or DEFAULT_REPOSITORIES validate_repositories(repositories) include = set(include) if not include or include - {'checkpoint', 'rollouts', 'metrics', 'reports'}: raise ValueError('select checkpoint, rollouts, metrics and/or reports explicitly') metadata = json.loads((directory / 'metadata.json').read_text()) run_id = metadata['run_id'] if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,127}', run_id) or metadata['team'] not in TEAMS: raise ValueError('invalid run_id or team') if directory.name != run_id: raise ValueError('experiment directory and run_id do not match') if metadata.get('status') == 'running': raise ValueError('finish the experiment before publishing') manifest = save_manifest(directory, metadata) prefix = f'{metadata["team"]}/{run_id}' config = clean(json.loads((directory / 'config.yaml').read_text())) plans = {} targets = include & {'checkpoint', 'rollouts'} if 'reports' in include: targets.add('rollouts') # Reports use the existing dataset repository. if not targets: # metrics-only uses the current model repository, not a future evaluation repo. targets = {'checkpoint'} for target in sorted(targets): remote = {k: v for k, v in manifest.items() if k not in CATEGORIES.values()} remote.pop('config_path'); remote.pop('metrics_path') remote['selection'] = sorted(include) remote['artifacts'] = [] files = []
def add(path, category, *, snapshot=False): path = Path(path) if not path.is_file(): raise ValueError(f'missing selected {category} file: {path.name}') if path.is_symlink(): raise ValueError('selected files must not be symlinks') sidecar = path.with_name(path.name + '.tracking.json') if sidecar.exists(): owner = json.loads(sidecar.read_text()).get('run_id') if owner not in (run_id, metadata.get('source_run_id')): raise ValueError('artifact belongs to another run; refusing stale output link') # JSON is sanitized using the existing logger policy; never load checkpoint code. source = encoded(json.loads(path.read_text())) if snapshot else path item = upload_file(prefix, category, path.name, source) if not item.size: raise ValueError(f'empty selected {category} file: {path.name}') if item.path not in {f.path for f in files}: files.append(item) remote['artifacts'].append(dict(kind=category, path=item.path, size=item.size, sha256=item.sha256)) return item.path
# Use the already sanitized snapshot, without persisting a second local config. cfg = upload_file(prefix, 'config', 'config.yaml', encoded(config)) files.append(cfg); remote['config_path'] = cfg.path if 'metrics' in include: remote['metrics_path'] = add(directory / manifest['metrics_path'], 'metrics', snapshot=True) for value in manifest['additional_metrics_paths']: if Path(value).suffix.lower() != '.json': raise ValueError('metrics artifacts must be JSON; register HTML as reports') add(directory / value, 'metrics', snapshot=True) if target in include: field = CATEGORIES[target] if not manifest[field]: raise ValueError(f'no registered {target} files; use link_output(kind=...)') remote[field] = [add(directory / value, target) for value in manifest[field]] if target == 'rollouts': remote['episode_metadata_paths'] = [add(directory / value, 'episode_metadata', snapshot=True) for value in manifest['episode_metadata_paths']] if 'reports' in include: if not manifest['report_paths']: raise ValueError('no registered reports files; register a report or prepare a bundle') remote['report_paths'] = [add(directory / value, 'reports') for value in manifest['report_paths']] # Immutable per-selection manifest: separate invocations cannot overwrite inventory. body = encoded(remote) digest = hashlib.sha256(body).hexdigest() size, sha256, git_sha1 = digests(body) files.append(UploadFile(f'{prefix}/manifests/{digest}/manifest.json', body, size, sha256, git_sha1)) plans[target] = dict(repository=repositories[target], prefix=prefix, files=files, manifest_path=files[-1].path) return plans
def load_hf_env(path=None): """Load optional HF dotenv credentials, retaining process environment priority.""" return load_env_file(path or os.getenv('HF_ENV_FILE') or DEFAULT_HF_ENV_FILE)
def connect(): """Return no client without an official token. Never return or log the token.""" load_hf_env() try: hub = importlib.import_module('huggingface_hub') except ImportError: return None, None, 'huggingface_hub is missing; install requirements-tracking.txt' try: if not hub.get_token(): return None, None, 'no Hugging Face token; set HF_TOKEN, configure HF_ENV_FILE or /root/.secrets/hf.env, or run hf auth login' return hub.HfApi(), hub.CommitOperationAdd, None except Exception as exc: return None, None, f'Hugging Face authentication unavailable ({type(exc).__name__})'
def initialize_repositories(repositories=None, *, dry_run=False): repositories = repositories or DEFAULT_REPOSITORIES validate_repositories(repositories) if dry_run: return {'status': 'dry-run', 'repositories': [r.repo_id for r in repositories.values()], 'private': True} api, _, reason = connect() if reason: return dict(status='skipped', reason=reason) results = {} try: identity = api.whoami() if identity.get('auth', {}).get('accessToken', {}).get('role') == 'read': return dict(status='skipped', reason='Hugging Face token is read-only; configure an organization write token and rerun --init-repos') allowed = any(org.get('name') == ORGANIZATION and org.get('roleInOrg') in ('admin', 'write', 'contributor') for org in identity.get('orgs', [])) if not allowed: return dict(status='skipped', reason='organization write access not confirmed; request Graph-Recurrent-VLA access') except Exception as exc: return dict(status='skipped', reason=f'authentication/access check failed ({type(exc).__name__})') for key, repo in repositories.items(): try: url = api.create_repo(repo_id=repo.repo_id, repo_type=repo.repo_type, private=True, exist_ok=True) results[key] = dict(status='ready', url=str(url)) except Exception as exc: results[key] = dict(status='failed', **failure_details(exc)) return dict(status='ready' if all(r['status'] == 'ready' for r in results.values()) else 'failed', repositories=results)
def remote_matches(item, remote): lfs = getattr(remote, 'lfs', None) lfs_sha = lfs.get('sha256') if isinstance(lfs, dict) else getattr(lfs, 'sha256', None) return remote.size == item.size and (lfs_sha == item.sha256 if lfs else remote.blob_id == item.git_sha1)
def failure_details(exc): """Safe diagnostics: never serialize SDK exception messages or responses.""" status = getattr(getattr(exc, 'response', None), 'status_code', None) reason = {401: 'Hugging Face authentication rejected; configure HF_TOKEN or hf auth login', 403: 'Hugging Face write access denied; check token scope and organization role', 404: 'repository missing or inaccessible; check access and run --init-repos explicitly', 409: 'repository changed concurrently; rerun the same command'}.get(status, 'publish failed; verify selected files, repository access and connectivity, then rerun') return dict(error_type=type(exc).__name__, http_status=status, reason=reason)
def publish(directory, include, *, repositories=None, dry_run=False, private=False, retries=2): """Post-run, per-repository atomic commits. Return errors without transport exceptions.""" if not 0 <= retries <= 5: raise ValueError('retries must be between 0 and 5') directory = Path(directory).resolve() plans = plan_upload(directory, include, repositories) report = dict(status='dry-run' if dry_run else 'pending', total_bytes=sum( f.size for plan in plans.values() for f in plan['files']), repositories={}) for key, plan in plans.items(): report['repositories'][key] = dict(repo_id=plan['repository'].repo_id, repo_type=plan['repository'].repo_type, files=[dict(path=f.path, size=f.size) for f in plan['files']]) if dry_run: return report api, operation, reason = connect() if reason: report.update(status='skipped', reason=reason) return report receipt_path = directory / 'huggingface_uploads.json' receipts = json.loads(receipt_path.read_text()) if receipt_path.exists() else {'schema_version': 1, 'publications': {}} for key, plan in plans.items(): repo = plan['repository'] result = report['repositories'][key] for attempt in range(retries + 1): try: info = api.repo_info(repo.repo_id, repo_type=repo.repo_type) if private and not info.private: raise ValueError('repository is public; --private requires a private repository') try: tree = api.list_repo_tree(repo.repo_id, path_in_repo=plan['prefix'], recursive=True, revision=info.sha, repo_type=repo.repo_type) existing = {f.path: f for f in tree if hasattr(f, 'blob_id')} except Exception as exc: if getattr(getattr(exc, 'response', None), 'status_code', None) != 404: raise existing = {} additions = [] for item in plan['files']: if digests(item.source)[1] != item.sha256: raise ValueError('artifact changed during publishing; stop writers and rerun') if item.path in existing: if not remote_matches(item, existing[item.path]): raise ValueError('remote immutable artifact differs; refusing overwrite') else: additions.append(operation(path_in_repo=item.path, path_or_fileobj=item.source)) revision = info.sha if additions: commit = api.create_commit(repo.repo_id, repo_type=repo.repo_type, operations=additions, parent_commit=info.sha, commit_message=f'Publish experiment {directory.name} ({key})') revision = commit.oid base = 'https://huggingface.co/' + ('datasets/' if repo.repo_type == 'dataset' else '') + repo.repo_id result.update(status='uploaded' if additions else 'unchanged', revision=revision, url=f'{base}/tree/{revision}/{plan["prefix"]}', manifest_path=plan['manifest_path'], uploaded_files=len(additions), skipped_files=len(plan['files']) - len(additions)) receipt_key = f'{repo.repo_type}:{repo.repo_id}:{plan["manifest_path"]}' receipts['publications'][receipt_key] = {k: v for k, v in result.items() if k != 'files'} write(receipt_path, receipts) break except Exception as exc: # Exception strings may include credentials or request headers. result.update(status='failed', **failure_details(exc), attempts=attempt + 1) status = result['http_status'] if isinstance(exc, ValueError) or (status and 400 <= status < 500 and status not in (409, 429)): break if attempt < retries: time.sleep(min(2 ** attempt, 8)) if result['status'] != 'failed': for field in ('error_type', 'attempts', 'http_status', 'reason'): result.pop(field, None) report['status'] = 'failed' if any(r['status'] == 'failed' for r in report['repositories'].values()) else 'complete' return report
def sync_wandb_links(directory): """Separate opt-in metadata update, no run resume/init or history replay.""" directory = Path(directory) receipts = json.loads((directory / 'huggingface_uploads.json').read_text()) metadata = json.loads((directory / 'metadata.json').read_text()) from .experiment_logger import has_wandb_api_key, load_wandb_env load_wandb_env() if not has_wandb_api_key() or not metadata.get('entity'): return dict(status='skipped', reason='W&B API key and recorded entity are required; HF receipts retained') try: wandb = importlib.import_module('wandb') run = wandb.Api(timeout=10).run(f'{metadata["entity"]}/{metadata["project"]}/{metadata["run_id"]}') run.summary['huggingface'] = receipts['publications'] run.summary.update() return dict(status='complete') except Exception as exc: return dict(status='failed', error_type=type(exc).__name__)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""CUDA PCA5 resident/transfer timing and same-estimator fidelity.
Uses real CUDA execution, paired CPU reference truth, full point support andfloat64 covariance. Does not claim tracking or final Graph handoff timing."""from __future__ import annotationsimport argparsefrom pathlib import Pathimport platformimport sysfrom time import perf_counterimport numpy as npimport torch
REPO=Path(__file__).resolve().parents[3];sys.path.insert(0,str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.geometry import GeometryFrame,GeometricFeatures,build_organized_geometryfrom visual.runtime.rgbd import iter_saved_rgbdfrom visual.runtime.test.pca_torch import TorchPCA5from visual.runtime.test.run_pca_optimization import reference,fidelity,combine_fidelity,synthetic_observationsfrom visual.runtime.test.normal_diagnostics import statsfrom visual.runtime.test.run_normal_diagnostics import save_json
def benchmark(input_path,masks_path,output_root,*,repeats=3,backend='eigh',synthetic=False): frames=list(iter_saved_rgbd(input_path,masks_path)) cfg=dict(task='pca5_cuda',repeats=repeats,backend=backend,synthetic=synthetic,pca_dtype='float64',initial_grounding_excluded=True,tracking_included=False, input_sha256=digests(Path(input_path))[1],masks_sha256=digests(Path(masks_path))[1],torch=torch.__version__,platform=platform.platform(), source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in [Path(__file__),Path(__file__).with_name('pca_torch.py'),Path(__file__).with_name('pca_triton.py')]}) with ExperimentLogger(team='visual',config=cfg,seed=0,model='pca5_cuda',job_type='evaluate') as logger: out=Path(output_root)/logger.run_id;out.mkdir(parents=True,exist_ok=False);print('Output:',out,flush=True) if not torch.cuda.is_available(): save_json(out/'cuda.json',dict(run_id=logger.run_id,config=cfg,status='not_executed',reason='CUDA unavailable')) logger.link_output(out/'cuda.json',kind='metrics');logger.record(gpu_executed=False);return out torch.set_num_threads(4) cfg['gpu']=torch.cuda.get_device_name();logger.record(evaluation_device='cuda',gpu_executed=True,gpu=cfg['gpu']) processor=TorchPCA5(frames[0].intrinsic,frames[0].depth.shape,device='cuda',backend=backend) resident=[(torch.as_tensor(f.depth,device='cuda'),{i:torch.as_tensor(m,device='cuda') for i,m in f.masks.items()}) for f in frames] for _ in range(3): processor(*resident[0]) torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats() rows=[];quality=[] for idx,frame in enumerate(frames): expected=reference(frame) for repeat in range(repeats): for mode in (('resident','cpu_input') if (idx+repeat)%2==0 else ('cpu_input','resident')): torch.cuda.synchronize();start=perf_counter() if mode=='cpu_input': data=(torch.as_tensor(frame.depth,device='cuda'),{i:torch.as_tensor(m,device='cuda') for i,m in frame.masks.items()}) else:data=resident[idx] begin=torch.cuda.Event(enable_timing=True);end=torch.cuda.Event(enable_timing=True) begin.record();result=processor(*data);end.record();torch.cuda.synchronize();wall=(perf_counter()-start)*1000 rows.append(dict(source_frame=frame.source_frame,repeat=repeat,mode=mode,wall_ms=wall,device_ms=begin.elapsed_time(end))) if repeat==0 and mode=='resident': objects={i:GeometricFeatures(**{k:v.cpu().numpy() for k,v in f.items()}) for i,f in result['objects'].items()} actual=GeometryFrame(frame.source_frame,frame.camera,frame.frame_idx,frame.timestamp,build_organized_geometry(frame),objects,{}) np.testing.assert_array_equal(result['xyz'].cpu().numpy(),expected.geometry.xyz) q=fidelity(expected,actual);quality.append(q) if idx==0 or (idx+1)%20==0:print('CUDA frames',idx+1,'/',len(frames),flush=True) synthetic_rows=[] if synthetic: for idx,(condition,frame,truth,regions) in enumerate(synthetic_observations(frames[0].intrinsic)): expected=reference(frame) result=processor(torch.as_tensor(frame.depth,device='cuda'),{i:torch.as_tensor(m,device='cuda') for i,m in frame.masks.items()}) objects={i:GeometricFeatures(**{k:v.cpu().numpy() for k,v in f.items()}) for i,f in result['objects'].items()} actual=GeometryFrame(frame.source_frame,frame.camera,frame.frame_idx,frame.timestamp,build_organized_geometry(frame),objects,{}) np.testing.assert_array_equal(result['xyz'].cpu().numpy(),expected.geometry.xyz) synthetic_rows.append(dict(condition=condition,fidelity=fidelity(expected,actual))) if (idx+1)%48==0:print('CUDA synthetic conditions',idx+1,'/288',flush=True) fs=combine_fidelity(quality) sf=combine_fidelity([r['fidelity'] for r in synthetic_rows]) summary={mode:{k:stats([r[k] for r in rows if r['mode']==mode]) for k in ('wall_ms','device_ms')} for mode in ('resident','cpu_input')} passed=all(v['validity_differences']==0 and v['other_field_differences']==0 and v['normal_max_deg']<=.001 and v['variation_max_deg']<=.001 for v in (fs,sf)) save_json(out/'cuda.json',dict(run_id=logger.run_id,config=cfg,status='executed',quality_passed=passed,fidelity=fs,summary=summary,frames=rows, synthetic=dict(fidelity=sf,cases=synthetic_rows),peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved())) logger.link_output(out/'cuda.json',kind='metrics');logger.log(summary,prefix='eval/cuda');logger.log(fs,prefix='eval/cuda/fidelity') if not passed:raise AssertionError('CUDA fidelity tolerance failed') return out
def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') p.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') p.add_argument('--out',type=Path,default=REPO/'visual/results/pca_optimization') p.add_argument('--repeats',type=int,default=3) p.add_argument('--backend',choices=['eigh','triton','triton_fused'],default='eigh') p.add_argument('--synthetic',action='store_true') a=p.parse_args();print(benchmark(a.input,a.masks,a.out,repeats=a.repeats,backend=a.backend,synthetic=a.synthetic))
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579# Task03-G — Geometry-Aware Structural Sampling, Phase 1 Feasibility
## 결과 범위와 재현 정보
새 ExperimentLogger UUID: 2c3d733de35c4532b2b81a0a751b7ebf. ep000 Frame 0 / base_camera / S3(PCA5), N=256, structural_ratio=.25, threshold=20°, seed=0. Peg P/F=32/129, Box P/F=32/127. CPU NumPy/SciPy offline 실행만 수행했다. 일반화 알고리즘 채택 근거가 아닌 관측 patch 단위의 첫 feasibility 실험이다.
주 비교는 Task03-E 7f657cf88baf4f1f89e594252e243e1c 저장 Global λ=0이다. Task03 2551448b0fae4c6bbce3caf48774275f Global λ=1과 Task03-F 1f7ad262dd2e4b2fb0ac805a4eda5278 UV는 참고 비교다. F 최종 UUID는 기존 수치 실행의 문서 후처리이며 독립 반복 실험으로 세지 않는다.
선택 규칙은 same-object X의 right/down pair를 기존 4-neighbour 무방향 연결로 복원하고, 양 끝 support·overlap 없음·depth_jump=False·finite angle≤20°로 고정했다. C의 각 source는 정확히 하나의 X patch에 귀속한다. C-free patch도 X와 Surface에서 보존한다. Weight는 C bbox의 3D 대각선이다. 전체 C의 seeded anchor 1점을 보존한 뒤 남은 31점을 capacity-capped largest remainder로 배분하고, patch 내부 원본 3D FPS와 전체 X의 Surface FPS를 사용한다.
## Evidence compatibility 관문
Task01 dense XYZ·validity·mask·overlap·camera·intrinsic·cam2world와 E의 C/X, Task02-C pair source/index/support를 대조했다. Right pair는 같은 행의 +1, down은 +width이며 각 pair는 한 번만 저장된다. Depth jump는 두 depth가 유효할 때 |z₂−z₁| > .01 + .02×min(z₁,z₂)이다. Equality는 jump가 아니다. Normal orientation 후보는 >20°, patch 연결은 finite ≤20°다. NaN angle은 연결하지 않는다. Normal-invalid X는 삭제하지 않는다.
| object | pairs | right | down | candidate/support/threshold | optimized pair identity || --- | --- | --- | --- | --- | --- || peg | 23876 | 11964 | 11912 | PASS | N/A || box | 23645 | 11835 | 11810 | PASS | N/A |
Reference PCA5 pair angle은 저장 Task02-B normal에서 직접 재계산해 exact equality를 확인했다. 저장 orientation endpoint 및 normal variation의 >20° membership은 Task03 optimized PCA5의 저장 C와 일치했고, 저장 선택 행의 validity/candidate membership도 일치했다. 하지만 optimized PCA5 전체 pair angle은 저장되지 않았다. Candidate endpoint 집합의 일치가 low-angle pair별 연결 gate의 일치를 보장하지 않는다. 따라서 이번 patch는 Task02-C reference PCA5 evidence에서 구성했고 optimized PCA5와 bit-exact라고 주장하지 않는다. Normal estimator/candidate detector는 재실행하지 않았다.
## 선택 전 patch 분절과 allocation
아래 patch ID는 GT-free 관측상 매끄럽게 연결된 표면 성분이다. Structural edge, physical component, 평가용 seam/rim label 또는 최종 graph edge를 뜻하지 않는다. Weight=0인 후보 patch에는 anchor 외 minimum quota가 없다. 실패를 보정하기 위한 병합·gate 변경·후보 삭제는 하지 않았다.
| object | X patches | C patches | X singleton | 0-span C patches | 0-span candidates / C | quota=0 C patches | quota=0 candidates | anchor patch/quota | fallback || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || peg | 20 | 12 | 19 | 11 | 11 / 703 (1.565%) | 11 | 11 | 0 / 32 | 0 || box | 105 | 30 | 87 | 15 | 15 / 599 (2.504%) | 21 | 43 | 52 / 1 | 0 |
peg: singleton 또는 candidate 0-span patch 19개, 그 안의 후보 11개 (1.565%). Candidate가 1개인 patch 11개, X singleton에 속한 후보 11개. 실제 fallback=0점.
box: singleton 또는 candidate 0-span patch 88개, 그 안의 후보 15개 (2.504%). Candidate가 1개인 patch 15개, X singleton에 속한 후보 14개. 실제 fallback=0점.
peg 전체 X patch (C=0 포함): span은 bbox proxy이며 구조 길이가 아니다. Capacity는 전체 C 수, additional은 anchor 제외 배분이다.
| patch | min source | X | C/capacity | X span m | C span/weight m | anchor | additional | quota | actual P | fallback P || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || 0 | 146191 | 11761 | 692 | 0.259619 | 0.243348 | 1 | 31 | 32 | 32 | 0 || 1 | 168678 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 2 | 186567 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 3 | 186623 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 4 | 187134 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 5 | 191167 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 6 | 192760 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 7 | 195317 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 8 | 201454 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 9 | 204968 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 10 | 212137 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 11 | 213216 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 12 | 213728 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 13 | 215262 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 14 | 215722 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 15 | 215773 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 16 | 216234 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 17 | 216284 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 18 | 219307 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 19 | 219819 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
box 전체 X patch (C=0 포함): span은 bbox proxy이며 구조 길이가 아니다. Capacity는 전체 C 수, additional은 anchor 제외 배분이다.
| patch | min source | X | C/capacity | X span m | C span/weight m | anchor | additional | quota | actual P | fallback P || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || 0 | 83165 | 11112 | 399 | 0.389164 | 0.326477 | 0 | 15 | 15 | 15 | 0 || 1 | 84271 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 2 | 84285 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 3 | 84698 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 4 | 84783 | 7 | 5 | 0.0135329 | 0.0135329 | 0 | 1 | 1 | 1 | 0 || 5 | 84796 | 10 | 0 | 0.00471966 | 0 | 0 | 0 | 0 | 0 | 0 || 6 | 85210 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 7 | 85722 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 8 | 86234 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 9 | 86746 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 10 | 87254 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 11 | 87356 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 12 | 87765 | 7 | 3 | 0.0170659 | 0.00605605 | 0 | 0 | 0 | 0 | 0 || 13 | 87858 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 14 | 88273 | 14 | 0 | 0.0071225 | 0 | 0 | 0 | 0 | 0 | 0 || 15 | 88369 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 16 | 88379 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 17 | 88881 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 18 | 89304 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 19 | 89392 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 20 | 89393 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 21 | 89817 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 22 | 89904 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 23 | 89913 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 24 | 90329 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 25 | 90841 | 3 | 2 | 0.00848839 | 0.00574664 | 0 | 0 | 0 | 0 | 0 || 26 | 90936 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 27 | 91438 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 28 | 91866 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 29 | 91867 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 30 | 91949 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 31 | 92372 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 32 | 92380 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 33 | 92485 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 34 | 92884 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 35 | 92885 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 36 | 92892 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 37 | 93397 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 38 | 93405 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 39 | 93493 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 40 | 93910 | 158 | 54 | 0.0271379 | 0.0255804 | 0 | 1 | 1 | 1 | 0 || 41 | 93917 | 2 | 1 | 0.0103938 | 0 | 0 | 0 | 0 | 0 | 0 || 42 | 93989 | 50 | 27 | 0.0268233 | 0.0268233 | 0 | 1 | 1 | 1 | 0 || 43 | 93990 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 44 | 93991 | 15 | 11 | 0.0136232 | 0.0136232 | 0 | 1 | 1 | 1 | 0 || 45 | 94947 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 46 | 94948 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 47 | 94949 | 40 | 29 | 0.0249794 | 0.0249794 | 0 | 1 | 1 | 1 | 0 || 48 | 95016 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 49 | 95022 | 49 | 14 | 0.0142764 | 0.0136464 | 0 | 1 | 1 | 1 | 0 || 50 | 95459 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 51 | 96051 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 52 | 96553 | 4 | 4 | 0.0034845 | 0.0034845 | 1 | 0 | 1 | 1 | 0 || 53 | 96563 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 54 | 97075 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 55 | 97506 | 3 | 3 | 0.00235313 | 0.00235313 | 0 | 0 | 0 | 0 | 0 || 56 | 97587 | 6 | 5 | 0.00487074 | 0.00481773 | 0 | 0 | 0 | 0 | 0 || 57 | 98601 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 58 | 100146 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 59 | 100650 | 19 | 13 | 0.0111558 | 0.0111558 | 0 | 0 | 0 | 0 | 0 || 60 | 100658 | 2 | 2 | 0.00217214 | 0.00217214 | 0 | 0 | 0 | 0 | 0 || 61 | 101160 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 62 | 101671 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 63 | 101672 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 64 | 101682 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 65 | 102115 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 66 | 102116 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 67 | 104726 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 68 | 105723 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 69 | 105724 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 70 | 105725 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 71 | 105726 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 72 | 105727 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 73 | 105728 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 74 | 105729 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 75 | 105730 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 76 | 105731 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 77 | 105732 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 78 | 105733 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 79 | 105734 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 80 | 106235 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 81 | 106236 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 82 | 106237 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 83 | 106238 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 84 | 106239 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 85 | 106240 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 86 | 106241 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 87 | 106242 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 88 | 106243 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 89 | 106244 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 90 | 106245 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 91 | 106246 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 92 | 106747 | 77 | 13 | 0.214497 | 0.214497 | 0 | 10 | 10 | 10 | 0 || 93 | 110914 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 94 | 111316 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 95 | 111828 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 96 | 112340 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 97 | 117057 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 98 | 119061 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 99 | 120533 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 100 | 121045 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 101 | 129855 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 102 | 130262 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 103 | 135998 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 104 | 136510 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |


## Primary — 원본 3D candidate·surface 보존
모든 거리는 변환하지 않은 CV-camera XYZ의 Euclidean 최근접 거리(mm)다. P의 patch 내부 선택 metric과 독립적으로 평가했다. Grouping·span allocation·patch별 초기화·patch 내부 3D와 Global λ=0 metric 차이가 묶여 있다. 아래 차이는 선택 규칙 전체의 차이이며 개별 요소의 인과 효과가 아니다.
| object | method | C→P mean | p50 | p95 | max | X→F mean | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || peg | global0 | 2.94515 | 2.46875 | 6.66215 | 8.19795 | 5.28368 | 8.60946 | 10.8408 || peg | geometry | 2.83494 | 2.66592 | 5.66392 | 6.63788 | 5.1986 | 8.56355 | 11.1341 || peg | global1 | 2.84805 | 2.66592 | 5.66544 | 6.61867 | 5.17004 | 8.54994 | 11.0471 || peg | uv | 3.62105 | 2.89099 | 8.90441 | 15.1258 | 5.27668 | 8.62629 | 11.5683 || box | global0 | 10.8746 | 8.84305 | 29.7788 | 46.0516 | 11.5801 | 19.0768 | 23.1584 || box | geometry | 14.7286 | 13.6098 | 30.7101 | 42.1494 | 11.4499 | 19.0144 | 23.9357 || box | global1 | 12.7793 | 12.5895 | 27.4828 | 32.7114 | 11.2533 | 18.7511 | 22.8926 || box | uv | 10.768 | 7.19952 | 35.0932 | 96.3886 | 11.6761 | 19.5611 | 23.9004 |
| object | Δ mean | Δ p50 | Δ p95 | Δ max | Δ Surface mean | Δ Surface p95 || --- | --- | --- | --- | --- | --- | --- || peg | -0.110212 | 0.197166 | -0.998228 | -1.56007 | -0.0850846 | -0.0459049 || box | 3.85401 | 4.76673 | 0.931283 | -3.90217 | -0.130226 | -0.0623638 |
| object | method | worst source | UV | XYZ m || --- | --- | --- | --- | --- || peg | global0 | 178953 | [265, 349] | [0.008720703423023224, 0.08583007752895355, 0.23499999940395355] || peg | geometry | 191736 | [248, 374] | [-0.006035156082361937, 0.09535546600818634, 0.20600000023841858] || box | global0 | 114427 | [251, 223] | [-0.010265625081956387, -0.07414062321186066, 0.5839999914169312] || box | geometry | 112891 | [251, 220] | [-0.010880859568715096, -0.08583789318799973, 0.6190000176429749] |


## 독립 평가 구역과 후보 밀도
Task03-F의 X bbox 기반 UV 4×4 및 XYZ 최대 2×2×2 경계와 helper를 그대로 사용했다. Candidate count, 선택률과 거리 분포를 함께 본다. Box X의 30.726m depth outlier 때문에 XYZ grid의 후보가 한 구역에 들어가는 한계를 보정하지 않았다. 전체 분위수는 후보 밀도의 영향을 받으며 구역 동등 가중 p95도 함께 기록한다. XYZ 공간 밀도의 공통 helper 값은 N/A이며 UV 밀도는 px²당 후보 수다.
| object | method | grid | C occupied | P=0 regions | equal-region mean p95 mm || --- | --- | --- | --- | --- | --- || peg | global0 | uv | 8 | [] | 5.61617 || peg | global0 | xyz | 4 | [6] | 5.81242 || peg | geometry | uv | 8 | [] | 4.95252 || peg | geometry | xyz | 4 | [6] | 5.23625 || box | global0 | uv | 9 | [] | 22.5887 || box | global0 | xyz | 1 | [] | 29.7788 || box | geometry | uv | 9 | [] | 28.2865 || box | geometry | xyz | 1 | [] | 30.7101 |
peg / uv independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 1 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 2 | 98 | 5 | 0.0654069 | 0.0510204 | 1.90722 | 3.87439 | 3.9925 || global0 | 3 | 11 | 2 | 0.00734159 | 0.181818 | 1.8892 | 3.94895 | 4.1479 || global0 | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 5 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 6 | 125 | 4 | 0.0834272 | 0.032 | 2.75116 | 6.01855 | 7.0785 || global0 | 7 | 149 | 7 | 0.0994452 | 0.0469799 | 1.93745 | 3.28836 | 4.08921 || global0 | 8 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 9 | 94 | 4 | 0.0627372 | 0.0425532 | 3.88951 | 7.11593 | 8.19795 || global0 | 10 | 70 | 1 | 0.0467192 | 0.0142857 | 4.06496 | 7.02078 | 7.44417 || global0 | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 12 | 115 | 8 | 0.076753 | 0.0695652 | 3.69792 | 6.86018 | 8.10343 || global0 | 13 | 41 | 1 | 0.0273641 | 0.0243902 | 3.7745 | 6.80221 | 7.74202 || global0 | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 1 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 2 | 98 | 4 | 0.0654069 | 0.0408163 | 2.29913 | 4.20056 | 4.7016 || geometry | 3 | 11 | 2 | 0.00734159 | 0.181818 | 1.8892 | 3.94895 | 4.1479 || geometry | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 5 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 6 | 125 | 4 | 0.0834272 | 0.032 | 2.49335 | 4.4182 | 5.21059 || geometry | 7 | 149 | 4 | 0.0994452 | 0.0268456 | 3.057 | 5.48384 | 6.09783 || geometry | 8 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 9 | 94 | 3 | 0.0627372 | 0.0319149 | 3.41058 | 6.24105 | 6.63788 || geometry | 10 | 70 | 3 | 0.0467192 | 0.0428571 | 2.13202 | 3.44828 | 3.8646 || geometry | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 12 | 115 | 9 | 0.076753 | 0.0782609 | 3.39673 | 6.18012 | 6.51205 || geometry | 13 | 41 | 3 | 0.0273641 | 0.0731707 | 2.90839 | 5.69918 | 6.51487 || geometry | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A |
peg / xyz independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 2 | 447 | 19 | N/A | 0.0425056 | 2.48632 | 5.90636 | 7.44417 || global0 | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 4 | 141 | 5 | N/A | 0.035461 | 3.82657 | 7.02556 | 8.19795 || global0 | 5 | 109 | 8 | N/A | 0.0733945 | 3.72553 | 6.86357 | 8.10343 || global0 | 6 | 6 | 0 | N/A | 0 | 2.23751 | 3.45418 | 3.53184 || global0 | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 2 | 447 | 17 | N/A | 0.0380313 | 2.56323 | 4.87173 | 6.09783 || geometry | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 4 | 141 | 6 | N/A | 0.0425532 | 3.34643 | 6.18969 | 6.63788 || geometry | 5 | 109 | 9 | N/A | 0.0825688 | 3.29005 | 6.11959 | 6.51205 || geometry | 6 | 6 | 0 | N/A | 0 | 2.78927 | 3.76398 | 3.8646 || geometry | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A |
box / uv independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 66 | 3 | 0.0812808 | 0.0454545 | 10.3462 | 14.7998 | 22.2359 || global0 | 1 | 78 | 3 | 0.0960591 | 0.0384615 | 7.90347 | 13.5986 | 14.6165 || global0 | 2 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 3 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 5 | 50 | 10 | 0.0615764 | 0.2 | 14.7896 | 33.8833 | 38.9934 || global0 | 6 | 100 | 3 | 0.123153 | 0.03 | 13.2174 | 42.8725 | 46.0516 || global0 | 7 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 8 | 22 | 1 | 0.0270936 | 0.0454545 | 9.07644 | 16.6948 | 17.3864 || global0 | 9 | 94 | 2 | 0.115764 | 0.0212766 | 14.4096 | 33.1814 | 44.4893 || global0 | 10 | 98 | 4 | 0.12069 | 0.0408163 | 11.1689 | 25.7114 | 30.9242 || global0 | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 12 | 40 | 3 | 0.0492611 | 0.075 | 4.99843 | 11.5026 | 13.5933 || global0 | 13 | 51 | 3 | 0.0628079 | 0.0588235 | 5.97387 | 11.0541 | 13.0251 || global0 | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 0 | 66 | 3 | 0.0812808 | 0.0454545 | 11.7534 | 31.8331 | 34.0837 || geometry | 1 | 78 | 1 | 0.0960591 | 0.0128205 | 11.488 | 21.2376 | 26.1019 || geometry | 2 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 3 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 5 | 50 | 14 | 0.0615764 | 0.28 | 14.5807 | 34.0494 | 36.8557 || geometry | 6 | 100 | 2 | 0.123153 | 0.02 | 24.6182 | 30.7025 | 42.1494 || geometry | 7 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 8 | 22 | 1 | 0.0270936 | 0.0454545 | 17.8174 | 34.6258 | 36.0874 || geometry | 9 | 94 | 2 | 0.115764 | 0.0212766 | 15.0542 | 26.7266 | 38.2396 || geometry | 10 | 98 | 3 | 0.12069 | 0.0306122 | 14.6248 | 28.1132 | 30.9242 || geometry | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 12 | 40 | 5 | 0.0492611 | 0.125 | 5.41378 | 30.5286 | 31.4366 || geometry | 13 | 51 | 1 | 0.0628079 | 0.0196078 | 9.86141 | 16.7622 | 19.7643 || geometry | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A |
box / xyz independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 2 | 599 | 32 | N/A | 0.0534224 | 10.8746 | 29.7788 | 46.0516 || global0 | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 4 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 5 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 6 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 2 | 599 | 32 | N/A | 0.0534224 | 14.7286 | 30.7101 | 42.1494 || geometry | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 4 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 5 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 6 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A |

## Secondary — GT 기반 보조 진단
선택 및 selection_before_gt.npz 저장·hash 후 GT reference/pose/ROI를 평가에만 적용했다. 동일 point/reference pair가 2px AND 3mm를 만족해야 한다. Peg GT-visible 464개 중 관측 가능 462개, Box 103개 중 103개가 분모다. Matching node 수와 unique reference 수는 서로 다른 수량이다. 특정 Box rim 선분 개선은 성공 조건이 아니다.
| object | method | stage | nodes | matching nodes | unique refs || --- | --- | --- | --- | --- | --- || peg | global0 | C | 703 | 692 | 462 || peg | global0 | P | 32 | 30 | 160 || peg | global0 | S | 97 | 0 | 0 || peg | global0 | F | 129 | 30 | 160 || peg | geometry | C | 703 | 692 | 462 || peg | geometry | P | 32 | 30 | 149 || peg | geometry | S | 97 | 0 | 0 || peg | geometry | F | 129 | 30 | 149 || peg | global1 | C | 703 | 692 | 462 || peg | global1 | P | 32 | 30 | 151 || peg | global1 | S | 97 | 0 | 0 || peg | global1 | F | 129 | 30 | 151 || peg | uv | C | 703 | 692 | 462 || peg | uv | P | 32 | 31 | 140 || peg | uv | S | 97 | 0 | 0 || peg | uv | F | 129 | 31 | 140 || box | global0 | C | 599 | 127 | 91 || box | global0 | P | 32 | 3 | 9 || box | global0 | S | 95 | 1 | 3 || box | global0 | F | 127 | 4 | 12 || box | geometry | C | 599 | 127 | 91 || box | geometry | P | 32 | 1 | 3 || box | geometry | S | 95 | 2 | 6 || box | geometry | F | 127 | 3 | 9 || box | global1 | C | 599 | 127 | 91 || box | global1 | P | 32 | 1 | 3 || box | global1 | S | 95 | 0 | 0 || box | global1 | F | 127 | 1 | 3 || box | uv | C | 599 | 127 | 91 || box | uv | P | 32 | 1 | 3 || box | uv | S | 95 | 0 | 0 || box | uv | F | 127 | 1 | 3 |
| object | method | P refs | S refs | F refs | S added refs | P/S overlap refs || --- | --- | --- | --- | --- | --- | --- || peg | global0 | 160 | 0 | 160 | 0 | 0 || peg | geometry | 149 | 0 | 149 | 0 | 0 || box | global0 | 9 | 3 | 12 | 3 | 0 || box | geometry | 3 | 6 | 9 | 6 | 0 |
| object | method | stage | GT face-pair/rim segment | observed refs | covered refs | matching nodes || --- | --- | --- | --- | --- | --- | --- || peg | global0 | C | ambiguous | 2 | 2 | 17 || peg | global0 | C | face_0_2 | 91 | 91 | 140 || peg | global0 | C | face_0_5 | 106 | 106 | 154 || peg | global0 | C | face_2_5 | 263 | 263 | 381 || peg | global0 | P | ambiguous | 2 | 1 | 1 || peg | global0 | P | face_0_2 | 91 | 44 | 7 || peg | global0 | P | face_0_5 | 106 | 49 | 7 || peg | global0 | P | face_2_5 | 263 | 66 | 15 || peg | global0 | S | ambiguous | 2 | 0 | 0 || peg | global0 | S | face_0_2 | 91 | 0 | 0 || peg | global0 | S | face_0_5 | 106 | 0 | 0 || peg | global0 | S | face_2_5 | 263 | 0 | 0 || peg | global0 | F | ambiguous | 2 | 1 | 1 || peg | global0 | F | face_0_2 | 91 | 44 | 7 || peg | global0 | F | face_0_5 | 106 | 49 | 7 || peg | global0 | F | face_2_5 | 263 | 66 | 15 || peg | geometry | C | ambiguous | 2 | 2 | 17 || peg | geometry | C | face_0_2 | 91 | 91 | 140 || peg | geometry | C | face_0_5 | 106 | 106 | 154 || peg | geometry | C | face_2_5 | 263 | 263 | 381 || peg | geometry | P | ambiguous | 2 | 2 | 1 || peg | geometry | P | face_0_2 | 91 | 29 | 4 || peg | geometry | P | face_0_5 | 106 | 30 | 5 || peg | geometry | P | face_2_5 | 263 | 88 | 20 || peg | geometry | S | ambiguous | 2 | 0 | 0 || peg | geometry | S | face_0_2 | 91 | 0 | 0 || peg | geometry | S | face_0_5 | 106 | 0 | 0 || peg | geometry | S | face_2_5 | 263 | 0 | 0 || peg | geometry | F | ambiguous | 2 | 2 | 1 || peg | geometry | F | face_0_2 | 91 | 29 | 4 || peg | geometry | F | face_0_5 | 106 | 30 | 5 || peg | geometry | F | face_2_5 | 263 | 88 | 20 || box | global0 | C | rim_axis1_+1 | 25 | 24 | 21 || box | global0 | C | rim_axis1_-1 | 26 | 26 | 43 || box | global0 | C | rim_axis2_+1 | 26 | 15 | 12 || box | global0 | C | rim_axis2_-1 | 26 | 26 | 46 || box | global0 | P | rim_axis1_+1 | 25 | 6 | 2 || box | global0 | P | rim_axis1_-1 | 26 | 0 | 0 || box | global0 | P | rim_axis2_+1 | 26 | 0 | 0 || box | global0 | P | rim_axis2_-1 | 26 | 3 | 1 || box | global0 | S | rim_axis1_+1 | 25 | 0 | 0 || box | global0 | S | rim_axis1_-1 | 26 | 0 | 0 || box | global0 | S | rim_axis2_+1 | 26 | 3 | 1 || box | global0 | S | rim_axis2_-1 | 26 | 0 | 0 || box | global0 | F | rim_axis1_+1 | 25 | 6 | 2 || box | global0 | F | rim_axis1_-1 | 26 | 0 | 0 || box | global0 | F | rim_axis2_+1 | 26 | 3 | 1 || box | global0 | F | rim_axis2_-1 | 26 | 3 | 1 || box | geometry | C | rim_axis1_+1 | 25 | 24 | 21 || box | geometry | C | rim_axis1_-1 | 26 | 26 | 43 || box | geometry | C | rim_axis2_+1 | 26 | 15 | 12 || box | geometry | C | rim_axis2_-1 | 26 | 26 | 46 || box | geometry | P | rim_axis1_+1 | 25 | 3 | 1 || box | geometry | P | rim_axis1_-1 | 26 | 0 | 0 || box | geometry | P | rim_axis2_+1 | 26 | 0 | 0 || box | geometry | P | rim_axis2_-1 | 26 | 0 | 0 || box | geometry | S | rim_axis1_+1 | 25 | 3 | 1 || box | geometry | S | rim_axis1_-1 | 26 | 0 | 0 || box | geometry | S | rim_axis2_+1 | 26 | 0 | 0 || box | geometry | S | rim_axis2_-1 | 26 | 3 | 1 || box | geometry | F | rim_axis1_+1 | 25 | 6 | 2 || box | geometry | F | rim_axis1_-1 | 26 | 0 | 0 || box | geometry | F | rim_axis2_+1 | 26 | 0 | 0 || box | geometry | F | rim_axis2_-1 | 26 | 3 | 1 |
Box의 verified line projection 간격과 missing-reference run은 JSON/NPZ에 기존 helper 정의로 저장했다. Peg face-pair 및 ambiguous reference의 물리적 선분 순서는 N/A다. Array 순서를 곡선 길이나 실제 연속 미보존 길이로 해석하지 않는다.


## 일반 Surface·negative ROI·depth·outlier trade-off
일반 Surface는 전체 X→F로 평가한다. S만 따로 평가하거나 far point를 제거하지 않았다. Known-negative ROI union은 평가용이며 평면 Surface 점유를 자동 오선택이라고 분류하지 않는다. 원본 outlier·depth tail은 그대로 남긴다.
| object | method | negative P / 32 | negative S | negative F | F exact feature rows | unavailable rows || --- | --- | --- | --- | --- | --- | --- || peg | global0 | 2 | 90 | 92 | 26 | 103 || peg | geometry | 2 | 91 | 93 | 97 | 32 || box | global0 | 14 | 61 | 75 | 45 | 82 || box | geometry | 12 | 68 | 80 | 49 | 78 |
| object | method | stage | depth min m | median | p95 | max || --- | --- | --- | --- | --- | --- | --- || peg | global0 | X | 0.166 | 0.206 | 0.32705 | 0.365 || peg | global0 | C | 0.166 | 0.181 | 0.316 | 0.35 || peg | global0 | P | 0.166 | 0.1865 | 0.3325 | 0.35 || peg | global0 | S | 0.176 | 0.266 | 0.3506 | 0.365 || peg | global0 | F | 0.166 | 0.255 | 0.3492 | 0.365 || peg | geometry | X | 0.166 | 0.206 | 0.32705 | 0.365 || peg | geometry | C | 0.166 | 0.181 | 0.316 | 0.35 || peg | geometry | P | 0.166 | 0.197 | 0.33295 | 0.35 || peg | geometry | S | 0.175 | 0.266 | 0.3506 | 0.365 || peg | geometry | F | 0.166 | 0.252 | 0.3492 | 0.365 || box | global0 | X | 0.295 | 0.496 | 0.535 | 30.726 || box | global0 | C | 0.295 | 0.488 | 0.6665 | 1.426 || box | global0 | P | 0.306 | 0.4955 | 1.3864 | 1.426 || box | global0 | S | 0.453 | 0.536 | 8.431 | 30.726 || box | global0 | F | 0.306 | 0.531 | 8.431 | 30.726 || box | geometry | X | 0.295 | 0.496 | 0.535 | 30.726 || box | geometry | C | 0.295 | 0.488 | 0.6665 | 1.426 || box | geometry | P | 0.303 | 0.5525 | 1.40565 | 1.426 || box | geometry | S | 0.306 | 0.523 | 8.431 | 30.726 || box | geometry | F | 0.303 | 0.524 | 8.431 | 30.726 |
Feature는 같은 S3 조건에서 저장된 23개 field의 exact available 행만 compact gather하고 availability mask/positions를 저장했다. Missing feature는 근사 복원하지 않았다. 완전한 production Vision Tensor 검증을 주장하지 않는다.
| object | patch | extreme source | original C span m | span without one point m | drop m | quota || --- | --- | --- | --- | --- | --- | --- || peg | 0 | 148779 | 0.243348 | 0.240427 | 0.0029204 | 32 || peg | 0 | 216283 | 0.243348 | 0.243348 | 0 | 32 || peg | 0 | 221356 | 0.243348 | 0.243348 | 0 | 32 |
| object | patch | extreme source | original C span m | span without one point m | drop m | quota || --- | --- | --- | --- | --- | --- | --- || box | 92 | 109819 | 0.214497 | 0.18542 | 0.0290762 | 10 || box | 4 | 85809 | 0.0135329 | 0.00731415 | 0.00621877 | 1 || box | 25 | 90842 | 0.00574664 | 0 | 0.00574664 | 0 |
각 patch의 C/X bbox min/max XYZ와 C extrema source별 leave-one-out span을 저장했다. 위 표는 한 극단점에 민감한 상위 사례다. 한 점 제거 span은 진단일 뿐 선택에 적용하지 않았다. Bbox span은 실제 구조 길이가 아니며 camera 축과 outlier에 민감하다.

## Synthetic 경계와 fallback 계약
기존 Task03-F 7개 fixture에는 dense X 및 PairEvidence가 없어 새 full-rule performance는 전부 N/A다. 구조 label로 patch를 만들거나 새 detector/normal/fixture를 생성하지 않았다. 기존 Global/UV 결과를 새 방법의 검증 결과로 표시하지 않는다.
| existing fixture | new full-rule performance | reason || --- | --- | --- || line_uniform | N/A | existing sparse C has no dense X or PairEvidence || line_dense | N/A | existing sparse C has no dense X or PairEvidence || separated_clean | N/A | existing sparse C has no dense X or PairEvidence || separated_noise | N/A | existing sparse C has no dense X or PairEvidence || camera_near | N/A | existing sparse C has no dense X or PairEvidence || camera_far | N/A | existing sparse C has no dense X or PairEvidence || camera_occluded | N/A | existing sparse C has no dense X or PairEvidence |
일반 fallback은 현재 C만으로 기존 fps_indices()의 Global λ=0 순서를 만들고 이미 선택된 point를 제외해 부족분을 채운다. 이번 고정 입력에서는 E의 기존 검증과 저장 순서를 재사용할 수 있으며 NPZ는 fallback 규칙의 필수 입력이 아니다. 두 실제 물체의 fallback은 0점이어서 새 결과가 fallback으로 Global FPS를 복제한 경우는 아니다. 작은 synthetic 계약 테스트는 입력 C만으로 fallback을 재현하고 depth/normal veto·분리·0-span·capacity·anchor·정렬·결정성·GT 독립성을 확인한다. 이 테스트는 실제 형상 또는 sensor noise에 대한 일반화 성능 검증이 아니다.
## 완료 판단 — 여섯 질문
1. 실제 C의 분리: Peg는 X patch 20개 중 C patch 12개, Box는 105개 중 30개다. 이는 관측 normal/depth gate로 연결된 표면이지 실제 구조의 독립 분해가 아니다.
2. 3D span quota: peg: patch 0=32; box: patch 0=15, patch 4=1, patch 40=1, patch 42=1, patch 44=1, patch 47=1, patch 49=1, patch 52=1, patch 92=10. Peg의 대부분 C는 하나의 큰 surface patch에 연결되어 독립 구조별 예산을 만들지 못했다. Box는 여러 patch에 배분되었지만 넓은 bbox를 가진 patch에 예산이 집중된다.
3. Global λ=0 대비 3D 보존: peg C→P mean/p95/max 2.945/6.662/8.198→2.835/5.664/6.638mm; X→F mean/p95 5.284/8.609→5.199/8.564mm; box C→P mean/p95/max 10.875/29.779/46.052→14.729/30.710/42.149mm; X→F mean/p95 11.580/19.077→11.450/19.014mm. 손익은 지표별로 해석하며 GT 보존으로 primary 손실을 상쇄하지 않는다.
4. 국소 구조·negative ROI: peg P/F refs 160/160→149/149; negative P/F 2/92→2/93; box P/F refs 9/12→3/9; negative P/F 14/75→12/80. Face-pair/rim 전체 구간과 Surface 추가분·overlap은 위 표에 제시했다. 구간별 개선·손실을 합쳐 특정 Box 선분을 성공 기준으로 삼지 않았다.
5. 제한 요인: Peg/Box의 0-span 후보 11/15개는 span quota를 받지 못하며 quota=0 후보 patch는 11/21개다. Normal 불연속 주변 후보가 작은 patch로 분절되면 중요한 구조라도 quota에서 사라질 수 있는 설계 취약성이다. 실제 fallback은 양쪽 0점이다. Bbox 극단점 민감도와 depth outlier는 제거하지 않았고 span을 구조 길이로 해석하지 않는다.
6. 추가 검증 판단: Frame0에서 관측 patch가 어떻게 분리·배분되는지는 재현 가능하게 설명했지만, Peg의 단일 큰 patch, Box의 fragmentation/zero-quota, reference와 optimized PCA5 pair 차이의 미확인, 7개 full-rule synthetic N/A가 남는다. 현재 결과만으로 일반 geometry preservation 후보의 유용성·안정성을 확립하거나 production 채택을 정당화하지 않는다. 관측 patch의 유용성에는 제한된 근거만 있으며, 독립 관측·형상·camera에서 같은 고정 규칙의 별도 evidence가 필요하다. 이번에는 추가 검증을 시작하지 않는다.
## 검증과 미실행 범위
Ran 93 tests in 0.704s; OK
Source/input/artifact hash 불변, 모든 C의 단일 patch 귀속, quota/capacity, P=32, F=129/127, P⊆C⊆X·F⊆X, pixel/XYZ/object/role 정렬, P/S 중복 없음, NPZ exact readback, saved baseline 평가 exact equality를 확인했다. GT annotation ��경에 따른 전체 선택 불변은 annotation-free 입력/함수 및 작은 full-rule 계약 테스트로 확인하고 실제 선택 전후 archive hash도 유지했다. 실제 Frame0 선택을 GT 변경 후 다시 실행하지 않았다. Optimized pair-level 동일성은 N/A다.
공통 ExperimentLogger와 experiment_artifacts의 digests/register_existing_output 및 link_output 로컬 API를 재사용했다. 실행 소스 snapshot, 시작 dirty diff, 입력 hash, 구현 diff와 tests.log를 새 UUID에 보존했다. Simulator/renderer·GPU/CUDA/MPS/PCL·추가 frame/episode·normal/candidate 재계산·sweep·production·Graph/GNN/BC·외부 업로드·dependency 설치·commit은 실행하지 않았다. Adaptive Budget 결합, Task-Relevance, 다른 grouping과 다음 단계는 시작하지 않고 여기서 종료한다.
## 산출물과 원본 링크
[geometry_aware_sampling.html](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.html)
[geometry_aware_sampling.json](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.json)
[geometry_aware_sampling.npz](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.npz)
[selection_before_gt.npz](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/selection_before_gt.npz)
[patch_diagnostics_before_selection.json](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_diagnostics_before_selection.json)
[verification.json](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/verification.json)
[tests.log](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/tests.log)
[source_hashes.json](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_hashes.json)
[original_hashes.json](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/original_hashes.json)
[preregistered_config.json](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/preregistered_config.json)
[implementation.patch](../../experiments/2c3d733de35c4532b2b81a0a751b7ebf/implementation.patch)
[Task03-E saved baseline](../../experiments/7f657cf88baf4f1f89e594252e243e1c/priority_fps_metric_control.html)
[Task03-F reference / existing synthetic evidence](../../experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/local_structural_sampling.html)
[approved plan](03g_geometry_aware_sampling_plan.md)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Grounding DINO initialization rules from the Visual v1 prototype.
Only RGB detections are used. A missing object stays missing until two scansagree; no simulator segmentation or pose is consulted."""
from __future__ import annotations
from itertools import product
PROMPTS = {"peg": "red and white block", "box": "cardboard box"}MAX_BOX_FRAC = 0.25MISSING_SCORE = 0.3EXCLUSION_IOU = 0.3SCAN_EVERY = 5
def box_iou(a, b): x = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) y = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) intersection = x * y area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) union = area_a + area_b - intersection return intersection / union if union > 0 else 0.0
def candidates(detector, rgb, prompt, limit=5): height, width = rgb.shape[:2] boxes, scores = detector(rgb, prompt) return [(box, float(score)) for box, score in zip(boxes, scores) if (box[2] - box[0]) * (box[3] - box[1]) < MAX_BOX_FRAC * height * width][:limit]
def assign(peg_candidates, box_candidates): """Pick distinct objects jointly, with an explicit missing choice.""" best = (None, None) best_score = 2 * MISSING_SCORE for peg, box in product([*peg_candidates, None], [*box_candidates, None]): if peg is not None and box is not None and box_iou(peg[0], box[0]) >= EXCLUSION_IOU: continue score = (peg[1] if peg else MISSING_SCORE) + (box[1] if box else MISSING_SCORE) if score > best_score: best, best_score = (peg, box), score return best
def detect_initial(frames, detector, prompts=None): """Return each object's selected box, score and source-frame index.""" prompts = PROMPTS if prompts is None else prompts first = {name: candidates(detector, frames[0], prompts[name]) for name in PROMPTS} peg, box = assign(first["peg"], first["box"]) result = { "peg": {"box": peg[0] if peg else None, "score": peg[1] if peg else None, "frame": 0 if peg else None, "prompt": prompts["peg"], "scans": 1}, "box": {"box": box[0] if box else None, "score": box[1] if box else None, "frame": 0 if box else None, "prompt": prompts["box"], "scans": 1}, } for name in PROMPTS: if result[name]["box"] is not None: continue other = result["box" if name == "peg" else "peg"]["box"] pending = None for frame in range(SCAN_EVERY, len(frames), SCAN_EVERY): result[name]["scans"] += 1 choices = [candidate for candidate in candidates(detector, frames[frame], prompts[name]) if candidate[1] >= MISSING_SCORE and (other is None or box_iou(candidate[0], other) < EXCLUSION_IOU)] if not choices: pending = None continue choice = choices[0] if pending is not None and box_iou(choice[0], pending[0]) >= 0.5: result[name].update(box=choice[0], score=choice[1], frame=frame) break pending = choice return result12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Saved-mask integration: source rows, dense artifacts and local run identity."""
from dataclasses import fieldsimport jsonimport osfrom pathlib import Pathimport tempfileimport unittestfrom unittest.mock import patch
import matplotlib.image as mpimgimport numpy as np
from visual.runtime.geometry import GeometricFeatures, process_geometryfrom visual.runtime.rgbd import BOX, PEG, iter_saved_rgbdfrom visual.runtime.test.run_geometry import evaluate
class GeometryEvaluationTests(unittest.TestCase): def test_sparse_sources_and_empty_mask_preserve_dense_features_without_rgb(self): count, height, width = 3, 9, 11 depth = np.ones((count, height, width), np.float32) depth[2] *= 2 depth[2, 4, 4] = np.nan source = np.array([0, 2], np.int32) peg = np.zeros((2, height, width), bool) peg[:, 1:8, 1:6] = True box = np.zeros_like(peg) box[1, 1:8, 7:10] = True # Deliberately no simulator GT in the input. episode = {"camera/rgb": np.full((count, height, width, 3), 110, np.uint8), "camera/depth": depth, "camera/intrinsic": np.tile([[100, 0, 5.5], [0, 100, 4.5], [0, 0, 1]], (count, 1, 1)), "camera/cam2world": np.tile(np.eye(4), (count, 1, 1)), "tcp_pose": np.tile([0, 0, 0, 1, 0, 0, 0], (count, 1)), "frame_idx": np.array([10, 11, 12]), "timestamp": np.array([0, 0.05, 0.1])} with tempfile.TemporaryDirectory() as directory: root = Path(directory) episode_path, masks_path = root / "episode.npz", root / "masks.npz" np.savez(episode_path, **episode) np.savez(masks_path, source_frame=source, peg=peg, box=box) with patch.dict(os.environ, {"WANDB_MODE": "disabled", "EXPERIMENTS_DIR": str(root / "experiments")}): output = evaluate(episode_path, masks_path, camera="camera", output_root=root / "out", selected_sources=[0, 2], repeats=1) data = json.loads((output / "geometry.json").read_text()) self.assertEqual([r["source_frame"] for r in data["frames"]], [0, 2]) self.assertEqual([r["frame_idx"] for r in data["frames"]], [10, 12]) self.assertEqual(data["summary"]["box"]["no_points_frames"], 1) self.assertEqual(data["frames"][0]["objects"]["box"]["observation_state"], "empty_mask") self.assertEqual(data["timing_ms"]["total"]["count"], 2) self.assertEqual(data["config"]["gt_segmentation_ids"], {}) self.assertEqual(len(data["config"]["input_sha256"]), 64) for frame in iter_saved_rgbd(episode_path, masks_path, camera="camera"): expected = process_geometry(frame) with np.load(output / f"f{frame.source_frame:04d}.npz", allow_pickle=False) as saved: self.assertNotIn("rgb", saved) self.assertEqual(int(saved["source_frame"]), frame.source_frame) self.assertEqual(int(saved["frame_idx"]), frame.frame_idx) np.testing.assert_array_equal(saved["xyz"], expected.geometry.xyz) for name, object_id in (("peg", PEG), ("box", BOX)): for field in fields(GeometricFeatures): np.testing.assert_array_equal(saved[f"{name}/{field.name}"], getattr(expected.objects[object_id], field.name)) image = mpimg.imread(output / f"f{frame.source_frame:04d}.png") self.assertGreater(image.shape[0], 1000) self.assertGreater(float(image.std()), 0.1) for name in ("geometry.html", "geometry.json", "f0000.npz", "f0000.png", "f0002.npz", "f0002.png"): sidecar = json.loads((output / f"{name}.tracking.json").read_text()) self.assertEqual(sidecar["run_id"], output.name) metadata = json.loads((root / "experiments" / output.name / "metadata.json").read_text()) self.assertEqual(metadata["status"], "finished") self.assertEqual(metadata["evaluation_device"], "cpu") self.assertFalse(metadata["gpu_executed"])
def test_invalid_diagnostic_parameters_fail_before_output(self): for arguments in (dict(repeats=0), dict(variation_degrees=np.nan), dict(variation_degrees=181)): with self.subTest(arguments=arguments), self.assertRaises(ValueError): evaluate("missing_episode", "missing_masks", output_root="unused", **arguments)
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""Detect objects with Grounding DINO, track them with SAM2, and save a movie.
Run from the repository root::
.venv/bin/python visual/runtime/test/run_tracking.py \ --input visual/data/step2/ep000.npz --device cuda
Grounding DINO jointly assigns peg and box boxes, including late initialization.SAM2 propagates their masks. Outputs include an MP4, PNGs, masks, and metadata."""
from __future__ import annotations
import argparseimport jsonimport sysimport tempfileimport timefrom contextlib import nullcontextfrom pathlib import Path
import cv2import imageio.v2 as imageioimport numpy as np
SCRIPT_DIR = Path(__file__).resolve().parentRUNTIME_DIR = SCRIPT_DIR.parentVISUAL_ROOT = SCRIPT_DIR.parents[1]DEFAULT_INPUT = VISUAL_ROOT / "data/step2/ep000.npz"sys.path.insert(0, str(RUNTIME_DIR))
from tracking import SAM2Tracker # noqa: E402from initialization import detect_initial # noqa: E402
OBJECTS = { "peg": (1, (255, 70, 70), "red and white block"), "box": (2, (60, 130, 255), "cardboard box"),}
def load_input(path: Path, camera: str, parser: argparse.ArgumentParser): """Return RGB frames, input kind, timestamps, and a useful default fps.""" if path.suffix.lower() == ".npz": with np.load(path) as archive: key = f"{camera}/rgb" if key not in archive: parser.error(f"{path} has no '{key}' array") frames = np.asarray(archive[key], dtype=np.uint8) timestamps = np.asarray(archive["timestamp"]) if "timestamp" in archive else None fps = 20.0 if timestamps is not None: if len(timestamps) != len(frames): parser.error(f"timestamp length {len(timestamps)} differs from frame count {len(frames)}") gaps = np.diff(timestamps.astype(np.float64)) gaps = gaps[gaps > 0] if len(gaps): fps = float(1.0 / np.median(gaps)) return frames, "episode", timestamps, fps
capture = cv2.VideoCapture(str(path)) if not capture.isOpened(): parser.error(f"could not open video: {path}") fps = float(capture.get(cv2.CAP_PROP_FPS)) frames = [] while True: ok, bgr = capture.read() if not ok: break frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)) capture.release() if not frames: parser.error(f"video contains no readable frames: {path}") if not np.isfinite(fps) or fps <= 0: fps = 20.0 return np.stack(frames), "video", None, fps
def initial_boxes(frames: np.ndarray, args) -> dict: """Run the RGB-only v1 joint assignment and late initialization.""" from grounding import GDino
detector = GDino(device=args.device, threshold=args.threshold) prompts = {name: getattr(args, f"{name}_prompt") or default_prompt for name, (_, _, default_prompt) in OBJECTS.items()} return detect_initial(frames, detector, prompts)
def render_frame(rgb: np.ndarray, masks: dict[int, object], initial: dict, frame_idx: int) -> np.ndarray: """Blend predicted masks and draw initial Grounding DINO boxes.""" out = rgb.copy() for name, (object_id, color, _) in OBJECTS.items(): mask = masks.get(object_id) if mask is None: continue if hasattr(mask, "detach"): mask = mask.detach().to("cpu").numpy() mask = np.asarray(mask, dtype=bool) if mask.shape != rgb.shape[:2]: mask = cv2.resize(mask.astype(np.uint8), (rgb.shape[1], rgb.shape[0]), interpolation=cv2.INTER_NEAREST).astype(bool) out[mask] = (0.45 * out[mask] + 0.55 * np.asarray(color)).astype(np.uint8) contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(out, contours, -1, color, max(1, min(rgb.shape[:2]) // 256)) ys, xs = np.nonzero(mask) if len(xs): cv2.putText(out, name, (int(xs.min()), max(18, int(ys.min()) - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2, cv2.LINE_AA)
for name, (object_id, color, _) in OBJECTS.items(): item = initial[name] if item["box"] is None or frame_idx != item["frame"]: continue x1, y1, x2, y2 = (int(round(value)) for value in item["box"]) cv2.rectangle(out, (x1, y1), (x2, y2), color, 1, cv2.LINE_AA) cv2.putText(out, f"GDINO {name}", (x1 + 3, max(16, y1 - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.42, color, 1, cv2.LINE_AA) cv2.putText(out, f"SAM2 mask + GDINO init box | frame {frame_idx}", (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2, cv2.LINE_AA) return out
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, default=DEFAULT_INPUT, help="Episode NPZ with camera RGB arrays or a video file") parser.add_argument("--out", type=Path, default=VISUAL_ROOT / "results/runtime_tracking") parser.add_argument("--camera", default="base_camera", help="Camera name for episode NPZ input") parser.add_argument("--device", default="cuda") parser.add_argument("--config", default="configs/sam2.1/sam2.1_hiera_s.yaml") parser.add_argument("--checkpoint", type=Path, default=VISUAL_ROOT / "checkpoints/sam2.1_hiera_small.pt") parser.add_argument("--threshold", type=float, default=0.1, help="Grounding DINO threshold used to initialize boxes") parser.add_argument("--stride", type=int, default=1, help="Track every Nth source frame and write those frames") parser.add_argument("--max-frames", type=int, default=None) parser.add_argument("--fps", type=float, default=None, help="Output fps; defaults to source fps / stride") parser.add_argument("--peg-prompt", default=None) parser.add_argument("--box-prompt", default=None) parser.add_argument("--hydra-override", action="append", default=[], help="SAM2 config override; may be passed more than once") args = parser.parse_args()
if args.stride < 1: parser.error("--stride must be at least 1") if args.fps is not None and args.fps <= 0: parser.error("--fps must be positive") if not args.input.is_file(): parser.error(f"input file does not exist: {args.input}") if not args.checkpoint.is_file(): parser.error(f"SAM2 checkpoint does not exist: {args.checkpoint}")
frames, input_kind, timestamps, source_fps = load_input(args.input, args.camera, parser) if frames.ndim != 4 or frames.shape[-1] != 3: parser.error(f"expected RGB frames with shape (T,H,W,3), got {frames.shape}") if timestamps is not None and len(timestamps) != len(frames): parser.error("timestamp and RGB frame counts differ") selected = list(range(0, len(frames), args.stride)) if args.max_frames is not None: selected = selected[:max(0, args.max_frames)] if not selected: parser.error("input contains no frames to track")
sampled = frames[selected] initial = initial_boxes(sampled, args) args.out.mkdir(parents=True, exist_ok=True) frames_dir = args.out / "frames" frames_dir.mkdir(parents=True, exist_ok=True) video_path = args.out / "tracking.mp4" if len(selected) > 1 else None output_fps = args.fps or source_fps / args.stride
tracker = SAM2Tracker(device=args.device, config=args.config, checkpoint=args.checkpoint, hydra_overrides=args.hydra_override) records = [] started = time.perf_counter() with tempfile.TemporaryDirectory(prefix="sam2_runtime_") as frame_dir: for local_idx, source_idx in enumerate(selected): frame_path = Path(frame_dir) / f"{local_idx:06d}.jpg" cv2.imwrite(str(frame_path), cv2.cvtColor(frames[source_idx], cv2.COLOR_RGB2BGR))
height, width = sampled.shape[1:3] masks_by_name = {name: np.zeros((len(selected), height, width), dtype=bool) for name in OBJECTS} first_group = [name for name in OBJECTS if initial[name]["frame"] == 0] groups = [(first_group, 0)] if first_group else [] groups += [([name], initial[name]["frame"]) for name in OBJECTS if initial[name]["frame"] not in (0, None)] for names, start in groups: boxes = {OBJECTS[name][0]: initial[name]["box"] for name in names} state = tracker.start(frame_dir, boxes, frame_idx=start) try: for local_idx, masks in tracker.track(state, start_frame=start): for name in names: mask = masks.get(OBJECTS[name][0]) if mask is None: continue if hasattr(mask, "detach"): mask = mask.detach().cpu().numpy() mask = np.asarray(mask, dtype=bool) if mask.shape != (height, width): mask = cv2.resize(mask.astype(np.uint8), (width, height), interpolation=cv2.INTER_NEAREST).astype(bool) masks_by_name[name][local_idx] = mask finally: tracker.reset(state)
np.savez_compressed(args.out / "masks.npz", **masks_by_name, source_frame=np.asarray(selected, dtype=np.int32)) writer_context = (imageio.get_writer(video_path, fps=output_fps, macro_block_size=1) if video_path else nullcontext(None)) with writer_context as writer: for local_idx, source_idx in enumerate(selected): masks = {OBJECTS[name][0]: values[local_idx] for name, values in masks_by_name.items()} rendered = render_frame(frames[source_idx], masks, initial, local_idx) cv2.imwrite(str(frames_dir / f"frame_{source_idx:05d}.png"), cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) if writer is not None: writer.append_data(rendered) records.append({"frame": int(source_idx), "objects": { name: {"object_id": object_id, "mask_pixels": int(masks_by_name[name][local_idx].sum())} for name, (object_id, _, _) in OBJECTS.items()}}) print(f"tracked frame {source_idx} ({local_idx + 1}/{len(selected)})", flush=True)
result = { "input": str(args.input.resolve()), "input_kind": input_kind, "camera": args.camera if input_kind == "episode" else None, "device": args.device, "config": args.config, "checkpoint": str(args.checkpoint.resolve()), "source_fps": source_fps, "output_fps": output_fps, "stride": args.stride, "frames_tracked": len(records), "elapsed_seconds": round(time.perf_counter() - started, 3), "initial_boxes": initial, "mask_file": str(args.out / "masks.npz"), "video": str(video_path) if video_path else None, "frames_dir": str(frames_dir), "results": records, } (args.out / "tracking.json").write_text(json.dumps(result, indent=2), encoding="utf-8") if video_path: print(f"saved video: {video_path}") print(f"saved frames: {frames_dir}") print(f"saved metadata: {args.out / 'tracking.json'}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259diff --git a/docs/visual-graph-integration/03_sampling.md b/docs/visual-graph-integration/03_sampling.mdindex acb3c0f..ac76cf2 100644--- a/docs/visual-graph-integration/03_sampling.md+++ b/docs/visual-graph-integration/03_sampling.md@@ -7,6 +7,10 @@ S4 depth-only 우선 선택은 이 조건에서 Peg 보존을 낮추고 가림· 이 수치는 **Tracker가 현재 관측한 reference 대비 Sampling 보존율**이다. 최종 detector, threshold, ratio 또는 feature 표현을 채택한 결과는 아니다. +후속 [Task03-D Box rim 병목 분석 Phase 1](03d_box_rim_bottleneck_phase1.md)은 저장된 frame 0/120의+관측·후보·priority·Surface coverage를 분리한다. Frame 0의 S3는 후보 coverage가 더 높지만+priority와 최종 coverage는 더 낮았다. 오염·원거리 depth·FPS 거리 경쟁의 인과 기여율은 미확인이다.+ 최종 run: `2551448b0fae4c6bbce3caf48774275f`. [전체 HTML](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.html), [전체 summary·설정·fidelity JSON](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json), [검증 기록](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/verification.json), [budget/ratio/false selection/latency 그림](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/tradeoffs.png),diff --git a/visual/runtime/test/sampling_evaluation.py b/visual/runtime/test/sampling_evaluation.pyindex ea0f223..e242ecc 100644--- a/visual/runtime/test/sampling_evaluation.py+++ b/visual/runtime/test/sampling_evaluation.py@@ -44,6 +44,25 @@ class CoverageMatcher: @staticmethod def key(px,m): return f'{px:g}px_{m*1000:g}mm' + def reference_hits(self, selected_flat, px=2., m=.003):+ """Reference IDs and matched source nodes from the existing joint adjacency.++ IDs are row positions in the saved reference arrays, not rounded pixels.+ A node can cover multiple IDs; multiple nodes covering one ID count once.+ """+ selected_flat = np.asarray(selected_flat)+ if selected_flat.ndim != 1 or selected_flat.dtype.kind not in 'iu':+ raise ValueError('source indices must be a one-dimensional integer array')+ if len(np.unique(selected_flat)) != len(selected_flat):+ raise ValueError('duplicate source nodes')+ rows = np.searchsorted(self.flat, selected_flat)+ if len(rows) and ((rows >= len(self.flat)).any()+ or not np.array_equal(self.flat[rows], selected_flat)):+ raise ValueError('evaluation points outside observed support')+ adjacency = self.adjacencies[self.key(px, m)][rows]+ return (np.flatnonzero(adjacency.getnnz(axis=0)),+ selected_flat[adjacency.getnnz(axis=1) > 0])+ def score(self, selected_flat): rows = np.searchsorted(self.flat, selected_flat) if len(rows) and ((rows >= len(self.flat)).any() or not np.array_equal(self.flat[rows], selected_flat)):@@ -78,6 +97,61 @@ class CoverageMatcher: return out, arrays +def count_ratio(numerator, denominator):+ """Preserve raw counts, including undefined zero-denominator fractions."""+ return dict(numerator=int(numerator), denominator=int(denominator),+ value=numerator/denominator if denominator else None)+++def staged_reference_coverage(matcher, candidates, priority, surface, final):+ """Saved-set diagnosis only; no candidate extraction or selection is run.++ C/P are None for the General FPS control, rather than empty candidate sets.+ Set differences overlap and must not be summed as causal loss fractions.+ """+ if (candidates is None) != (priority is None):+ raise ValueError('candidate and priority applicability must agree')+ nodes = dict(X=matcher.flat, C=candidates, P=priority, S=surface, F=final)+ hits, stages = {}, {}+ for name, flat in nodes.items():+ if flat is None:+ hits[name] = None+ stages[name] = None+ continue+ ids, matched = matcher.reference_hits(flat)+ hits[name] = set(ids.tolist())+ stages[name] = dict(node_count=len(flat), matched_node_count=len(matched),+ unique_reference_count=len(ids))+ p = np.asarray(priority if priority is not None else [], dtype=np.int64)+ if np.intersect1d(p, surface).size or set(final) != set(p) | set(surface):+ raise ValueError('final nodes must be the disjoint priority/surface union')+ if candidates is not None and not set(p) <= set(candidates):+ raise ValueError('priority nodes outside candidate support')+ v, o = set(range(matcher.nref)), hits['X']+ c, p, s, f = hits['C'], hits['P'], hits['S'], hits['F']+ if not f <= o or (c is not None and not c <= o):+ raise AssertionError('covered references outside observable references')+ if f != (p or set()) | s:+ raise AssertionError('final reference union differs from priority/surface')+ differences = {'V_minus_O': v-o, 'O_minus_F': o-f}+ if c is not None:+ differences.update(O_minus_C=o-c, C_minus_P=c-p, C_minus_F=c-f,+ P_intersect_S=p&s, S_minus_P=s-p, S_minus_C=s-c,+ C_minus_P_intersect_S=(c-p)&s)+ else:+ differences.update({key: None for key in ('O_minus_C', 'C_minus_P', 'C_minus_F',+ 'P_intersect_S', 'S_minus_P', 'S_minus_C', 'C_minus_P_intersect_S')})+ coverage = dict(observation=count_ratio(len(o), len(v)))+ for name, key in [('C', 'candidate'), ('P', 'priority'), ('S', 'surface'), ('F', 'final_retention')]:+ coverage[key] = count_ratio(len(hits[name]), len(o)) if hits[name] is not None else None+ return dict(stages=stages, coverage=coverage,+ gt_final_coverage=count_ratio(len(f), len(v)),+ reference_ids={k: sorted(ids) if ids is not None else None+ for k, ids in dict(V=v, O=o, **hits).items()},+ differences={k: dict(count=len(ids), reference_ids=sorted(ids)) if ids is not None else None+ for k, ids in differences.items()})++ def evaluation_context(frame, evidence, gt, camera, robot_ids): """Reuse unchanged Task02 visible seam/rim definition; GT read after extraction.""" truths, regions, maps = real_truth(frame, evidence.frame, gt, camera)diff --git a/visual/runtime/test/test_sampling_evaluation.py b/visual/runtime/test/test_sampling_evaluation.pyindex 798172c..6975e66 100644--- a/visual/runtime/test/test_sampling_evaluation.py+++ b/visual/runtime/test/test_sampling_evaluation.py@@ -13,7 +13,10 @@ from visual.runtime.rgbd import PEG, BOX from visual.runtime.sampling import extract_sampling_evidence, sample_points, SamplingConfig from visual.runtime.test.normal_diagnostics import synthetic_frame, oracle, box_primitives, rim_region from visual.runtime.test.run_structural_edges import rim_reference-from visual.runtime.test.sampling_evaluation import CoverageMatcher+from visual.runtime.test.sampling_evaluation import CoverageMatcher, staged_reference_coverage+from visual.runtime.test.run_rim_bottleneck import (+ geometry_evidence, validate_saved_selection, occupancy, source_contract,+) from visual.runtime.test.run_sampling import conditions, evaluate @@ -110,4 +113,135 @@ class SamplingEvaluationTests(unittest.TestCase): with self.assertRaises(ValueError):evaluate(episode,masks,root/'out',camera='camera',selected=(),make_plots=False) +class StagedCoverageTests(unittest.TestCase):+ def fixture(self):+ mask = np.zeros((16, 16), bool)+ mask[5, [3, 6, 10]] = True+ k = np.array([[1000., 0, 8], [0, 1000., 8], [0, 0, 1]])+ frame = synthetic_frame(np.full((16, 16), .3, np.float32), k, mask)+ geometry = build_organized_geometry(frame)+ uv = np.array([[2., 5], [4.5, 5], [7., 5], [10., 5]])+ xyz = np.tile(geometry.xyz[5, 6], (4, 1))+ matcher = CoverageMatcher(geometry, PEG, (uv, xyz))+ return frame, geometry, matcher++ def test_reference_overlap_union_and_surface_outside_candidates(self):+ _, _, matcher = self.fixture()+ c, p, s, f = [np.array(a, np.int64) for a in ([83, 86], [83], [86, 90], [90, 83, 86])]+ row = staged_reference_coverage(matcher, c, p, s, f)+ self.assertEqual(row['reference_ids']['C'], [0, 1, 2])+ self.assertEqual(row['reference_ids']['P'], [0, 1])+ self.assertEqual(row['reference_ids']['S'], [1, 2, 3])+ self.assertEqual(row['reference_ids']['F'], [0, 1, 2, 3])+ self.assertEqual(row['stages']['C'], dict(node_count=2, matched_node_count=2, unique_reference_count=3))+ expected = dict(V_minus_O=0, O_minus_C=1, C_minus_P=1, C_minus_F=0,+ P_intersect_S=1, S_minus_P=2, S_minus_C=1,+ C_minus_P_intersect_S=1, O_minus_F=0)+ self.assertEqual({k: v['count'] for k, v in row['differences'].items()}, expected)+ self.assertEqual(row['coverage']['candidate'], dict(numerator=3, denominator=4, value=.75))++ def test_two_different_nodes_cannot_satisfy_one_reference_pair(self):+ frame, _, _ = self.fixture()+ intrinsic = frame.intrinsic.copy(); intrinsic[0, 0] = 100.+ geometry = build_organized_geometry(replace(frame, intrinsic=intrinsic))+ # Node 83 satisfies 2D only; node 90 satisfies 3D only.+ matcher = CoverageMatcher(geometry, PEG, (np.array([[3., 5]]), geometry.xyz[5, 10][None]))+ ids, matched = matcher.reference_hits(np.array([83, 90]))+ self.assertEqual((len(ids), len(matched)), (0, 0))++ def test_empty_points_zero_observation_and_zero_visible(self):+ frame, geometry, matcher = self.fixture()+ empty = np.array([], np.int64)+ row = staged_reference_coverage(matcher, empty, empty, empty, empty)+ self.assertEqual(row['coverage']['final_retention'], dict(numerator=0, denominator=4, value=0.))+ geometry = build_organized_geometry(replace(frame, masks={PEG: np.zeros_like(frame.depth, bool)}))+ for refs in ((matcher.ref_uv, matcher.ref_xyz), (np.empty((0, 2)), np.empty((0, 3)))):+ row = staged_reference_coverage(CoverageMatcher(geometry, PEG, refs), empty, empty, empty, empty)+ self.assertEqual(row['coverage']['final_retention'], dict(numerator=0, denominator=0, value=None))+ self.assertEqual(row['coverage']['observation']['numerator'], 0)+ self.assertEqual(row['coverage']['observation']['denominator'], len(refs[0]))++ def test_general_fps_candidate_and_priority_are_inapplicable(self):+ _, _, matcher = self.fixture()+ flat = matcher.flat+ row = staged_reference_coverage(matcher, None, None, flat, flat)+ for name in ('C', 'P'):+ self.assertIsNone(row['stages'][name])+ self.assertIsNone(row['coverage']['candidate'])+ self.assertIsNone(row['coverage']['priority'])+ self.assertIsNone(row['differences']['O_minus_C'])+ self.assertEqual(row['coverage']['surface'], row['coverage']['final_retention'])++ def test_invalid_nodes_and_non_partition_are_rejected(self):+ _, _, matcher = self.fixture()+ for flat in (np.array([0]), np.array([83, 83]), np.array([256]), np.array([-1]), np.array([83.])):+ with self.assertRaises(ValueError):+ matcher.reference_hits(flat)+ with self.assertRaises(ValueError):+ staged_reference_coverage(matcher, np.array([83]), np.array([86]), np.array([90]), np.array([86, 90]))+ with self.assertRaises(ValueError):+ staged_reference_coverage(matcher, matcher.flat, np.array([83]), np.array([83, 90]), np.array([83, 90]))+ with self.assertRaises(ValueError):+ staged_reference_coverage(matcher, matcher.flat, np.array([83]), np.array([90]), matcher.flat)++ def test_geometry_alignment_invalid_depth_overlap_and_pixel_centres(self):+ frame, _, _ = self.fixture()+ depth = frame.depth.copy()+ depth[5, 6] = 0+ depth[2, 2] = np.nan+ box = np.zeros_like(depth, bool)+ box[5, 10] = True # ambiguous in BOTH masks+ frame = replace(frame, depth=depth, masks={PEG: frame.masks[PEG], BOX: box})+ evidence = geometry_evidence(frame)+ geometry = evidence.frame.geometry+ self.assertEqual(np.flatnonzero(geometry.observed_mask(PEG)).tolist(), [83])+ self.assertFalse(geometry.observed_mask(BOX).any())+ self.assertTrue(np.isnan(geometry.xyz[5, 6]).all())+ z = float(depth[5, 3])+ np.testing.assert_allclose(geometry.xyz[5, 3], [(3.5-8)*z/1000, (5.5-8)*z/1000, z], rtol=1e-7)+ # Minimal evaluation adapter has exactly the existing validity ROI field.+ from visual.runtime.geometry import compute_geometric_features, GeometryParameters+ for oid in (PEG, BOX):+ features = compute_geometric_features(geometry, oid, np.full_like(geometry.xyz, np.nan),+ np.zeros_like(depth, bool), GeometryParameters())+ np.testing.assert_array_equal(evidence.frame.objects[oid].depth_validity_boundary,+ features.depth_validity_boundary)+ key = 'saved'+ archive = {'source_frame': np.array(frame.source_frame), 'shape': np.array(depth.shape),+ key+'/flat_index': np.array([83]), key+'/pixels_vu': np.array([[5, 3]]),+ key+'/object_id': np.array([PEG]), key+'/points': geometry.xyz[5, 3][None].copy(),+ key+'/priority_selected': np.array([False]), key+'/depth_priority_selected': np.array([False])}+ self.assertTrue(validate_saved_selection(archive, key, frame, geometry)['xyz_exact'])+ for field, corrupted in [('points', archive[key+'/points']+.001), ('pixels_vu', np.array([[5, 4]])),+ ('object_id', np.array([BOX]))]:+ with self.assertRaises((ValueError, AssertionError)):+ validate_saved_selection(dict(archive, **{key+'/'+field: corrupted}), key, frame, geometry)+ with self.assertRaises(ValueError):+ validate_saved_selection(dict(archive, source_frame=np.array(frame.source_frame+1)), key, frame, geometry)++ def test_negative_union_deduplicates_and_depth_bands_cover_paths(self):+ frame, _, matcher = self.fixture()+ a = np.zeros_like(frame.depth, bool); b = a.copy()+ a[5, [3, 6]] = True; b[5, [6, 10]] = True+ row = occupancy(frame, dict(X=matcher.flat, C=None, P=None, S=matcher.flat, F=matcher.flat), dict(a=a, b=b))+ roi = row['negative_roi']+ self.assertEqual(roi['a']['F']['count']+roi['b']['F']['count'], 4)+ self.assertEqual(roi['known_negative_union']['F']['count'], 3)+ self.assertIsNone(roi['known_negative_union']['P'])+ self.assertEqual(sum(v['numerator'] for v in row['depth_quantile_occupancy']['F'].values()), 3)++ def test_historical_evaluation_changes_fail_closed(self):+ import hashlib+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ relative = 'visual/runtime/test/sampling_evaluation.py'+ snapshot = root/'evaluated_source'/relative+ snapshot.parent.mkdir(parents=True)+ source = Path(relative).read_text().replace('<= m', '<= m*2', 1)+ snapshot.write_text(source)+ config = {'source_sha256': {relative: hashlib.sha256(snapshot.read_bytes()).hexdigest()}}+ with self.assertRaisesRegex(ValueError, 'historical evaluation definition'):+ source_contract(root, config)++ if __name__=='__main__':unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Causal SAM2 -> PCA5 timing, excluding cached initial grounding and startup.
Only currently implemented geometry is produced; final Graph sampling/edgesare deliberately not fabricated. Reports queue growth at 20Hz without drops."""from __future__ import annotationsimport argparsefrom dataclasses import replaceimport importlibimport jsonfrom pathlib import Pathimport sysimport time
import numpy as npimport torch
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.rgbd import iter_saved_rgbdfrom visual.runtime.tracking import SAM2Trackerfrom visual.scripts.stream_v1 import CausalFrames, StreamTrackerfrom visual.runtime.test.pca_optimized import process_optimizedfrom visual.runtime.test.pca_torch import TorchPCA5from visual.runtime.test.normal_diagnostics import statsfrom visual.runtime.test.run_normal_diagnostics import save_json
class DeviceStreamTracker(StreamTracker): """Reuse causal tracking operations; supply the predictor's actual device.
The legacy StreamTracker initialization hardcodes CausalFrames' CUDA default. This harness only adapts its frame-buffer construction for CPU. """ def _init_state(self, rgb0): mod = importlib.import_module(type(self.p).__module__) h, w = rgb0.shape[:2] frames = CausalFrames(self.p.image_size, device=self.p.device, keep=self.keep_frames, preprocess=self.pre) frames.push(rgb0) original = mod.load_video_frames mod.load_video_frames = lambda **kw: (frames, h, w) try: state = self.p.init_state(video_path='<stream>') finally: mod.load_video_frames = original self.frames = frames return state
def benchmark(input_path, masks_path, tracking_path, checkpoint, *, device, count, output_root, backend='eigh', compile_image_encoder=False, cpu_parallel=False, encoder_warmup=0, tracker_warmup_steps=0): if count < 2: raise ValueError('count must include startup and at least one subsequent frame') input_path, masks_path, tracking_path, checkpoint = map(Path, (input_path,masks_path,tracking_path,checkpoint)) frames = list(iter_saved_rgbd(input_path,masks_path))[:count] tracking = json.loads(tracking_path.read_text()) boxes = {i+1:tracking['initial_boxes'][name]['box'] for i,name in enumerate(('peg','box'))} cfg = dict(task='pca5_streaming_budget',device=device,backend=backend,compile_image_encoder=compile_image_encoder,cpu_parallel=cpu_parallel,encoder_warmup=encoder_warmup,tracker_warmup_steps=tracker_warmup_steps,warmup_uses_only_first_rgb=True,frames=len(frames),target_period_ms=50, initial_grounding='cached initial boxes; grounding not run or timed',startup_excluded=True, checkpoint_sha256=digests(checkpoint)[1], input_sha256=digests(input_path)[1], tracker_config=tracking['config'],preprocess='gpu',initial_boxes=boxes, final_graph_handoff_implemented=False,frame_drops=0,geometry='optimized_analytic' if device=='cpu' else 'torch_float64_pca5', clock='scheduled 50ms arrivals; all frames processed causally; queue delay included in arrival-to-geometry-ready', source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in [Path(__file__),REPO/'visual/scripts/stream_v1.py',REPO/'visual/runtime/test/pca_torch.py',REPO/'visual/runtime/test/pca_optimized.py']}) with ExperimentLogger(team='visual',config=cfg,seed=0,model='pca5_causal_stream',job_type='evaluate') as logger: out=Path(output_root)/logger.run_id;out.mkdir(parents=True,exist_ok=False);print('Output:',out,flush=True) if device=='cuda' and not torch.cuda.is_available(): save_json(out/'streaming.json',dict(run_id=logger.run_id,config=cfg,status='not_executed',reason='CUDA unavailable')) logger.link_output(out/'streaming.json',kind='metrics');logger.record(gpu_executed=False);return out torch.set_num_threads(4) start=time.perf_counter() overrides=['++model.compile_image_encoder=True'] if compile_image_encoder else None predictor=SAM2Tracker(device=device,checkpoint=checkpoint,config=tracking['config'],hydra_overrides=overrides).predictor tracker=DeviceStreamTracker(predictor,preprocess='gpu',prune=True,keep_mem=16,keep_frames=2) processor=TorchPCA5(frames[0].intrinsic,frames[0].depth.shape,device=device,backend=backend) if device=='cuda' else None autocast = torch.autocast(device_type='cuda',dtype=torch.bfloat16,enabled=device=='cuda') rows=[];saved_masks=[] def sync(): if device=='cuda':torch.cuda.synchronize() with torch.inference_mode(),autocast: masks=tracker.start(frames[0].rgb,boxes) # Warm only the already available first RGB, without advancing or # resetting tracker state or accessing a future observation. for _ in range(encoder_warmup): predictor.image_encoder(tracker.frames[0][None]) for _ in range(tracker_warmup_steps): tracker.step(frames[0].rgb) if tracker_warmup_steps: tracker.reset() masks=tracker.start(frames[0].rgb,boxes) assert tracker.frames.latest==0 # fresh actual observation state if device=='cpu':process_optimized(replace(frames[0],masks={i-1:m.cpu().numpy() for i,m in masks.items()}),solver='analytic',parallel=cpu_parallel) else:processor(torch.as_tensor(frames[0].depth,device='cuda'),{i-1:m for i,m in masks.items()}) sync();startup=(time.perf_counter()-start)*1000 epoch=time.perf_counter() for idx,frame in enumerate(frames[1:]): arrival=epoch+idx*.05 delay=arrival-time.perf_counter() if delay>0:time.sleep(delay) sync();begin=time.perf_counter() fi,masks=tracker.step(frame.rgb);sync();after_tracking=time.perf_counter() if device=='cpu': masks={i-1:m.detach().cpu().numpy() for i,m in masks.items()};after_transfer=time.perf_counter() geometry=process_optimized(replace(frame,masks=masks),solver='analytic',parallel=cpu_parallel) points=sum(int(f.valid_points.sum()) for f in geometry.objects.values()) else: depth=torch.as_tensor(frame.depth,device='cuda'); masks={i-1:m for i,m in masks.items()};sync();after_transfer=time.perf_counter() geometry=processor(depth,masks) points=None # avoid a timed host reduction/synchronization for reporting sync();end=time.perf_counter() saved_masks.append(masks) rows.append(dict(source_frame=frame.source_frame,tracker_frame=fi,queue_wait_ms=(begin-arrival)*1000, tracking_ms=(after_tracking-begin)*1000,transfer_ms=(after_transfer-after_tracking)*1000, geometry_ms=(end-after_transfer)*1000,service_ms=(end-begin)*1000, arrival_to_geometry_ready_ms=(end-arrival)*1000,observed_points=points)) print('Stream frame',frame.source_frame,'service_ms',round(rows[-1]['service_ms'],2),flush=True) elapsed=time.perf_counter()-epoch tracker.reset() # Keep references during timing; transfer/serialize the masks afterward. arrays={name:np.stack([(m[i].detach().cpu().numpy() if device=='cuda' else m[i]) for m in saved_masks]) for name,i in [('peg',0),('box',1)]} np.savez_compressed(out/'tracked_masks.npz',source_frame=np.array([r['source_frame'] for r in rows]),**arrays) logger.link_output(out/'tracked_masks.npz',kind='trajectory') keys=['tracking_ms','transfer_ms','geometry_ms','service_ms','queue_wait_ms','arrival_to_geometry_ready_ms'] summary={k:stats([r[k] for r in rows]) for k in keys} data=dict(run_id=logger.run_id,config=cfg,status='executed',startup_excluded_ms=startup,summary=summary,frames=rows, achieved_hz=len(rows)/elapsed,service_over_50ms=sum(r['service_ms']>50 for r in rows), arrival_deadline_misses=sum(r['arrival_to_geometry_ready_ms']>50 for r in rows), final_graph_handoff_measured=False,scope='RGB available to implemented geometry ready; sampling/edges/Graph packaging absent') save_json(out/'streaming.json',data);logger.link_output(out/'streaming.json',kind='metrics') logger.log(summary,prefix='eval/streaming');logger.record(gpu_executed=device=='cuda',initial_grounding_excluded=True) return out
def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') p.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') p.add_argument('--tracking',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/tracking.json') p.add_argument('--checkpoint',type=Path,default=REPO/'visual/checkpoints/sam2.1_hiera_small.pt') p.add_argument('--device',choices=['cpu','cuda'],default='cpu');p.add_argument('--frames',type=int,default=12) p.add_argument('--backend',choices=['eigh','triton','triton_fused'],default='eigh') p.add_argument('--compile-image-encoder',action='store_true') p.add_argument('--cpu-parallel',action='store_true') p.add_argument('--encoder-warmup',type=int,default=0) p.add_argument('--tracker-warmup-steps',type=int,default=0) p.add_argument('--out',type=Path,default=REPO/'visual/results/pca_optimization') a=p.parse_args();print(benchmark(a.input,a.masks,a.tracking,a.checkpoint,device=a.device,count=a.frames,output_root=a.out,backend=a.backend,compile_image_encoder=a.compile_image_encoder,cpu_parallel=a.cpu_parallel,encoder_warmup=a.encoder_warmup,tracker_warmup_steps=a.tracker_warmup_steps))
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Observation-only adjacent-pixel evidence promoted unchanged from Task 02-C.
These are independent causes, never final structural labels or graph edges."""from dataclasses import dataclassimport numpy as npfrom visual.runtime.geometry import GeometryParametersPARAMETERS = GeometryParameters()
@dataclass(frozen=True)class PairEvidence: shape: tuple pixels: np.ndarray # [P,2] source flat indices, right/down neighbour once supported: np.ndarray # [P,2] unambiguous observed object endpoint mask_boundary: np.ndarray invalid_depth_boundary: np.ndarray # XOR depth validity, not zero-depth jump overlap: np.ndarray # [P,2], ambiguous tracker membership signed_depth_delta_m: np.ndarray # z(second)-z(first), NaN unless both valid depth_jump: np.ndarray normal_angle_deg: np.ndarray # NaN unless both normals available near_endpoint: np.ndarray # local pair endpoint 0/1, -1 unless a depth jump far_endpoint: np.ndarray
def endpoint_mask(self, selected, side=None): result = np.zeros(np.prod(self.shape), bool) for k in (0, 1): keep = selected & self.supported[:, k] if side is not None: keep &= side == k result[self.pixels[keep, k]] = True return result.reshape(self.shape)
def candidates(self, threshold): if not np.isfinite(threshold) or threshold < 0: raise ValueError('angle threshold must be finite and nonnegative') orientation = self.endpoint_mask(self.normal_angle_deg > threshold) depth = self.endpoint_mask(self.depth_jump) return dict(orientation=orientation, depth=depth, union=orientation | depth, occluding=self.endpoint_mask(self.depth_jump, self.near_endpoint), occluded=self.endpoint_mask(self.depth_jump, self.far_endpoint), invalid=self.endpoint_mask(self.invalid_depth_boundary), mask=self.endpoint_mask(self.mask_boundary))
def pair_evidence(geometry, object_id, normals, normal_valid, parameters=PARAMETERS): """Preserve all adjacent pairs touching the raw object mask, even invalids.
Mask transition, invalid depth and overlap flags are independent. An external finite-depth neighbour is retained to determine jump direction. Its XYZ is never included as an object normal support or an object candidate point. """ shape = geometry.valid_depth.shape indices = np.arange(np.prod(shape), dtype=np.int32).reshape(shape) mask = geometry.object_masks[object_id] support = geometry.observed_mask(object_id) parts = [] for a, b in (((slice(None), slice(None, -1)), (slice(None), slice(1, None))), ((slice(None, -1), slice(None)), (slice(1, None), slice(None)))): keep = mask[a] | mask[b] parts.append(np.column_stack((indices[a][keep], indices[b][keep]))) pixels = np.concatenate(parts) valid = geometry.valid_depth.ravel()[pixels] both = valid.all(1) z = geometry.xyz[..., 2].ravel()[pixels] delta = np.full(len(pixels), np.nan, np.float32) delta[both] = z[both, 1]-z[both, 0] jump = np.zeros(len(pixels), bool) jump[both] = np.abs(delta[both]) > (parameters.depth_jump_abs_m + parameters.depth_jump_rel*np.min(z[both], axis=1)) nv = normal_valid.ravel()[pixels].all(1) angles = np.full(len(pixels), np.nan, np.float32) n = normals.reshape(-1, 3)[pixels[nv]] angles[nv] = np.rad2deg(np.arctan2(np.linalg.norm(np.cross(n[:, 0], n[:, 1]), axis=1), np.einsum('ij,ij->i', n[:, 0], n[:, 1]))) near = np.full(len(pixels), -1, np.int8) near[jump] = np.argmin(z[jump], axis=1).astype(np.int8) far = np.where(jump, 1-near, -1).astype(np.int8) return PairEvidence(shape, pixels, support.ravel()[pixels], np.logical_xor(mask.ravel()[pixels[:, 0]], mask.ravel()[pixels[:, 1]]), valid[:, 0] ^ valid[:, 1], geometry.overlap_mask.ravel()[pixels], delta, jump, angles, near, far)1234567{ "status": "FAIL", "exception_type": "ValueError", "reason": "finish the experiment before registering post-run artifacts", "no_automatic_reselection": true, "existing_attempt_preserved": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Organized, observation-only NumPy geometry diagnostics (Task 01).
All arrays retain the source (v, u) image layout. This is an internal baseline,not structural classification, sampling, or the final Vision--Graph interface.No RGB values, object GT, erosion, outlier removal, or reconstruction are used."""
from __future__ import annotations
from dataclasses import dataclassfrom time import perf_counter
import numpy as np
from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFrame
@dataclass(frozen=True)class GeometryParameters: """Adjacent z jump > abs + rel * min(z1, z2), in metres.
These are diagnostic baseline thresholds, not edge-classification settings. The same gate prevents a normal stencil from crossing a detected z jump. """
depth_jump_abs_m: float = 0.01 depth_jump_rel: float = 0.02
def __post_init__(self) -> None: values = (self.depth_jump_abs_m, self.depth_jump_rel) if not np.isfinite(values).all() or min(values) < 0: raise ValueError("depth jump thresholds must be finite and nonnegative")
@dataclass(frozen=True)class OrganizedGeometry: """CV-camera XYZ in metres; invalid depth has three NaNs, never a point.
``xyz[v, u]`` corresponds to source pixel centre ``(u+.5, v+.5)``. Finite background geometry is retained, but only ``observed_mask(id)`` may be used as that object's points. Overlapping tracker masks are preserved and marked ambiguous; those pixels are excluded from BOTH object supports. """
xyz: np.ndarray valid_depth: np.ndarray object_masks: dict[int, np.ndarray] overlap_mask: np.ndarray
def observed_mask(self, object_id: int) -> np.ndarray: return self.object_masks[object_id] & self.valid_depth & ~self.overlap_mask
@dataclass(frozen=True)class GeometricFeatures: """Pixel-aligned diagnostics for one object, without semantic edge labels.
Unavailable floating features are NaN and have explicit validity masks. ``depth_jump_m`` compares a supported centre to ANY finite 4-neighbour, including other labels/background; it measures observation discontinuity. Mask, invalid-depth, and image boundaries are separate diagnostic flags. ``mask_boundary`` can include invalid/ambiguous mask pixels: it is NOT a point selection. Geometry selection always requires ``valid_points``. Normal variation is the maximum angle (radians) to supported same-object 4-neighbour normals; even a smooth curved surface can have a large value. """
object_mask: np.ndarray valid_points: np.ndarray normals: np.ndarray normal_valid: np.ndarray depth_jump_m: np.ndarray depth_pair_valid: np.ndarray depth_discontinuity: np.ndarray mask_boundary: np.ndarray depth_validity_boundary: np.ndarray image_boundary: np.ndarray normal_variation_rad: np.ndarray normal_variation_valid: np.ndarray normal_neighbor_count: np.ndarray
@dataclass(frozen=True)class GeometryFrame: source_frame: int camera: str frame_idx: int | None timestamp: float | None geometry: OrganizedGeometry objects: dict[int, GeometricFeatures] timings_ms: dict[str, float]
def build_organized_geometry(frame: TrackedRGBDFrame) -> OrganizedGeometry: """Adapt pointcloud.backproject's pixel-centre equations to dense layout.
Kept NumPy-only rather than importing the legacy plotting/SciPy module. No depth is filtered, filled, smoothed, or selected before feature analysis. """ depth = np.asarray(frame.depth) if depth.ndim != 2 or not min(depth.shape) or not np.issubdtype(depth.dtype, np.floating): raise ValueError("depth must be a nonempty floating point (H,W) array in metres") intrinsic = np.asarray(frame.intrinsic, dtype=np.float64) if (intrinsic.shape != (3, 3) or not np.isfinite(intrinsic).all() or intrinsic[0, 0] <= 0 or intrinsic[1, 1] <= 0): raise ValueError("intrinsic must be finite (3,3) with positive focal lengths") # The legacy equations assume the standard zero-skew CV pinhole intrinsic. if not np.allclose(intrinsic[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1]): raise ValueError("intrinsic must use the standard zero-skew CV pinhole form") if set(frame.masks) - {PEG, BOX}: raise ValueError("unknown output object ID; expected PEG=0 or BOX=1") masks = {} for object_id in (PEG, BOX): mask = np.asarray(frame.masks.get(object_id, np.zeros(depth.shape, dtype=bool))) if mask.shape != depth.shape or mask.dtype != np.bool_: raise ValueError("object masks must be boolean (H,W) arrays matching depth") masks[object_id] = mask.copy() valid = np.isfinite(depth) & (depth > 0) xyz = np.full((*depth.shape, 3), np.nan, dtype=np.float32) v, u = np.nonzero(valid) # Exactly the equations in visual/scripts/pointcloud.py::backproject. z = depth[v, u] xyz[v, u, 0] = (u + 0.5 - intrinsic[0, 2]) * z / intrinsic[0, 0] xyz[v, u, 1] = (v + 0.5 - intrinsic[1, 2]) * z / intrinsic[1, 1] xyz[v, u, 2] = z if not np.isfinite(xyz[valid]).all(): raise ValueError("finite positive depth/intrinsic must yield representable float32 XYZ") return OrganizedGeometry(xyz, valid, masks, masks[PEG] & masks[BOX])
def _pairs(): """Each in-image horizontal/vertical pair once; no wrap or padded neighbours.""" yield (slice(None), slice(None, -1)), (slice(None), slice(1, None)) yield (slice(None, -1), slice(None)), (slice(1, None), slice(None))
def _jump(z1: np.ndarray, z2: np.ndarray, parameters: GeometryParameters) -> np.ndarray: # Inputs have invalid z replaced by zero by callers, avoiding NaN/Inf math. return np.abs(z1 - z2) > ( parameters.depth_jump_abs_m + parameters.depth_jump_rel * np.minimum(z1, z2) )
def estimate_surface_normals( geometry: OrganizedGeometry, object_id: int, parameters: GeometryParameters,) -> tuple[np.ndarray, np.ndarray]: """Central cross product from a full, same-object 5-pixel (+) stencil.
Centre and four neighbours must have unambiguous valid depth, and none of the four centre-to-neighbour pairs may exceed the z-jump gate. No one-sided fallback or extrapolation is performed at holes, mask/image borders, or tiny fragments. Unit normals point towards the camera (n dot XYZ <= 0). """ xyz = geometry.xyz normals = np.full_like(xyz, np.nan) normal_valid = np.zeros(geometry.valid_depth.shape, dtype=bool) if min(normal_valid.shape) < 3: return normals, normal_valid support = geometry.observed_mask(object_id) centre = (slice(1, -1), slice(1, -1)) neighbours = ((slice(1, -1), slice(None, -2)), (slice(1, -1), slice(2, None)), (slice(None, -2), slice(1, -1)), (slice(2, None), slice(1, -1))) usable = support[centre].copy() z = np.where(geometry.valid_depth, xyz[..., 2], 0) for neighbour in neighbours: usable &= support[neighbour] & ~_jump(z[centre], z[neighbour], parameters) # Compute only complete stencils, so invalid XYZ never enters a cross product. v, u = np.nonzero(usable) v, u = v + 1, u + 1 dx = xyz[v, u + 1].astype(np.float64) - xyz[v, u - 1] dy = xyz[v + 1, u].astype(np.float64) - xyz[v - 1, u] cross = np.cross(dx, dy) length = np.linalg.norm(cross, axis=1) good = np.isfinite(length) & (length > 0) v, u, cross = v[good], u[good], cross[good] / length[good, None] cross[np.einsum("ij,ij->i", cross, xyz[v, u]) > 0] *= -1 normals[v, u] = cross.astype(np.float32) normal_valid[v, u] = True return normals, normal_valid
def compute_geometric_features( geometry: OrganizedGeometry, object_id: int, normals: np.ndarray, normal_valid: np.ndarray, parameters: GeometryParameters,) -> GeometricFeatures: """Measure separate 4-neighbour boundary causes and local normal variation.""" mask = geometry.object_masks[object_id] support = geometry.observed_mask(object_id) shape = mask.shape z = np.where(geometry.valid_depth, geometry.xyz[..., 2], 0) jump_m = np.zeros(shape, np.float32) pair_valid = np.zeros(shape, bool) discontinuity = np.zeros(shape, bool) mask_boundary = np.zeros(shape, bool) validity_boundary = np.zeros(shape, bool) variation = np.zeros(shape, np.float32) count = np.zeros(shape, np.uint8) for a, b in _pairs(): both_depth = geometry.valid_depth[a] & geometry.valid_depth[b] dz = np.abs(z[a] - z[b]) jumps = both_depth & _jump(z[a], z[b], parameters) both_normals = normal_valid[a] & normal_valid[b] angle = np.zeros(both_normals.shape, np.float32) n1, n2 = normals[a][both_normals], normals[b][both_normals] # atan2 is stable near zero, including identical rounded float32 normals. angle[both_normals] = np.arctan2( np.linalg.norm(np.cross(n1, n2), axis=1), np.einsum("ij,ij->i", n1, n2) ) for p, q in ((a, b), (b, a)): available = support[p] & both_depth pair_valid[p] |= available np.maximum(jump_m[p], np.where(available, dz, 0), out=jump_m[p]) discontinuity[p] |= support[p] & jumps mask_boundary[p] |= mask[p] & ~mask[q] validity_boundary[p] |= support[p] & ~geometry.valid_depth[q] np.maximum(variation[p], angle, out=variation[p]) count[p] += both_normals jump_m[~pair_valid] = np.nan variation_valid = normal_valid & (count > 0) variation[~variation_valid] = np.nan image_boundary = np.zeros(shape, bool) image_boundary[[0, -1], :] = mask[[0, -1], :] image_boundary[:, [0, -1]] = mask[:, [0, -1]] return GeometricFeatures( object_mask=mask, valid_points=support, normals=normals, normal_valid=normal_valid, depth_jump_m=jump_m, depth_pair_valid=pair_valid, depth_discontinuity=discontinuity, mask_boundary=mask_boundary, depth_validity_boundary=validity_boundary, image_boundary=image_boundary, normal_variation_rad=variation, normal_variation_valid=variation_valid, normal_neighbor_count=count, )
def process_geometry( frame: TrackedRGBDFrame, parameters: GeometryParameters | None = None,) -> GeometryFrame: """Process one current observation; no cache, final classification, or RGB features.""" parameters = parameters or GeometryParameters() start = perf_counter() geometry = build_organized_geometry(frame) after_geometry = perf_counter() normals = {object_id: estimate_surface_normals(geometry, object_id, parameters) for object_id in geometry.object_masks} after_normals = perf_counter() features = {object_id: compute_geometric_features( geometry, object_id, *normals[object_id], parameters, ) for object_id in geometry.object_masks} end = perf_counter() timings = dict(geometry=(after_geometry - start) * 1000, normals=(after_normals - after_geometry) * 1000, discontinuity_features=(end - after_normals) * 1000, total=(end - start) * 1000) return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timings)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445"""Evaluate saved tracker masks against GT and write a report plus depth video.
Run from the repository root::
WANDB_MODE=disabled .venv/bin/python visual/runtime/test/run_rgbd.py \ --input visual/data/step2/ep000.npz \ --masks visual/results/runtime_tracking/ep000/masks.npz
GT is read only here, after Visual output has been produced by rgbd.py."""
from __future__ import annotations
import argparseimport base64import hashlibimport htmlimport iofrom itertools import chainimport jsonfrom pathlib import Pathimport sys
import cv2import imageio.v2 as imageioimport numpy as npfrom scipy.spatial import cKDTree
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))
from utils.experiment_logger import ExperimentLogger # noqa: E402from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFrame, iter_saved_rgbd # noqa: E402from visual.scripts.pointcloud import backproject, to_world # noqa: E402
OBJECTS = {"peg": PEG, "box": BOX}COLORS = {"peg": (255, 100, 90), "box": (60, 205, 255)} # RGB
def compare_object(frame: TrackedRGBDFrame, object_id: int, gt_mask: np.ndarray) -> dict: """Compare masks and unfiltered visible surfaces; distances are in mm.
Geometry uses every pixel with finite positive depth, with no erosion, sampling, or pose fitting. Missing surfaces yield None, never zero error. """ predicted = frame.masks[object_id] if gt_mask.shape != frame.depth.shape or gt_mask.dtype != np.bool_: raise ValueError("GT mask must be boolean and match the depth resolution") predicted_pixels, gt_pixels = int(predicted.sum()), int(gt_mask.sum()) tp = int(np.count_nonzero(predicted & gt_mask)) union = predicted_pixels + gt_pixels - tp valid_depth = np.isfinite(frame.depth) & (frame.depth > 0) predicted_valid = predicted & valid_depth gt_valid = gt_mask & valid_depth row = dict( predicted_pixels=predicted_pixels, gt_pixels=gt_pixels, tp=tp, fp=predicted_pixels - tp, fn=gt_pixels - tp, iou=tp / union if union else None, precision=tp / predicted_pixels if predicted_pixels else None, recall=tp / gt_pixels if gt_pixels else None, predicted_depth_pixels=int(predicted_valid.sum()), gt_depth_pixels=int(gt_valid.sum()), predicted_valid_depth_fraction=float(predicted_valid.sum() / predicted_pixels) if predicted_pixels else None, median_depth_m=float(np.median(frame.depth[predicted_valid])) if predicted_valid.any() else None, centroid_error_mm=None, chamfer_mm=None, predicted_to_gt_mm=None, gt_to_predicted_mm=None, ) if predicted_valid.any() and gt_valid.any(): predicted_world = to_world( backproject(frame.depth, frame.intrinsic, predicted_valid), frame.cam2world ) gt_world = to_world( backproject(frame.depth, frame.intrinsic, gt_valid), frame.cam2world ) predicted_distance = cKDTree(gt_world).query(predicted_world)[0] gt_distance = cKDTree(predicted_world).query(gt_world)[0] row.update( centroid_error_mm=float(np.linalg.norm( predicted_world.mean(axis=0, dtype=np.float64) - gt_world.mean(axis=0, dtype=np.float64) ) * 1000), predicted_to_gt_mm=float(predicted_distance.mean() * 1000), gt_to_predicted_mm=float(gt_distance.mean() * 1000), chamfer_mm=float((predicted_distance.mean() + gt_distance.mean()) * 500), ) return row
def statistics(values) -> dict: values = np.asarray([value for value in values if value is not None], dtype=np.float64) if not len(values): return dict(count=0, mean=None, median=None, p95=None) return dict(count=len(values), mean=float(values.mean()), median=float(np.median(values)), p95=float(np.percentile(values, 95)))
def summarize(records: list[dict]) -> dict: summary = {} for name in OBJECTS: rows = [record["objects"][name] for record in records] tp, fp, fn = (sum(row[key] for row in rows) for key in ("tp", "fp", "fn")) visible = [row for row in rows if row["gt_pixels"] > 0] summary[name] = dict( frames=len(rows), visible_frames=len(visible), missed_visible_frames=sum(row["predicted_pixels"] == 0 for row in visible), invisible_frames=len(rows) - len(visible), false_positive_invisible_frames=sum( row["gt_pixels"] == 0 and row["predicted_pixels"] > 0 for row in rows ), geometry_unavailable_visible_frames=sum(row["chamfer_mm"] is None for row in visible), tp=tp, fp=fp, fn=fn, micro_iou=tp / (tp + fp + fn) if tp + fp + fn else None, micro_precision=tp / (tp + fp) if tp + fp else None, micro_recall=tp / (tp + fn) if tp + fn else None, visible_iou=statistics(row["iou"] for row in visible), centroid_error_mm=statistics(row["centroid_error_mm"] for row in rows), chamfer_mm=statistics(row["chamfer_mm"] for row in rows), predicted_to_gt_mm=statistics(row["predicted_to_gt_mm"] for row in rows), gt_to_predicted_mm=statistics(row["gt_to_predicted_mm"] for row in rows), ) return summary
def depth_colors(depth: np.ndarray, near: float, far: float) -> np.ndarray: """Fixed metre scale for the whole video; invalid depth is black.""" if not np.isfinite([near, far]).all() or not 0 <= near < far: raise ValueError("depth range must be finite and satisfy 0 <= near < far") valid = np.isfinite(depth) & (depth > 0) scaled = np.zeros(depth.shape, dtype=np.float32) scaled[valid] = np.clip((depth[valid] - near) / (far - near), 0, 1) colored = cv2.cvtColor( cv2.applyColorMap(np.rint(scaled * 255).astype(np.uint8), cv2.COLORMAP_TURBO), cv2.COLOR_BGR2RGB, ) colored[~valid] = 0 return colored
def _text(image, text, xy, scale=0.55, color=(235, 240, 245)): cv2.putText(image, text, xy, cv2.FONT_HERSHEY_SIMPLEX, scale, color, 1, cv2.LINE_AA)
def _outline(image, mask, color, thickness=1): contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(image, contours, -1, color, thickness)
def _number(value, decimals=2): return "n/a" if value is None else f"{value:.{decimals}f}"
def render_depth_frame(frame: TrackedRGBDFrame, gt_masks: dict[str, np.ndarray], metrics: dict, near: float, far: float) -> np.ndarray: """RGB tracking, RGB with depth overlay, and isolated object depth panels.""" colored = depth_colors(frame.depth, near, far) valid = np.isfinite(frame.depth) & (frame.depth > 0) rgb = frame.rgb.copy() overlay = frame.rgb.copy() overlay[valid] = (0.3 * overlay[valid] + 0.7 * colored[valid]).astype(np.uint8) union = frame.masks[PEG] | frame.masks[BOX] isolated = colored.copy() isolated[~union] = 0 for name, object_id in OBJECTS.items(): _outline(rgb, gt_masks[name], (255, 255, 255), 1) _outline(rgb, frame.masks[object_id], COLORS[name], 2) _outline(overlay, frame.masks[object_id], COLORS[name], 2) _outline(isolated, frame.masks[object_id], COLORS[name], 1)
# Keep labels readable for lower-resolution inputs too. panel_width = max(384, frame.rgb.shape[1]) panel_width += panel_width % 2 # H.264 yuv420 needs an even canvas width. panel_height = round(frame.rgb.shape[0] * panel_width / frame.rgb.shape[1]) panel_height += panel_height % 2 header, footer = 64, 144 canvas = np.full((header + panel_height + footer, panel_width * 3, 3), (18, 23, 32), dtype=np.uint8) titles = ("RGB | predicted masks + white GT", "RGB + depth overlay", "Tracked-object depth") for column, (panel, title) in enumerate(zip((rgb, overlay, isolated), titles)): x = column * panel_width canvas[header:header + panel_height, x:x + panel_width] = cv2.resize( panel, (panel_width, panel_height), interpolation=cv2.INTER_NEAREST ) _text(canvas, title, (x + 12, 23), 0.55) timing = f"source row {frame.source_frame} | step {frame.frame_idx} | t={_number(frame.timestamp, 3)}s | {frame.camera}" _text(canvas, timing, (12, 49), 0.5) top = header + panel_height for line, name in enumerate(OBJECTS): row = metrics[name] label = (f"{name.upper()} | IoU {_number(row['iou'], 3)}" f" | Chamfer {_number(row['chamfer_mm'])} mm" f" | centroid {_number(row['centroid_error_mm'])} mm" f" | median z {_number(row['median_depth_m'], 3)} m") _text(canvas, label, (12, top + 23 + 24 * line), 0.55, COLORS[name]) bar_width = panel_width - 32 gradient = np.linspace(near, far, bar_width, dtype=np.float32)[None, :] canvas[top + 66:top + 82, 16:16 + bar_width] = depth_colors( np.repeat(gradient, 16, axis=0), near, far ) _text(canvas, f"{near:.2f} m", (16, top + 104), 0.5) _text(canvas, f"{far:.2f} m", (bar_width - 38, top + 104), 0.5) _text(canvas, "Fixed CV camera z scale | black = invalid / unselected", (panel_width + 12, top + 80), 0.5) _text(canvas, "Colors clip at scale limits; metric calculations use all finite positive depths.", (panel_width + 12, top + 103), 0.46) _text(canvas, "Surface differences use the same recorded depth; no independent depth prediction is evaluated.", (12, top + 130), 0.5) return canvas
def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def write_report(path: Path, data: dict) -> None: """Write one portable HTML containing numerical tables, plots, and raw data.""" import matplotlib.pyplot as plt
records, summary = data["frames"], data["summary"] figure, axes = plt.subplots(2, 1, figsize=(11, 5.5), sharex=True, layout="constrained") steps = [row["source_frame"] for row in records] for name in OBJECTS: color = np.asarray(COLORS[name]) / 255 for axis, key in zip(axes, ("iou", "chamfer_mm")): values = [row["objects"][name][key] for row in records] axis.plot(steps, [np.nan if value is None else value for value in values], label=name, color=color, linewidth=1.5) axis.grid(alpha=0.2) axes[0].set(ylabel="Mask IoU", ylim=(-0.03, 1.03)) axes[1].set(ylabel="Visible-surface Chamfer (mm)", xlabel="Source episode row") axes[0].legend() chart = io.BytesIO() figure.savefig(chart, format="png", dpi=140) plt.close(figure) encoded_chart = base64.b64encode(chart.getvalue()).decode("ascii")
rows = [] for name, values in summary.items(): rows.append("<tr>" + "".join(f"<td>{value}</td>" for value in ( name, f"{values['visible_frames']} / {values['frames']}", _number(values["visible_iou"]["mean"], 4), _number(values["micro_iou"], 4), _number(values["micro_precision"], 4), _number(values["micro_recall"], 4), _number(values["centroid_error_mm"]["mean"]), _number(values["chamfer_mm"]["mean"]), _number(values["chamfer_mm"]["p95"]), values["chamfer_mm"]["count"], values["geometry_unavailable_visible_frames"], values["missed_visible_frames"], values["false_positive_invisible_frames"], )) + "</tr>")
frame_rows = [] for record in records: for name, values in record["objects"].items(): columns = (record["source_frame"], record["frame_idx"], name, values["gt_pixels"], values["predicted_pixels"], _number(values["iou"], 4), _number(values["precision"], 4), _number(values["recall"], 4), values["predicted_depth_pixels"], values["gt_depth_pixels"], _number(values["predicted_valid_depth_fraction"], 4), _number(values["median_depth_m"], 4), _number(values["centroid_error_mm"]), _number(values["chamfer_mm"]), _number(values["predicted_to_gt_mm"]), _number(values["gt_to_predicted_mm"])) frame_rows.append("<tr>" + "".join(f"<td>{value}</td>" for value in columns) + "</tr>")
def table(headers, content): return ("<div class='scroll'><table><thead><tr>" + "".join(f"<th>{header}</th>" for header in headers) + "</tr></thead><tbody>" + "".join(content) + "</tbody></table></div>")
totals = table(("Object", "GT visible / total", "Mean visible IoU", "Micro IoU", "Precision", "Recall", "Mean centroid mm", "Mean Chamfer mm", "p95 Chamfer mm", "3D frames", "Visible, no 3D", "Missed visible", "False positive invisible"), rows) per_frame = table(("Source row", "Step", "Object", "GT px", "Pred px", "IoU", "Precision", "Recall", "Pred depth px", "GT depth px", "Pred valid depth fraction", "Median z m", "Centroid mm", "Chamfer mm", "Pred→GT mm", "GT→pred mm"), frame_rows) # Escaping < also makes the embedded JSON safe when paths contain markup. raw_data = json.dumps(data, allow_nan=False, indent=2).replace("<", "\\u003c") details = html.escape(json.dumps({key: value for key, value in data.items() if key not in ("summary", "frames")}, indent=2)) document = f"""<!doctype html><html lang="ko"><meta charset="utf-8"><title>Visual RGB-D · GT 비교</title><style>body{{font:15px/1.6 system-ui,sans-serif;margin:32px auto;padding:0 24px;max-width:1400px;color:#202a38;background:#f6f8fb}}h1,h2{{line-height:1.25}} .scroll{{overflow:auto;background:white;border:1px solid #dde3ed;border-radius:8px}}table{{border-collapse:collapse;white-space:nowrap;width:100%;font-variant-numeric:tabular-nums}}td,th{{padding:9px 12px;text-align:right;border-bottom:1px solid #e5e9ef}}th{{background:#eaf0f8}}td:first-child,th:first-child{{text-align:left}}img{{max-width:100%;background:white;border-radius:8px}}code,pre{{background:#eaf0f8;padding:2px 5px;border-radius:4px}}pre{{overflow:auto;padding:16px}}details{{margin:20px 0}}.note{{padding:14px 18px;background:#e8eff9;border-left:4px solid #466eb9}}</style><h1>Visual RGB-D · GT 비교</h1><p>{len(records)} frames · {html.escape(data['camera'])} · run <code>{data['run_id']}</code></p><p><a href="depth.mp4">Depth 시각화 영상 (MP4)</a> · 원본 row {steps[0]}–{steps[-1]} · {data['video_fps']:.3f} fps</p><p class="note">예측 mask와 simulator GT segmentation을 비교합니다. 3D 오차는 각 mask를<strong>같은 기록 depth</strong>로 역투영한 가시 표면 간 거리이며, depth 센서 정확도나물체 pose 추정 오차를 의미하지 않습니다. 카메라 calibration과 TCP pose는 기록된 입력입니다.</p><h2>물체별 수치</h2>{totals}<h2>프레임별 변화</h2><img alt="Mask IoU and surface distance by source frame" src="data:image/png;base64,{encoded_chart}"><h2>지표 정의와 분모</h2><ul><li>GT visible: GT mask가 1 pixel 이상인 프레임. Mean visible IoU는 모든 visible 프레임의 평균이며 미검출은 0입니다.</li><li>Micro IoU / Precision / Recall: 전체 프레임의 TP·FP·FN을 합산해 계산합니다. GT가 없는 프레임의 오검출도 FP에 포함합니다.</li><li>GT와 예측이 모두 빈 mask이면 프레임 IoU는 n/a입니다. Precision·Recall도 해당 분모가 0이면 n/a입니다.</li><li>역투영: CV pixel centre (u+0.5, v+0.5), finite depth > 0, metre 단위. 기존 Visual backproject / to_world 함수를 재사용합니다.</li><li>Centroid: 예측·GT 가시 표면 centroid 간 Euclidean 거리(mm). Actor 중심에 대한 pose 오차가 아닙니다.</li><li>Chamfer: 0.5 × (예측→GT 평균 최근접 거리 + GT→예측 평균 최근접 거리), mm. 제곱 거리나 두 방향의 합이 아닙니다.</li><li>3D frames: 양쪽 모두 유효 depth point가 있는 프레임 수. 없는 경우 거리 오차는 n/a이며 평균에 포함하지 않습니다. Visible, no 3D와 Missed visible을 함께 확인해야 합니다.</li><li>3D 거리는 모든 유효 관측점을 사용하며 sampling·erosion·필터링을 하지 않습니다. p95는 프레임별 거리의 95 percentile입니다.</li><li>영상의 depth 범위는 {data['depth_range_m'][0]:.2f}–{data['depth_range_m'][1]:.2f} m로 고정합니다. 범위 밖 색은 clip하지만 수치 평가는 모든 finite positive depth를 사용합니다.</li><li>이 실행은 저장된 관측·mask의 CPU 평가입니다. Simulator와 SAM2 추론, CUDA backend는 실행하지 않습니다.</li></ul><details><summary>프레임별 전체 수치</summary>{per_frame}</details><details><summary>입력 출처·재현 설정</summary><pre>{details}</pre></details><script type="application/json" id="evaluation-data">{raw_data}</script></html>""" path.write_text(document, encoding="utf-8")
def evaluate(episode_path: Path, masks_path: Path, *, camera="base_camera", output_root: Path, near=0.05, far=1.0, fps=None) -> Path: """Produce exactly two primary artifacts in a fresh experiment run directory.""" episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() depth_colors(np.ones((1, 1), dtype=np.float32), near, far) if fps is not None and (not np.isfinite(fps) or fps <= 0): raise ValueError("fps must be finite and positive") with np.load(episode_path, allow_pickle=False) as archive: required = [f"{camera}/seg", "peg_id", "box_id"] missing = [key for key in required if key not in archive] if missing: raise ValueError(f"GT evaluation requires: {', '.join(missing)}") segmentation = archive[f"{camera}/seg"] gt_ids = {name: int(archive[f"{name}_id"].item()) for name in OBJECTS} if gt_ids["peg"] == gt_ids["box"]: raise ValueError("GT peg and box segmentation IDs must be distinct") seed = int(archive["seed"].item()) if "seed" in archive else None timestamps = archive["timestamp"] if "timestamp" in archive else None expected_shape = archive[f"{camera}/depth"].shape if segmentation.shape != expected_shape: raise ValueError("GT segmentation shape must match the episode depth array") with np.load(masks_path, allow_pickle=False) as archive: source = archive["source_frame"] if source.ndim != 1 or not np.issubdtype(source.dtype, np.integer) or not len(source): raise ValueError("source_frame must be a nonempty one-dimensional integer array") if np.any(source < 0) or np.any(source >= len(segmentation)) or np.any(np.diff(source.astype(np.int64)) <= 0): raise ValueError("video source_frame must be in range and strictly increasing") if timestamps is not None: if timestamps.shape != (len(segmentation),): raise ValueError("timestamp shape must match episode frame count") tracked_times = timestamps[source] if not np.isfinite(tracked_times).all() or np.any(np.diff(tracked_times) <= 0): raise ValueError("tracked timestamps must be finite and strictly increasing") else: tracked_times = None if fps is None: if tracked_times is None or len(tracked_times) < 2: raise ValueError("pass --fps when fewer than two tracked timestamps are available") fps = float(1 / np.median(np.diff(tracked_times))) fps_source = "inverse median tracked timestamp gap" else: fps_source = "explicit override"
metadata_path = masks_path.with_name("tracking.json") provenance = {} if metadata_path.is_file(): recorded = json.loads(metadata_path.read_text(encoding="utf-8")) if recorded.get("camera") not in (None, camera): raise ValueError("camera differs from the mask runner's tracking.json") recorded_input = recorded.get("input") if recorded_input and Path(recorded_input).is_file() and Path(recorded_input).resolve() != episode_path: if _sha256(Path(recorded_input)) != _sha256(episode_path): raise ValueError("episode differs from the mask runner's tracking.json") provenance = {key: recorded.get(key) for key in ("input", "camera", "device", "config", "checkpoint", "stride")} iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) first = next(iterator) # Validate the Visual observation boundary before creating outputs. config = dict(input=str(episode_path), masks=str(masks_path), camera=camera, depth_range_m=[near, far], video_fps=fps, fps_source=fps_source, input_sha256=_sha256(episode_path), masks_sha256=_sha256(masks_path), output_root=str(Path(output_root).resolve()), gt_segmentation_ids=gt_ids, output_object_ids=OBJECTS, tracker=provenance, geometry="all finite-positive-depth pixels, no sampling or filters") with ExperimentLogger(team="visual", config=config, seed=seed, model="saved_sam2_rgbd", job_type="evaluate") as experiment: output = Path(output_root).resolve() / experiment.run_id output.mkdir(parents=True, exist_ok=False) video_path = output / "depth.mp4" records = [] with imageio.get_writer(video_path, fps=fps, codec="libx264", macro_block_size=1, ffmpeg_params=["-crf", "18"]) as writer: for frame in chain((first,), iterator): gt_masks = {name: segmentation[frame.source_frame] == gt_ids[name] for name in OBJECTS} metrics = {name: compare_object(frame, object_id, gt_masks[name]) for name, object_id in OBJECTS.items()} record = dict(source_frame=frame.source_frame, frame_idx=frame.frame_idx, timestamp=frame.timestamp, objects=metrics) records.append(record) writer.append_data(render_depth_frame(frame, gt_masks, metrics, near, far)) if len(records) == 1 or len(records) % 20 == 0: print(f"evaluated {len(records)}/{len(source)} frames", flush=True) experiment.link_output(video_path, kind="rollouts") summary = summarize(records) report_path = output / "gt_report.html" data = dict(run_id=experiment.run_id, seed=seed, evaluation_device="cpu", git_commit=experiment.metadata.get("git_commit"), git_dirty=experiment.metadata.get("git_dirty"), **config, summary=summary, frames=records) write_report(report_path, data) experiment.link_output(report_path, kind="reports") experiment.log(summary, prefix="eval/rgbd") experiment.record(dataset_sha256=config["input_sha256"], masks_sha256=config["masks_sha256"], evaluated_frames=len(records), evaluation_device="cpu") return output
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True, help="Original recorded episode NPZ") parser.add_argument("--masks", type=Path, required=True, help="Runtime masks.npz") parser.add_argument("--camera", default="base_camera") parser.add_argument("--out", type=Path, default=REPO / "visual/results/runtime_rgbd", help="Output root; creates a fresh <run_id> subdirectory") parser.add_argument("--depth-min", type=float, default=0.05, help="Fixed video depth scale, metres") parser.add_argument("--depth-max", type=float, default=1.0, help="Fixed video depth scale, metres") parser.add_argument("--fps", type=float, default=None, help="Override median timestamp-gap playback fps") args = parser.parse_args() try: output = evaluate(args.input, args.masks, camera=args.camera, output_root=args.out, near=args.depth_min, far=args.depth_max, fps=args.fps) except (ValueError, KeyError, FileNotFoundError) as exc: parser.error(str(exc)) print(f"saved GT report: {output / 'gt_report.html'}") print(f"saved depth video: {output / 'depth.mp4'}")
if __name__ == "__main__": main()12"""Compatibility imports for the original Task 02-B experiments."""from visual.runtime.normal_estimators import METHODS, finite_difference, local_plane, _assign, _empty, _jump123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Grounding DINO inference for runtime visual pipelines.
Example::
detector = GDino() boxes, scores = detector(rgb, "red and white block")
``rgb`` is an H x W x 3 uint8 RGB image. ``boxes`` are pixel-coordinate``[x1, y1, x2, y2]`` boxes ordered by descending score."""
from __future__ import annotations
import time
import numpy as npfrom PIL import Image
GDINO_ID = "IDEA-Research/grounding-dino-tiny"CAND_THR = 0.1
class GDino: """Load Grounding DINO once, then detect prompted objects in RGB images.
Args: device: Torch device used for inference. Defaults to ``"cuda"`` to match the existing Visual pipeline. model_id: Hugging Face model identifier or local model directory. threshold: Box and text threshold passed to Transformers postprocessing. """
def __init__(self, device: str = "cuda", model_id: str = GDINO_ID, threshold: float = CAND_THR): import torch from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
self._torch = torch self.device = device self.threshold = threshold self.proc = AutoProcessor.from_pretrained(model_id) self.model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device).eval() self.last_ms = {"pre": 0.0, "forward": 0.0, "post": 0.0}
def _synchronize(self) -> None: if self.device.startswith("cuda") and self._torch.cuda.is_available(): self._torch.cuda.synchronize(self.device)
def __call__(self, rgb: np.ndarray, prompt: str) -> tuple[list[list[float]], list[float]]: """Return score-sorted pixel boxes and scores for one text prompt.""" image = Image.fromarray(np.asarray(rgb, dtype=np.uint8))
t0 = time.perf_counter() inputs = self.proc( images=image, text=prompt.lower().strip() + ".", return_tensors="pt", ).to(self.device) self._synchronize() t1 = time.perf_counter()
with self._torch.inference_mode(): outputs = self.model(**inputs) self._synchronize() t2 = time.perf_counter()
detections = self.proc.post_process_grounded_object_detection( outputs, inputs.input_ids, threshold=self.threshold, text_threshold=self.threshold, target_sizes=[image.size[::-1]], )[0] boxes = detections["boxes"].detach().cpu().numpy() scores = detections["scores"].detach().cpu().numpy() self.last_ms = { "pre": (t1 - t0) * 1000, "forward": (t2 - t1) * 1000, "post": (time.perf_counter() - t2) * 1000, }
order = np.argsort(-scores) return boxes[order].tolist(), scores[order].tolist()
# Keep the descriptive spelling available to new callers while preserving the# short class name used in the existing Visual scripts.GroundingDINO = GDino
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585# Task03-G — Geometry-Aware Structural Sampling, Phase 1 Feasibility
Frame0 결과: Peg C→P p95는 6.662→5.664mm로 개선됐고 Box는 29.779→30.710mm로 악화됐다. X→F Surface mean/p95는 두 물체에서 소폭 개선됐지만 Final GT reference는 Peg 160→149, Box 12→9로 줄었다. Fallback은 양쪽 0점이며, 관측 patch의 유용성은 제한적이다. 일반화 성공이나 정책 채택을 주장하지 않는다.
수치 선택 UUID는 2c3d733de35c4532b2b81a0a751b7ebf다. 해당 실행은 수치·문서 생성 후 최종 artifact 등록에서 종료 후 전용 API를 실행 중 호출해 failed로 남았다. 이번 보고 UUID는 저장 수치 NPZ와 pre-GT 선택을 byte-identical 복사한 문서 후처리이며 새 FPS/평가 실행은 0회다. 실패 실행과 모든 원본 산출물은 보존했다.
## 결과 범위와 재현 정보
새 ExperimentLogger UUID: 495a67210c5c4cbfab91d013239f7ce9. ep000 Frame 0 / base_camera / S3(PCA5), N=256, structural_ratio=.25, threshold=20°, seed=0. Peg P/F=32/129, Box P/F=32/127. CPU NumPy/SciPy offline 실행만 수행했다. 일반화 알고리즘 채택 근거가 아닌 관측 patch 단위의 첫 feasibility 실험이다.
주 비교는 Task03-E 7f657cf88baf4f1f89e594252e243e1c 저장 Global λ=0이다. Task03 2551448b0fae4c6bbce3caf48774275f Global λ=1과 Task03-F 1f7ad262dd2e4b2fb0ac805a4eda5278 UV는 참고 비교다. F 최종 UUID는 기존 수치 실행의 문서 후처리이며 독립 반복 실험으로 세지 않는다.
선택 규칙은 same-object X의 right/down pair를 기존 4-neighbour 무방향 연결로 복원하고, 양 끝 support·overlap 없음·depth_jump=False·finite angle≤20°로 고정했다. C의 각 source는 정확히 하나의 X patch에 귀속한다. C-free patch도 X와 Surface에서 보존한다. Weight는 C bbox의 3D 대각선이다. 전체 C의 seeded anchor 1점을 보존한 뒤 남은 31점을 capacity-capped largest remainder로 배분하고, patch 내부 원본 3D FPS와 전체 X의 Surface FPS를 사용한다.
## Evidence compatibility 관문
Task01 dense XYZ·validity·mask·overlap·camera·intrinsic·cam2world와 E의 C/X, Task02-C pair source/index/support를 대조했다. Right pair는 같은 행의 +1, down은 +width이며 각 pair는 한 번만 저장된다. Depth jump는 두 depth가 유효할 때 |z₂−z₁| > .01 + .02×min(z₁,z₂)이다. Equality는 jump가 아니다. Normal orientation 후보는 >20°, patch 연결은 finite ≤20°다. NaN angle은 연결하지 않는다. Normal-invalid X는 삭제하지 않는다.
| object | pairs | right | down | candidate/support/threshold | optimized pair identity || --- | --- | --- | --- | --- | --- || peg | 23876 | 11964 | 11912 | PASS | N/A || box | 23645 | 11835 | 11810 | PASS | N/A |
Reference PCA5 pair angle은 저장 Task02-B normal에서 직접 재계산해 exact equality를 확인했다. 저장 orientation endpoint 및 normal variation의 >20° membership은 Task03 optimized PCA5의 저장 C와 일치했고, 저장 선택 행의 validity/candidate membership도 일치했다. 하지만 optimized PCA5 전체 pair angle은 저장되지 않았다. Candidate endpoint 집합의 일치가 low-angle pair별 연결 gate의 일치를 보장하지 않는다. 따라서 이번 patch는 Task02-C reference PCA5 evidence에서 구성했고 optimized PCA5와 bit-exact라고 주장하지 않는다. Normal estimator/candidate detector는 재실행하지 않았다.
## 선택 전 patch 분절과 allocation
아래 patch ID는 GT-free 관측상 매끄럽게 연결된 표면 성분이다. Structural edge, physical component, 평가용 seam/rim label 또는 최종 graph edge를 뜻하지 않는다. Weight=0인 후보 patch에는 anchor 외 minimum quota가 없다. 실패를 보정하기 위한 병합·gate 변경·후보 삭제는 하지 않았다.
| object | X patches | C patches | X singleton | 0-span C patches | 0-span candidates / C | quota=0 C patches | quota=0 candidates | anchor patch/quota | fallback || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || peg | 20 | 12 | 19 | 11 | 11 / 703 (1.565%) | 11 | 11 | 0 / 32 | 0 || box | 105 | 30 | 87 | 15 | 15 / 599 (2.504%) | 21 | 43 | 52 / 1 | 0 |
peg: singleton 또는 candidate 0-span patch 19개, 그 안의 후보 11개 (1.565%). Candidate가 1개인 patch 11개, X singleton에 속한 후보 11개. 실제 fallback=0점.
box: singleton 또는 candidate 0-span patch 88개, 그 안의 후보 15개 (2.504%). Candidate가 1개인 patch 15개, X singleton에 속한 후보 14개. 실제 fallback=0점.
peg 전체 X patch (C=0 포함): span은 bbox proxy이며 구조 길이가 아니다. Capacity는 전체 C 수, additional은 anchor 제외 배분이다.
| patch | min source | X | C/capacity | X span m | C span/weight m | anchor | additional | quota | actual P | fallback P || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || 0 | 146191 | 11761 | 692 | 0.259619 | 0.243348 | 1 | 31 | 32 | 32 | 0 || 1 | 168678 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 2 | 186567 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 3 | 186623 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 4 | 187134 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 5 | 191167 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 6 | 192760 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 7 | 195317 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 8 | 201454 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 9 | 204968 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 10 | 212137 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 11 | 213216 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 12 | 213728 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 13 | 215262 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 14 | 215722 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 15 | 215773 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 16 | 216234 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 17 | 216284 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 18 | 219307 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 19 | 219819 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
box 전체 X patch (C=0 포함): span은 bbox proxy이며 구조 길이가 아니다. Capacity는 전체 C 수, additional은 anchor 제외 배분이다.
| patch | min source | X | C/capacity | X span m | C span/weight m | anchor | additional | quota | actual P | fallback P || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || 0 | 83165 | 11112 | 399 | 0.389164 | 0.326477 | 0 | 15 | 15 | 15 | 0 || 1 | 84271 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 2 | 84285 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 3 | 84698 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 4 | 84783 | 7 | 5 | 0.0135329 | 0.0135329 | 0 | 1 | 1 | 1 | 0 || 5 | 84796 | 10 | 0 | 0.00471966 | 0 | 0 | 0 | 0 | 0 | 0 || 6 | 85210 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 7 | 85722 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 8 | 86234 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 9 | 86746 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 10 | 87254 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 11 | 87356 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 12 | 87765 | 7 | 3 | 0.0170659 | 0.00605605 | 0 | 0 | 0 | 0 | 0 || 13 | 87858 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 14 | 88273 | 14 | 0 | 0.0071225 | 0 | 0 | 0 | 0 | 0 | 0 || 15 | 88369 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 16 | 88379 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 17 | 88881 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 18 | 89304 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 19 | 89392 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 20 | 89393 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 21 | 89817 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 22 | 89904 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 23 | 89913 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 24 | 90329 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 25 | 90841 | 3 | 2 | 0.00848839 | 0.00574664 | 0 | 0 | 0 | 0 | 0 || 26 | 90936 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 27 | 91438 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 28 | 91866 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 29 | 91867 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 30 | 91949 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 31 | 92372 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 32 | 92380 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 33 | 92485 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 34 | 92884 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 35 | 92885 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 36 | 92892 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 37 | 93397 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 38 | 93405 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 39 | 93493 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 40 | 93910 | 158 | 54 | 0.0271379 | 0.0255804 | 0 | 1 | 1 | 1 | 0 || 41 | 93917 | 2 | 1 | 0.0103938 | 0 | 0 | 0 | 0 | 0 | 0 || 42 | 93989 | 50 | 27 | 0.0268233 | 0.0268233 | 0 | 1 | 1 | 1 | 0 || 43 | 93990 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 44 | 93991 | 15 | 11 | 0.0136232 | 0.0136232 | 0 | 1 | 1 | 1 | 0 || 45 | 94947 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 46 | 94948 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 47 | 94949 | 40 | 29 | 0.0249794 | 0.0249794 | 0 | 1 | 1 | 1 | 0 || 48 | 95016 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 49 | 95022 | 49 | 14 | 0.0142764 | 0.0136464 | 0 | 1 | 1 | 1 | 0 || 50 | 95459 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 51 | 96051 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 52 | 96553 | 4 | 4 | 0.0034845 | 0.0034845 | 1 | 0 | 1 | 1 | 0 || 53 | 96563 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 54 | 97075 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 55 | 97506 | 3 | 3 | 0.00235313 | 0.00235313 | 0 | 0 | 0 | 0 | 0 || 56 | 97587 | 6 | 5 | 0.00487074 | 0.00481773 | 0 | 0 | 0 | 0 | 0 || 57 | 98601 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 58 | 100146 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 59 | 100650 | 19 | 13 | 0.0111558 | 0.0111558 | 0 | 0 | 0 | 0 | 0 || 60 | 100658 | 2 | 2 | 0.00217214 | 0.00217214 | 0 | 0 | 0 | 0 | 0 || 61 | 101160 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 62 | 101671 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 63 | 101672 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 64 | 101682 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 65 | 102115 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 66 | 102116 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 67 | 104726 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 68 | 105723 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 69 | 105724 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 70 | 105725 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 71 | 105726 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 72 | 105727 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 73 | 105728 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 74 | 105729 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 75 | 105730 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 76 | 105731 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 77 | 105732 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 78 | 105733 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 79 | 105734 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 80 | 106235 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 81 | 106236 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 82 | 106237 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 83 | 106238 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 84 | 106239 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 85 | 106240 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 86 | 106241 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 87 | 106242 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 88 | 106243 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 89 | 106244 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 90 | 106245 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 91 | 106246 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 92 | 106747 | 77 | 13 | 0.214497 | 0.214497 | 0 | 10 | 10 | 10 | 0 || 93 | 110914 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 94 | 111316 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 95 | 111828 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 96 | 112340 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 97 | 117057 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 98 | 119061 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 99 | 120533 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 100 | 121045 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 101 | 129855 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 102 | 130262 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 103 | 135998 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 || 104 | 136510 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |


## Primary — 원본 3D candidate·surface 보존
모든 거리는 변환하지 않은 CV-camera XYZ의 Euclidean 최근접 거리(mm)다. P의 patch 내부 선택 metric과 독립적으로 평가했다. Grouping·span allocation·patch별 초기화·patch 내부 3D와 Global λ=0 metric 차이가 묶여 있다. 아래 차이는 선택 규칙 전체의 차이이며 개별 요소의 인과 효과가 아니다.
| object | method | C→P mean | p50 | p95 | max | X→F mean | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || peg | global0 | 2.94515 | 2.46875 | 6.66215 | 8.19795 | 5.28368 | 8.60946 | 10.8408 || peg | geometry | 2.83494 | 2.66592 | 5.66392 | 6.63788 | 5.1986 | 8.56355 | 11.1341 || peg | global1 | 2.84805 | 2.66592 | 5.66544 | 6.61867 | 5.17004 | 8.54994 | 11.0471 || peg | uv | 3.62105 | 2.89099 | 8.90441 | 15.1258 | 5.27668 | 8.62629 | 11.5683 || box | global0 | 10.8746 | 8.84305 | 29.7788 | 46.0516 | 11.5801 | 19.0768 | 23.1584 || box | geometry | 14.7286 | 13.6098 | 30.7101 | 42.1494 | 11.4499 | 19.0144 | 23.9357 || box | global1 | 12.7793 | 12.5895 | 27.4828 | 32.7114 | 11.2533 | 18.7511 | 22.8926 || box | uv | 10.768 | 7.19952 | 35.0932 | 96.3886 | 11.6761 | 19.5611 | 23.9004 |
| object | Δ mean | Δ p50 | Δ p95 | Δ max | Δ Surface mean | Δ Surface p95 || --- | --- | --- | --- | --- | --- | --- || peg | -0.110212 | 0.197166 | -0.998228 | -1.56007 | -0.0850846 | -0.0459049 || box | 3.85401 | 4.76673 | 0.931283 | -3.90217 | -0.130226 | -0.0623638 |
| object | method | worst source | UV | XYZ m || --- | --- | --- | --- | --- || peg | global0 | 178953 | [265, 349] | [0.008720703423023224, 0.08583007752895355, 0.23499999940395355] || peg | geometry | 191736 | [248, 374] | [-0.006035156082361937, 0.09535546600818634, 0.20600000023841858] || box | global0 | 114427 | [251, 223] | [-0.010265625081956387, -0.07414062321186066, 0.5839999914169312] || box | geometry | 112891 | [251, 220] | [-0.010880859568715096, -0.08583789318799973, 0.6190000176429749] |


## 독립 평가 구역과 후보 밀도
Task03-F의 X bbox 기반 UV 4×4 및 XYZ 최대 2×2×2 경계와 helper를 그대로 사용했다. Candidate count, 선택률과 거리 분포를 함께 본다. Box X의 30.726m depth outlier 때문에 XYZ grid의 후보가 한 구역에 들어가는 한계를 보정하지 않았다. 전체 분위수는 후보 밀도의 영향을 받으며 구역 동등 가중 p95도 함께 기록한다. XYZ 공간 밀도의 공통 helper 값은 N/A이며 UV 밀도는 px²당 후보 수다.
| object | method | grid | C occupied | P=0 regions | equal-region mean p95 mm || --- | --- | --- | --- | --- | --- || peg | global0 | uv | 8 | [] | 5.61617 || peg | global0 | xyz | 4 | [6] | 5.81242 || peg | geometry | uv | 8 | [] | 4.95252 || peg | geometry | xyz | 4 | [6] | 5.23625 || box | global0 | uv | 9 | [] | 22.5887 || box | global0 | xyz | 1 | [] | 29.7788 || box | geometry | uv | 9 | [] | 28.2865 || box | geometry | xyz | 1 | [] | 30.7101 |
peg / uv independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 1 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 2 | 98 | 5 | 0.0654069 | 0.0510204 | 1.90722 | 3.87439 | 3.9925 || global0 | 3 | 11 | 2 | 0.00734159 | 0.181818 | 1.8892 | 3.94895 | 4.1479 || global0 | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 5 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 6 | 125 | 4 | 0.0834272 | 0.032 | 2.75116 | 6.01855 | 7.0785 || global0 | 7 | 149 | 7 | 0.0994452 | 0.0469799 | 1.93745 | 3.28836 | 4.08921 || global0 | 8 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 9 | 94 | 4 | 0.0627372 | 0.0425532 | 3.88951 | 7.11593 | 8.19795 || global0 | 10 | 70 | 1 | 0.0467192 | 0.0142857 | 4.06496 | 7.02078 | 7.44417 || global0 | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 12 | 115 | 8 | 0.076753 | 0.0695652 | 3.69792 | 6.86018 | 8.10343 || global0 | 13 | 41 | 1 | 0.0273641 | 0.0243902 | 3.7745 | 6.80221 | 7.74202 || global0 | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 1 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 2 | 98 | 4 | 0.0654069 | 0.0408163 | 2.29913 | 4.20056 | 4.7016 || geometry | 3 | 11 | 2 | 0.00734159 | 0.181818 | 1.8892 | 3.94895 | 4.1479 || geometry | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 5 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 6 | 125 | 4 | 0.0834272 | 0.032 | 2.49335 | 4.4182 | 5.21059 || geometry | 7 | 149 | 4 | 0.0994452 | 0.0268456 | 3.057 | 5.48384 | 6.09783 || geometry | 8 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 9 | 94 | 3 | 0.0627372 | 0.0319149 | 3.41058 | 6.24105 | 6.63788 || geometry | 10 | 70 | 3 | 0.0467192 | 0.0428571 | 2.13202 | 3.44828 | 3.8646 || geometry | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 12 | 115 | 9 | 0.076753 | 0.0782609 | 3.39673 | 6.18012 | 6.51205 || geometry | 13 | 41 | 3 | 0.0273641 | 0.0731707 | 2.90839 | 5.69918 | 6.51487 || geometry | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A |
peg / xyz independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 2 | 447 | 19 | N/A | 0.0425056 | 2.48632 | 5.90636 | 7.44417 || global0 | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 4 | 141 | 5 | N/A | 0.035461 | 3.82657 | 7.02556 | 8.19795 || global0 | 5 | 109 | 8 | N/A | 0.0733945 | 3.72553 | 6.86357 | 8.10343 || global0 | 6 | 6 | 0 | N/A | 0 | 2.23751 | 3.45418 | 3.53184 || global0 | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 2 | 447 | 17 | N/A | 0.0380313 | 2.56323 | 4.87173 | 6.09783 || geometry | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 4 | 141 | 6 | N/A | 0.0425532 | 3.34643 | 6.18969 | 6.63788 || geometry | 5 | 109 | 9 | N/A | 0.0825688 | 3.29005 | 6.11959 | 6.51205 || geometry | 6 | 6 | 0 | N/A | 0 | 2.78927 | 3.76398 | 3.8646 || geometry | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A |
box / uv independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 66 | 3 | 0.0812808 | 0.0454545 | 10.3462 | 14.7998 | 22.2359 || global0 | 1 | 78 | 3 | 0.0960591 | 0.0384615 | 7.90347 | 13.5986 | 14.6165 || global0 | 2 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 3 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 5 | 50 | 10 | 0.0615764 | 0.2 | 14.7896 | 33.8833 | 38.9934 || global0 | 6 | 100 | 3 | 0.123153 | 0.03 | 13.2174 | 42.8725 | 46.0516 || global0 | 7 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 8 | 22 | 1 | 0.0270936 | 0.0454545 | 9.07644 | 16.6948 | 17.3864 || global0 | 9 | 94 | 2 | 0.115764 | 0.0212766 | 14.4096 | 33.1814 | 44.4893 || global0 | 10 | 98 | 4 | 0.12069 | 0.0408163 | 11.1689 | 25.7114 | 30.9242 || global0 | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 12 | 40 | 3 | 0.0492611 | 0.075 | 4.99843 | 11.5026 | 13.5933 || global0 | 13 | 51 | 3 | 0.0628079 | 0.0588235 | 5.97387 | 11.0541 | 13.0251 || global0 | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || global0 | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 0 | 66 | 3 | 0.0812808 | 0.0454545 | 11.7534 | 31.8331 | 34.0837 || geometry | 1 | 78 | 1 | 0.0960591 | 0.0128205 | 11.488 | 21.2376 | 26.1019 || geometry | 2 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 3 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 4 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 5 | 50 | 14 | 0.0615764 | 0.28 | 14.5807 | 34.0494 | 36.8557 || geometry | 6 | 100 | 2 | 0.123153 | 0.02 | 24.6182 | 30.7025 | 42.1494 || geometry | 7 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 8 | 22 | 1 | 0.0270936 | 0.0454545 | 17.8174 | 34.6258 | 36.0874 || geometry | 9 | 94 | 2 | 0.115764 | 0.0212766 | 15.0542 | 26.7266 | 38.2396 || geometry | 10 | 98 | 3 | 0.12069 | 0.0306122 | 14.6248 | 28.1132 | 30.9242 || geometry | 11 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 12 | 40 | 5 | 0.0492611 | 0.125 | 5.41378 | 30.5286 | 31.4366 || geometry | 13 | 51 | 1 | 0.0628079 | 0.0196078 | 9.86141 | 16.7622 | 19.7643 || geometry | 14 | 0 | 0 | 0 | N/A | N/A | N/A | N/A || geometry | 15 | 0 | 0 | 0 | N/A | N/A | N/A | N/A |
box / xyz independent regions:
| method | region | C | P | C density/px² | P/C | C→P mean mm | p95 | max || --- | --- | --- | --- | --- | --- | --- | --- | --- || global0 | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 2 | 599 | 32 | N/A | 0.0534224 | 10.8746 | 29.7788 | 46.0516 || global0 | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 4 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 5 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 6 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || global0 | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 0 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 1 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 2 | 599 | 32 | N/A | 0.0534224 | 14.7286 | 30.7101 | 42.1494 || geometry | 3 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 4 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 5 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 6 | 0 | 0 | N/A | N/A | N/A | N/A | N/A || geometry | 7 | 0 | 0 | N/A | N/A | N/A | N/A | N/A |

## Secondary — GT 기반 보조 진단
선택 및 selection_before_gt.npz 저장·hash 후 GT reference/pose/ROI를 평가에만 적용했다. 동일 point/reference pair가 2px AND 3mm를 만족해야 한다. Peg GT-visible 464개 중 관측 가능 462개, Box 103개 중 103개가 분모다. Matching node 수와 unique reference 수는 서로 다른 수량이다. 특정 Box rim 선분 개선은 성공 조건이 아니다.
| object | method | stage | nodes | matching nodes | unique refs || --- | --- | --- | --- | --- | --- || peg | global0 | C | 703 | 692 | 462 || peg | global0 | P | 32 | 30 | 160 || peg | global0 | S | 97 | 0 | 0 || peg | global0 | F | 129 | 30 | 160 || peg | geometry | C | 703 | 692 | 462 || peg | geometry | P | 32 | 30 | 149 || peg | geometry | S | 97 | 0 | 0 || peg | geometry | F | 129 | 30 | 149 || peg | global1 | C | 703 | 692 | 462 || peg | global1 | P | 32 | 30 | 151 || peg | global1 | S | 97 | 0 | 0 || peg | global1 | F | 129 | 30 | 151 || peg | uv | C | 703 | 692 | 462 || peg | uv | P | 32 | 31 | 140 || peg | uv | S | 97 | 0 | 0 || peg | uv | F | 129 | 31 | 140 || box | global0 | C | 599 | 127 | 91 || box | global0 | P | 32 | 3 | 9 || box | global0 | S | 95 | 1 | 3 || box | global0 | F | 127 | 4 | 12 || box | geometry | C | 599 | 127 | 91 || box | geometry | P | 32 | 1 | 3 || box | geometry | S | 95 | 2 | 6 || box | geometry | F | 127 | 3 | 9 || box | global1 | C | 599 | 127 | 91 || box | global1 | P | 32 | 1 | 3 || box | global1 | S | 95 | 0 | 0 || box | global1 | F | 127 | 1 | 3 || box | uv | C | 599 | 127 | 91 || box | uv | P | 32 | 1 | 3 || box | uv | S | 95 | 0 | 0 || box | uv | F | 127 | 1 | 3 |
| object | method | P refs | S refs | F refs | S added refs | P/S overlap refs || --- | --- | --- | --- | --- | --- | --- || peg | global0 | 160 | 0 | 160 | 0 | 0 || peg | geometry | 149 | 0 | 149 | 0 | 0 || box | global0 | 9 | 3 | 12 | 3 | 0 || box | geometry | 3 | 6 | 9 | 6 | 0 |
| object | method | stage | GT face-pair/rim segment | observed refs | covered refs | matching nodes || --- | --- | --- | --- | --- | --- | --- || peg | global0 | C | ambiguous | 2 | 2 | 17 || peg | global0 | C | face_0_2 | 91 | 91 | 140 || peg | global0 | C | face_0_5 | 106 | 106 | 154 || peg | global0 | C | face_2_5 | 263 | 263 | 381 || peg | global0 | P | ambiguous | 2 | 1 | 1 || peg | global0 | P | face_0_2 | 91 | 44 | 7 || peg | global0 | P | face_0_5 | 106 | 49 | 7 || peg | global0 | P | face_2_5 | 263 | 66 | 15 || peg | global0 | S | ambiguous | 2 | 0 | 0 || peg | global0 | S | face_0_2 | 91 | 0 | 0 || peg | global0 | S | face_0_5 | 106 | 0 | 0 || peg | global0 | S | face_2_5 | 263 | 0 | 0 || peg | global0 | F | ambiguous | 2 | 1 | 1 || peg | global0 | F | face_0_2 | 91 | 44 | 7 || peg | global0 | F | face_0_5 | 106 | 49 | 7 || peg | global0 | F | face_2_5 | 263 | 66 | 15 || peg | geometry | C | ambiguous | 2 | 2 | 17 || peg | geometry | C | face_0_2 | 91 | 91 | 140 || peg | geometry | C | face_0_5 | 106 | 106 | 154 || peg | geometry | C | face_2_5 | 263 | 263 | 381 || peg | geometry | P | ambiguous | 2 | 2 | 1 || peg | geometry | P | face_0_2 | 91 | 29 | 4 || peg | geometry | P | face_0_5 | 106 | 30 | 5 || peg | geometry | P | face_2_5 | 263 | 88 | 20 || peg | geometry | S | ambiguous | 2 | 0 | 0 || peg | geometry | S | face_0_2 | 91 | 0 | 0 || peg | geometry | S | face_0_5 | 106 | 0 | 0 || peg | geometry | S | face_2_5 | 263 | 0 | 0 || peg | geometry | F | ambiguous | 2 | 2 | 1 || peg | geometry | F | face_0_2 | 91 | 29 | 4 || peg | geometry | F | face_0_5 | 106 | 30 | 5 || peg | geometry | F | face_2_5 | 263 | 88 | 20 || box | global0 | C | rim_axis1_+1 | 25 | 24 | 21 || box | global0 | C | rim_axis1_-1 | 26 | 26 | 43 || box | global0 | C | rim_axis2_+1 | 26 | 15 | 12 || box | global0 | C | rim_axis2_-1 | 26 | 26 | 46 || box | global0 | P | rim_axis1_+1 | 25 | 6 | 2 || box | global0 | P | rim_axis1_-1 | 26 | 0 | 0 || box | global0 | P | rim_axis2_+1 | 26 | 0 | 0 || box | global0 | P | rim_axis2_-1 | 26 | 3 | 1 || box | global0 | S | rim_axis1_+1 | 25 | 0 | 0 || box | global0 | S | rim_axis1_-1 | 26 | 0 | 0 || box | global0 | S | rim_axis2_+1 | 26 | 3 | 1 || box | global0 | S | rim_axis2_-1 | 26 | 0 | 0 || box | global0 | F | rim_axis1_+1 | 25 | 6 | 2 || box | global0 | F | rim_axis1_-1 | 26 | 0 | 0 || box | global0 | F | rim_axis2_+1 | 26 | 3 | 1 || box | global0 | F | rim_axis2_-1 | 26 | 3 | 1 || box | geometry | C | rim_axis1_+1 | 25 | 24 | 21 || box | geometry | C | rim_axis1_-1 | 26 | 26 | 43 || box | geometry | C | rim_axis2_+1 | 26 | 15 | 12 || box | geometry | C | rim_axis2_-1 | 26 | 26 | 46 || box | geometry | P | rim_axis1_+1 | 25 | 3 | 1 || box | geometry | P | rim_axis1_-1 | 26 | 0 | 0 || box | geometry | P | rim_axis2_+1 | 26 | 0 | 0 || box | geometry | P | rim_axis2_-1 | 26 | 0 | 0 || box | geometry | S | rim_axis1_+1 | 25 | 3 | 1 || box | geometry | S | rim_axis1_-1 | 26 | 0 | 0 || box | geometry | S | rim_axis2_+1 | 26 | 0 | 0 || box | geometry | S | rim_axis2_-1 | 26 | 3 | 1 || box | geometry | F | rim_axis1_+1 | 25 | 6 | 2 || box | geometry | F | rim_axis1_-1 | 26 | 0 | 0 || box | geometry | F | rim_axis2_+1 | 26 | 0 | 0 || box | geometry | F | rim_axis2_-1 | 26 | 3 | 1 |
Box의 verified line projection 간격과 missing-reference run은 JSON/NPZ에 기존 helper 정의로 저장했다. Peg face-pair 및 ambiguous reference의 물리적 선분 순서는 N/A다. Array 순서를 곡선 길이나 실제 연속 미보존 길이로 해석하지 않는다.


## 일반 Surface·negative ROI·depth·outlier trade-off
일반 Surface는 전체 X→F로 평가한다. S만 따로 평가하거나 far point를 제거하지 않았다. Known-negative ROI union은 평가용이며 평면 Surface 점유를 자동 오선택이라고 분류하지 않는다. 원본 outlier·depth tail은 그대로 남긴다.
| object | method | negative P / 32 | negative S | negative F | F exact feature rows | unavailable rows || --- | --- | --- | --- | --- | --- | --- || peg | global0 | 2 | 90 | 92 | 26 | 103 || peg | geometry | 2 | 91 | 93 | 97 | 32 || box | global0 | 14 | 61 | 75 | 45 | 82 || box | geometry | 12 | 68 | 80 | 49 | 78 |
| object | method | stage | depth min m | median | p95 | max || --- | --- | --- | --- | --- | --- | --- || peg | global0 | X | 0.166 | 0.206 | 0.32705 | 0.365 || peg | global0 | C | 0.166 | 0.181 | 0.316 | 0.35 || peg | global0 | P | 0.166 | 0.1865 | 0.3325 | 0.35 || peg | global0 | S | 0.176 | 0.266 | 0.3506 | 0.365 || peg | global0 | F | 0.166 | 0.255 | 0.3492 | 0.365 || peg | geometry | X | 0.166 | 0.206 | 0.32705 | 0.365 || peg | geometry | C | 0.166 | 0.181 | 0.316 | 0.35 || peg | geometry | P | 0.166 | 0.197 | 0.33295 | 0.35 || peg | geometry | S | 0.175 | 0.266 | 0.3506 | 0.365 || peg | geometry | F | 0.166 | 0.252 | 0.3492 | 0.365 || box | global0 | X | 0.295 | 0.496 | 0.535 | 30.726 || box | global0 | C | 0.295 | 0.488 | 0.6665 | 1.426 || box | global0 | P | 0.306 | 0.4955 | 1.3864 | 1.426 || box | global0 | S | 0.453 | 0.536 | 8.431 | 30.726 || box | global0 | F | 0.306 | 0.531 | 8.431 | 30.726 || box | geometry | X | 0.295 | 0.496 | 0.535 | 30.726 || box | geometry | C | 0.295 | 0.488 | 0.6665 | 1.426 || box | geometry | P | 0.303 | 0.5525 | 1.40565 | 1.426 || box | geometry | S | 0.306 | 0.523 | 8.431 | 30.726 || box | geometry | F | 0.303 | 0.524 | 8.431 | 30.726 |
Feature는 같은 S3 조건에서 저장된 23개 field의 exact available 행만 compact gather하고 availability mask/positions를 저장했다. Missing feature는 근사 복원하지 않았다. 완전한 production Vision Tensor 검증을 주장하지 않는다.
| object | patch | extreme source | original C span m | span without one point m | drop m | quota || --- | --- | --- | --- | --- | --- | --- || peg | 0 | 148779 | 0.243348 | 0.240427 | 0.0029204 | 32 || peg | 0 | 216283 | 0.243348 | 0.243348 | 0 | 32 || peg | 0 | 221356 | 0.243348 | 0.243348 | 0 | 32 |
| object | patch | extreme source | original C span m | span without one point m | drop m | quota || --- | --- | --- | --- | --- | --- | --- || box | 92 | 109819 | 0.214497 | 0.18542 | 0.0290762 | 10 || box | 4 | 85809 | 0.0135329 | 0.00731415 | 0.00621877 | 1 || box | 25 | 90842 | 0.00574664 | 0 | 0.00574664 | 0 |
각 patch의 C/X bbox min/max XYZ와 C extrema source별 leave-one-out span을 저장했다. 위 표는 한 극단점에 민감한 상위 사례다. 한 점 제거 span은 진단일 뿐 선택에 적용하지 않았다. Bbox span은 실제 구조 길이가 아니며 camera 축과 outlier에 민감하다.

## Synthetic 경계와 fallback 계약
기존 Task03-F 7개 fixture에는 dense X 및 PairEvidence가 없어 새 full-rule performance는 전부 N/A다. 구조 label로 patch를 만들거나 새 detector/normal/fixture를 생성하지 않았다. 기존 Global/UV 결과를 새 방법의 검증 결과로 표시하지 않는다.
| existing fixture | new full-rule performance | reason || --- | --- | --- || line_uniform | N/A | existing sparse C has no dense X or PairEvidence || line_dense | N/A | existing sparse C has no dense X or PairEvidence || separated_clean | N/A | existing sparse C has no dense X or PairEvidence || separated_noise | N/A | existing sparse C has no dense X or PairEvidence || camera_near | N/A | existing sparse C has no dense X or PairEvidence || camera_far | N/A | existing sparse C has no dense X or PairEvidence || camera_occluded | N/A | existing sparse C has no dense X or PairEvidence |
일반 fallback은 현재 C만으로 기존 fps_indices()의 Global λ=0 순서를 만들고 이미 선택된 point를 제외해 부족분을 채운다. 이번 고정 입력에서는 E의 기존 검증과 저장 순서를 재사용할 수 있으며 NPZ는 fallback 규칙의 필수 입력이 아니다. 두 실제 물체의 fallback은 0점이어서 새 결과가 fallback으로 Global FPS를 복제한 경우는 아니다. 작은 synthetic 계약 테스트는 입력 C만으로 fallback을 재현하고 depth/normal veto·분리·0-span·capacity·anchor·정렬·결정성·GT 독립성을 확인한다. 이 테스트는 실제 형상 또는 sensor noise에 대한 일반화 성능 검증이 아니다.
## 완료 판단 — 여섯 질문
1. 실제 C의 분리: Peg는 X patch 20개 중 C patch 12개, Box는 105개 중 30개다. 이는 관측 normal/depth gate로 연결된 표면이지 실제 구조의 독립 분해가 아니다.
2. 3D span quota: peg: patch 0=32; box: patch 0=15, patch 4=1, patch 40=1, patch 42=1, patch 44=1, patch 47=1, patch 49=1, patch 52=1, patch 92=10. Peg의 대부분 C는 하나의 큰 surface patch에 연결되어 독립 구조별 예산을 만들지 못했다. Box는 여러 patch에 배분되었지만 넓은 bbox를 가진 patch에 예산이 집중된다.
3. Global λ=0 대비 3D 보존: peg C→P mean/p95/max 2.945/6.662/8.198→2.835/5.664/6.638mm; X→F mean/p95 5.284/8.609→5.199/8.564mm; box C→P mean/p95/max 10.875/29.779/46.052→14.729/30.710/42.149mm; X→F mean/p95 11.580/19.077→11.450/19.014mm. 손익은 지표별로 해석하며 GT 보존으로 primary 손실을 상쇄하지 않는다.
4. 국소 구조·negative ROI: peg P/F refs 160/160→149/149; negative P/F 2/92→2/93; box P/F refs 9/12→3/9; negative P/F 14/75→12/80. Face-pair/rim 전체 구간과 Surface 추가분·overlap은 위 표에 제시했다. 구간별 개선·손실을 합쳐 특정 Box 선분을 성공 기준으로 삼지 않았다.
5. 제한 요인: Peg/Box의 0-span 후보 11/15개는 span quota를 받지 못하며 quota=0 후보 patch는 11/21개다. Normal 불연속 주변 후보가 작은 patch로 분절되면 중요한 구조라도 quota에서 사라질 수 있는 설계 취약성이다. 실제 fallback은 양쪽 0점이다. Bbox 극단점 민감도와 depth outlier는 제거하지 않았고 span을 구조 길이로 해석하지 않는다.
6. 추가 검증 판단: Frame0에서 관측 patch가 어떻게 분리·배분되는지는 재현 가능하게 설명했지만, Peg의 단일 큰 patch, Box의 fragmentation/zero-quota, reference와 optimized PCA5 pair 차이의 미확���, 7개 full-rule synthetic N/A가 남는다. 현재 결과만으로 일반 geometry preservation 후보의 유용성·안정성을 확립하거나 production 채택을 정당화하지 않는다. 관측 patch의 유용성에는 제한된 근거만 있으며, 독립 관측·형상·camera에서 같은 고정 규칙의 별도 evidence가 필요하다. 이번에는 추가 검증을 시작하지 않는다.
## 검증과 미실행 범위
Ran 93 tests in 0.704s; OK
Source/input/artifact hash 불변, 모든 C의 단일 patch 귀속, quota/capacity, P=32, F=129/127, P⊆C⊆X·F⊆X, pixel/XYZ/object/role 정렬, P/S 중복 없음, NPZ exact readback, saved baseline 평가 exact equality를 확인했다. GT annotation 변경에 따른 전체 선택 불변은 annotation-free 입력/함수 및 작은 full-rule 계약 테스트로 확인하고 실제 선택 전후 archive hash도 유지했다. 실제 Frame0 선택을 GT 변경 후 다시 실행하지 않았다. Optimized pair-level 동일성은 N/A다.
공통 ExperimentLogger와 experiment_artifacts의 digests/register_existing_output 및 link_output 로컬 API를 재사용했다. 실행 소스 snapshot, 시작 dirty diff, 입력 hash, 구현 diff와 tests.log를 새 UUID에 보존했다. Simulator/renderer·GPU/CUDA/MPS/PCL·추가 frame/episode·normal/candidate 재계산·sweep·production·Graph/GNN/BC·외부 업로드·dependency 설치·commit은 실행하지 않았다. Adaptive Budget 결합, Task-Relevance, 다른 grouping과 다음 단계는 시작하지 않고 여기서 종료한다.
재현 명령: WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_geometry_aware_sampling --original-state STATE_DIR. STATE_DIR에는 사전 파일 hash mapping인 hashes.json과 git_start.diff, git_status.txt를 둔다. 선택 규칙·입력 경로/hash는 preregistered_config.json, 실행 소스는 source_snapshot 또는 selection_source_snapshot에 있다. 보고서가 이미 존재하면 덮어쓰기를 거부하므로 별도 checkout/복제 경로에서 재현한다. 현재 결과의 문서만 재생성하려면 --render-saved SELECTION_RUN_DIR을 추가한다. 원본을 수정하지 않고 새로운 보고 UUID를 생성한다.
## 산출물과 원본 링크
[geometry_aware_sampling.html](../../experiments/495a67210c5c4cbfab91d013239f7ce9/geometry_aware_sampling.html)
[geometry_aware_sampling.json](../../experiments/495a67210c5c4cbfab91d013239f7ce9/geometry_aware_sampling.json)
[geometry_aware_sampling.npz](../../experiments/495a67210c5c4cbfab91d013239f7ce9/geometry_aware_sampling.npz)
[selection_before_gt.npz](../../experiments/495a67210c5c4cbfab91d013239f7ce9/selection_before_gt.npz)
[patch_diagnostics_before_selection.json](../../experiments/495a67210c5c4cbfab91d013239f7ce9/patch_diagnostics_before_selection.json)
[verification.json](../../visual/results/diagnostic_previews/03g/verification.json)
[tests.log](../../experiments/495a67210c5c4cbfab91d013239f7ce9/tests.log)
[source_hashes.json](../../experiments/495a67210c5c4cbfab91d013239f7ce9/source_hashes.json)
[original_hashes.json](../../experiments/495a67210c5c4cbfab91d013239f7ce9/original_hashes.json)
[preregistered_config.json](../../visual/results/diagnostic_previews/03g/preregistered_config.json)
[implementation.patch](../../experiments/495a67210c5c4cbfab91d013239f7ce9/implementation.patch)
[Task03-E saved baseline](../../experiments/7f657cf88baf4f1f89e594252e243e1c/priority_fps_metric_control.html)
[Task03-F reference / existing synthetic evidence](../../experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/local_structural_sampling.html)
[approved plan](03g_geometry_aware_sampling_plan.md)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745"""Task03-AB: gated CPU offline total-budget ablation; no production changes.
WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03ab-mpl .venv/bin/python -m \ visual.runtime.test.run_adaptive_node_budget --preservation-before PATH"""from __future__ import annotations
import argparsefrom dataclasses import dataclassimport htmlimport jsonfrom numbers import Integralfrom pathlib import Pathimport platformimport shutilimport subprocessfrom time import perf_counter
import numpy as npfrom scipy.ndimage import labelfrom scipy.spatial import cKDTree
from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.edge_evidence import PairEvidencefrom visual.runtime.geometry import GeometricFeatures, GeometryFrame, OrganizedGeometryfrom visual.runtime.rgbd import PEG, BOX, iter_saved_rgbdfrom visual.runtime.sampling import ( SamplingConfig, SamplingEvidence, allocate_budget, extract_candidates, extract_sampling_evidence, sample_points,)from visual.runtime.test.normal_diagnostics import statsfrom visual.runtime.test.run_rim_bottleneck import source_contract, occupancyfrom visual.runtime.test.run_sampling import validate_resultfrom visual.runtime.test.sampling_evaluation import ( CoverageMatcher, TOLERANCES, evaluation_context, score_selection, staged_reference_coverage, summarize,)
REPO = Path(__file__).resolve().parents[3]SOURCE = REPO / 'visual/results/sampling/2551448b0fae4c6bbce3caf48774275f'KEY = 'S3_n256_r0.25_t20_s0'CONDITIONS = ('Fixed256', 'Adaptive', 'FixedMatched')OBJECTS = (('peg', PEG), ('box', BOX))REPRESENTATIVE = (0, 15, 18, 45, 80, 120)FIELDS = ('points', 'pixels_vu', 'flat_index', 'object_id', 'priority_selected', 'depth_priority_selected')TIMERS = ('candidate_selection', 'budget_allocation', 'structural_sampling', 'surface_fps')
def write_json(path, value): Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + '\n', encoding='utf-8')
def distribution(values): a = np.asarray([x for x in values if x is not None], float) a = a[np.isfinite(a)] return dict(stats(a), min=float(a.min()) if len(a) else None)
def ratio(n, d): return n / d if d else None
def support_counts(counts): if len(counts) != 2 or any(not isinstance(x, Integral) or isinstance(x, (bool, np.bool_)) or x < 0 for x in counts): raise ValueError('two nonnegative integer support counts required') return tuple(int(x) for x in counts)
def requested_budget(counts, reference): """Only current support counts and an immutable past/current reference.""" counts = support_counts(counts) area = sum(counts) minimums = tuple(min(16, x) for x in counts) if reference is None: if area: raise ValueError('positive support requires initialized reference') return 0, minimums if not isinstance(reference, Integral) or reference <= 0: raise ValueError('reference must be a positive integer') rounded = (512 * area + int(reference)) // (2 * int(reference)) return min(256, max(sum(minimums), rounded)), minimums
@dataclassclass AreaBudget: reference: int | None = None reference_source: int | None = None
def step(self, counts, source): counts = support_counts(counts) if self.reference is None and sum(counts): self.reference, self.reference_source = sum(counts), int(source) return requested_budget(counts, self.reference)
def matched_budget(areas, requests): """One offline matched-count control, selected without geometry scores.""" if len(areas) != len(requests) or not len(areas): raise ValueError('aligned nonempty counts required') target = sum(min(int(a), int(n)) for a, n in zip(areas, requests)) b = min(range(32, 257), key=lambda n: (abs(sum(min(n, int(a)) for a in areas) - target), n)) actual = sum(min(b, int(a)) for a in areas) return dict(budget=b, adaptive_selected_sum=target, fixed_selected_sum=actual, mean_error_nodes=(actual-target)/len(areas), causal_online=False, selection='count-only absolute total difference; smaller integer on ties')
def measure_areas(frame, geometry): """Validity count cost and diagnostic raw-mask scans are separate.""" t0 = perf_counter() counts = tuple(int(np.count_nonzero(geometry.observed_mask(oid))) for _, oid in OBJECTS) count_ms = (perf_counter()-t0)*1000 t0 = perf_counter() result = {} for (name, oid), valid in zip(OBJECTS, counts): mask = frame.masks[oid] raw = int(np.count_nonzero(mask)) invalid = int(np.count_nonzero(mask & ~geometry.valid_depth)) overlap = int(np.count_nonzero(mask & geometry.valid_depth & geometry.overlap_mask)) if raw != valid + invalid + overlap: raise AssertionError('raw/valid exclusion partition') result[name] = dict(raw=raw, valid=valid, invalid_depth=invalid, positive_depth_overlap=overlap, minimum=min(16, valid)) raw_ms = (perf_counter()-t0)*1000 return result, count_ms, raw_ms
def exact_result(first, second): for field in FIELDS: np.testing.assert_array_equal(getattr(first, field), getattr(second, field), err_msg=field) if set(first.metadata) != set(second.metadata): raise AssertionError('feature field mismatch') for field in first.metadata: np.testing.assert_array_equal(first.metadata[field], second.metadata[field], err_msg=field) if first.counts != second.counts or first.object_budgets != second.object_budgets: raise AssertionError('selection counts mismatch')
def exact_saved(result, archive, key=KEY): for field in FIELDS: np.testing.assert_array_equal(getattr(result, field), archive[f'{key}/{field}'], err_msg=field) saved = {n.split('/metadata/')[1] for n in archive.files if n.startswith(key+'/metadata/')} if saved != set(result.metadata): raise AssertionError('available feature fields mismatch') for field in result.metadata: np.testing.assert_array_equal(result.metadata[field], archive[f'{key}/metadata/{field}'], err_msg=field)
def validate_selection(result, evidence, config, candidates): validate_result(result, evidence, config) counts = [len(candidates[i].points) for _, i in OBJECTS] expected = allocate_budget(config.num_points, counts, config.min_points, counts) np.testing.assert_array_equal([result.object_budgets[i] for _, i in OBJECTS], expected) if len(result.points) != min(config.num_points, sum(counts)): raise AssertionError('selected total differs from capacity-limited request') if len(np.unique(result.points, axis=0)) != len(result.points): raise AssertionError('duplicate XYZ') for _, oid in OBJECTS: keep = result.object_id == oid rows = np.searchsorted(candidates[oid].flat_index, result.flat_index[keep]) for field, values in result.metadata.items(): np.testing.assert_array_equal(values[keep], candidates[oid].metadata[field][rows], err_msg=field) c = result.counts[oid] if c['selected'] != c['priority'] + c['surface_fps'] or c['depth_priority']: raise AssertionError('S3 role accounting')
def save_evidence(path, evidence): """Lossless temporary observation cache: global gate before any ablation.""" f = evidence.frame g = f.geometry a = dict(xyz=g.xyz, valid_depth=g.valid_depth, overlap=g.overlap_mask) for _, oid in OBJECTS: a[f'mask/{oid}'] = g.object_masks[oid] for field in GeometricFeatures.__dataclass_fields__: a[f'feature/{oid}/{field}'] = getattr(f.objects[oid], field) for field in PairEvidence.__dataclass_fields__: a[f'pair/{oid}/{field}'] = np.asarray(getattr(evidence.pairs[oid], field)) a['provenance'] = np.array(json.dumps(dict(source_frame=f.source_frame, camera=f.camera, frame_idx=f.frame_idx, timestamp=f.timestamp, timings_ms=evidence.timings_ms))) np.savez_compressed(path, **a)
def load_evidence(path): with np.load(path, allow_pickle=False) as a: p = json.loads(str(a['provenance'])) g = OrganizedGeometry(a['xyz'], a['valid_depth'], {i:a[f'mask/{i}'] for _, i in OBJECTS}, a['overlap']) features = {i:GeometricFeatures(**{k:a[f'feature/{i}/{k}'] for k in GeometricFeatures.__dataclass_fields__}) for _, i in OBJECTS} pairs = {i:PairEvidence(**{k:tuple(a[f'pair/{i}/{k}']) if k == 'shape' else a[f'pair/{i}/{k}'] for k in PairEvidence.__dataclass_fields__}) for _, i in OBJECTS} f = GeometryFrame(p['source_frame'], p['camera'], p['frame_idx'], p['timestamp'], g, features, p['timings_ms']) return SamplingEvidence(f, pairs, 'pca5', p['timings_ms'])
def nearest(source, target): if not len(source): return np.empty(0) return cKDTree(target).query(source)[0]*1000 if len(target) else np.full(len(source), np.nan)
def distance_summary(distances): finite = np.isfinite(distances) return dict(distance_mm=distribution(distances), source_count=len(distances), missing_count=int((~finite).sum()), within_3mm=int((distances[finite] <= 3).sum()), coverage_3mm=ratio(int((distances[finite] <= 3).sum()), len(distances)))
def general_geometry(frame, evidence, candidates, sample, context): report, arrays = {}, {} g = evidence.frame.geometry for name, oid in OBJECTS: obj = candidates[oid] x = obj.flat_index c = x[obj.metadata['structural_candidate']] chosen = sample.object_id == oid f = sample.flat_index[chosen] p = sample.flat_index[chosen & sample.priority_selected] s = sample.flat_index[chosen & ~sample.priority_selected] xyz = g.xyz.reshape(-1, 3) xf, cp = nearest(xyz[x], xyz[f]), nearest(xyz[c], xyz[p]) components, count = label(g.observed_mask(oid)) component_rows = [] component_index = components.ravel() for k in range(1, count+1): keep = component_index[x] == k nc, np_, nf = (int((component_index[v] == k).sum()) for v in (c, p, f)) component_rows.append(dict(id=k, support=int(keep.sum()), candidate=nc, priority=np_, final=nf, small=bool(keep.sum() <= 64), candidate_without_priority=bool(nc and not np_), candidate_without_final=bool(nc and not nf), **distance_summary(xf[keep]))) paths = dict(X=x, C=c, P=p, S=s, F=f) stages = staged_reference_coverage(context['matchers'][name], c, p, s, f) depth = occupancy(frame, paths, context['negatives'][name]) report[name] = dict(x_to_f=distance_summary(xf), c_to_p=distance_summary(cp), components=component_rows, stages=stages, occupancy=depth, camera_range_m=distribution(np.linalg.norm(xyz[x].astype(float), axis=1))) arrays[name+'/c_to_p'] = cp arrays[name+'/x_to_f'] = xf return report, arrays
def sampling_timing(sample): t = {k:float(sample.timings_ms[k]) for k in (*TIMERS, 'sampling_total')} t['gather_packaging_and_other_overhead'] = t['sampling_total']-sum(t[k] for k in TIMERS) if t['gather_packaging_and_other_overhead'] < -1e-9: raise AssertionError('negative timer residual') return t
def latency_summary(records): result = {} for condition in CONDITIONS: rows = [r for r in records if r['condition'] == condition] per_frame, effective, executed = {}, {}, {} for r in rows: owner = next(x for x in records if x['source_frame'] == r['source_frame'] and x['repeat'] == r['repeat'] and x['condition'] == (r['alias_of'] or condition)) for key, value in owner['timings_ms'].items(): effective.setdefault(key, []).append(value) per_frame.setdefault(key, {}).setdefault(r['source_frame'], []).append(value) if r['executed']: executed.setdefault(key, []).append(value) result[condition] = dict(executed_calls=sum(r['executed'] for r in rows), alias_calls=sum(not r['executed'] for r in rows), frame_median_then_distribution={k:distribution([np.median(v) for v in frames.values()]) for k, frames in per_frame.items()}, all_repetitions_effective_including_explicit_alias={k:distribution(v) for k,v in effective.items()}, executed_only={k:distribution(v) for k,v in executed.items()}) return result
def preserve_check(before): changed = [name for name, expected in before['sha256'].items() if not (REPO/name).is_file() or digests(REPO/name)[1] != expected] return dict(checked_files=len(before['sha256']), changed_or_missing=changed, unchanged=not changed)
def add_temporal_and_pairs(rows): for index, row in enumerate(rows): if row['source_frame'] != index: raise AssertionError('source frame continuity') for condition, data in row['conditions'].items(): previous = rows[index-1]['conditions'][condition] if index else None for field in ('requested', 'selected'): delta = data[field]-previous[field] if previous else None data['delta_'+field] = delta data['abs_delta_'+field] = abs(delta) if delta is not None else None fixed = row['conditions']['Fixed256']['selected'] data['node_reduction_vs_fixed256'] = 1-data['selected']/fixed if fixed else None for name, _ in OBJECTS: base = row['conditions']['Fixed256']['geometry']['objects'][name] current = data['geometry']['objects'][name] f, a = (v['structural']['tolerance']['2px_3mm']['sampling_retention'] for v in (base, current)) data['objects'][name]['retention_difference_pp_vs_fixed256'] = (a-f)*100 if a is not None and f is not None else None for field in ('mean', 'p95'): f, a = (v['surface']['all']['distance_mm'][field] for v in (base, current)) data['objects'][name]['surface_'+field+'_difference_mm_vs_fixed256'] = a-f if a is not None and f is not None else None
def make_summary(rows, pools, distance_pools, matched, policy): summary = {} fixed_sum = sum(r['conditions']['Fixed256']['selected'] for r in rows) for condition in CONDITIONS: geometry = summarize(pools[condition], distance_pools[condition]) geometry.pop('timings_ms', None) # timings are paired separately, with explicit aliases counts = {field:distribution([r['conditions'][condition][field] for r in rows]) for field in ('requested', 'selected', 'priority', 'surface', 'shortfall', 'delta_requested', 'delta_selected', 'abs_delta_selected')} selected = sum(r['conditions'][condition]['selected'] for r in rows) objects = {} for name, _ in OBJECTS: objects[name] = dict( allocated=distribution([r['conditions'][condition]['objects'][name]['allocated'] for r in rows]), selected=distribution([r['conditions'][condition]['objects'][name]['selected'] for r in rows]), density_per_valid_pixel=distribution([r['conditions'][condition]['objects'][name]['density_per_valid_pixel'] for r in rows]), retention_difference_pp=distribution([r['conditions'][condition]['objects'][name]['retention_difference_pp_vs_fixed256'] for r in rows]), c_to_p_mm=distribution(np.concatenate(distance_pools[condition][name+'/c_to_p']))) summary[condition] = dict(counts=counts, selected_sum=selected, node_reduction_fraction=1-selected/fixed_sum, geometry=geometry, objects=objects, requested_max_frames=[r['source_frame'] for r in rows if r['conditions'][condition]['requested'] == 256], requested_min_frames=[r['source_frame'] for r in rows if r['conditions'][condition]['requested'] == r['minimum_total']]) area = [sum(r['areas'][name]['valid'] for name, _ in OBJECTS) for r in rows] median_area = float(np.median(area)) strata = {} for title, ids in [('area_le_median',[i for i,a in enumerate(area) if a <= median_area]), ('area_gt_median',[i for i,a in enumerate(area) if a > median_area]), ('box_support_zero',[i for i,r in enumerate(rows) if not r['areas']['box']['valid']])]: strata[title] = dict(source_frames=ids, objects={name:distribution([ rows[i]['conditions']['Adaptive']['objects'][name]['retention_difference_pp_vs_fixed256'] for i in ids]) for name, _ in OBJECTS}) return dict(conditions=summary, matched=matched, policy=dict(alpha=1, reference=policy.reference, reference_source=policy.reference_source, rounding='integer half-up', maximum=256, minimum='sum min(16, current object support)'), area_strata=dict(median_valid_area=median_area, strata=strata))
def plot_results(output, rows, latency): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt colors = dict(Fixed256='#64748b', Adaptive='#e76f51', FixedMatched='#247ba0') x = np.arange(len(rows)) plotdir = output/'plots' plotdir.mkdir(exist_ok=True) def finish(fig, axes, filename): for ax in np.asarray(axes).ravel(): for lo, hi in ((18,26),(56,65)): if ax.get_xlabel() == 'Source frame': ax.axvspan(lo-.5,hi+.5,color='#cbd5e1',alpha=.4) ax.grid(alpha=.2) ax.legend(fontsize=7, loc='best') fig.savefig(plotdir/filename, dpi=140) plt.close(fig) fig, axes = plt.subplots(4,1,figsize=(15,12),layout='constrained') for name, _ in OBJECTS: for field, ls in [('raw','--'),('valid','-')]: axes[0].plot(x,[r['areas'][name][field] for r in rows],ls,label=name+' '+field) for condition in CONDITIONS: axes[1].plot(x,[r['conditions'][condition]['selected'] for r in rows],label=condition,color=colors[condition]) for name, ls in [('peg','-'),('box','--')]: axes[2].plot(x,[r['conditions'][condition]['objects'][name]['allocated'] for r in rows],ls, label=condition+' '+name,color=colors[condition]) for field, ls in [('priority','-'),('surface','--')]: axes[3].plot(x,[r['conditions'][condition][field] for r in rows],ls,label=condition+' '+field,color=colors[condition]) for ax,title in zip(axes,['Raw / valid projected pixel areas','Actual point nodes','Object allocated budgets','Priority / Surface roles']): ax.set(title=title,xlabel='Source frame') finish(fig,axes,'budget_timeseries.png') fig, axes = plt.subplots(2,3,figsize=(17,9),layout='constrained') area = [sum(r['areas'][n]['valid'] for n,_ in OBJECTS) for r in rows] reduction = [r['conditions']['Adaptive']['node_reduction_vs_fixed256']*100 for r in rows] for col,(name,_) in enumerate(OBJECTS): for condition in CONDITIONS: retention = [r['conditions'][condition]['geometry']['objects'][name]['structural']['tolerance']['2px_3mm']['sampling_retention'] for r in rows] axes[0,col].scatter(reduction,retention,s=10,label=condition,color=colors[condition],alpha=.7) axes[1,col].plot(x,[r['conditions'][condition]['geometry']['objects'][name]['surface']['all']['distance_mm']['p95'] for r in rows], label=condition,color=colors[condition]) axes[0,col].set(title=name+' retention vs Adaptive node reduction',xlabel='Adaptive node reduction (%)',ylabel='Observable reference retention') axes[1,col].set(title=name+' X to F p95 distance',xlabel='Source frame',ylabel='mm') for condition in CONDITIONS: axes[0,2].scatter(area,[r['conditions'][condition]['selected'] for r in rows],s=12,label=condition,color=colors[condition]) axes[0,2].set(title='Area / node relationship (cap 256)',xlabel='Valid projected pixels',ylabel='Actual nodes',ylim=(0,270)) axes[1,2].plot(x,[r['conditions']['Adaptive']['delta_selected'] for r in rows],label='Adaptive signed delta') axes[1,2].plot(x,[r['conditions']['Adaptive']['abs_delta_selected'] for r in rows],label='Adaptive abs delta') axes[1,2].set(title='Temporal node changes',xlabel='Source frame',ylabel='Nodes / frame') finish(fig,axes,'preservation_temporal.png') fig, axes = plt.subplots(2,2,figsize=(15,9),layout='constrained') for condition in CONDITIONS: ys = [np.median([next(t for t in latency if t['source_frame']==r['source_frame'] and t['repeat']==rep and t['condition']==(next(z for z in latency if z['source_frame']==r['source_frame'] and z['repeat']==rep and z['condition']==condition)['alias_of'] or condition))['timings_ms']['sampling_total'] for rep in range(3)]) for r in rows] axes[0,0].plot(x,ys,label=condition,color=colors[condition]) axes[0,1].scatter([r['conditions'][condition]['selected'] for r in rows],ys,s=12,label=condition,color=colors[condition]) axes[0,0].set(title='Paired sampling (frame median; aliases explicit in JSON)',xlabel='Source frame',ylabel='ms') axes[0,1].set(title='Selected nodes / actual measured selection latency',xlabel='Actual nodes',ylabel='ms') for name,_ in OBJECTS: axes[1,0].plot(x,[r['conditions']['Adaptive']['general'][name]['occupancy']['depth_m']['X']['median'] for r in rows],label=name+' median z') axes[1,1].scatter([r['areas'][name]['valid'] for r in rows], [r['conditions']['Adaptive']['objects'][name]['retention_difference_pp_vs_fixed256'] for r in rows],s=15,label=name) axes[1,0].set(title='Observed depth; contamination retained',xlabel='Source frame',ylabel='Camera z (m)') axes[1,1].set(title='Small masks / sampling retention loss',xlabel='Valid projected pixels',ylabel='Adaptive - Fixed256 (pp)') finish(fig,axes,'latency_depth.png')
def overlay(output, frame, candidates, samples, context): import matplotlib.pyplot as plt h,w = frame.depth.shape fig,axes = plt.subplots(3,3,figsize=(15,13),layout='constrained') for row, oid in enumerate((None, PEG, BOX)): union = frame.masks[PEG] | frame.masks[BOX] if oid is None else frame.masks[oid] v,u = np.nonzero(union) limits = (max(0,int(u.min())-10),min(w-1,int(u.max())+10),min(h-1,int(v.max())+10),max(0,int(v.min())-10)) if len(u) else (0,w-1,h-1,0) for col,condition in enumerate(CONDITIONS): ax=axes[row,col]; ax.imshow(frame.rgb) for name,i in OBJECTS: if oid is not None and oid != i: continue mask=frame.masks[i] if mask.any() and not mask.all(): ax.contour(mask,[.5],colors=['#69ff72'],linewidths=.5) flat=candidates[i].flat_index[candidates[i].metadata['structural_candidate']] cv,cu=np.unravel_index(flat,(h,w));ax.scatter(cu,cv,s=2,c='#ff5d41',alpha=.45) uv=context['references'][name][0];ax.scatter(uv[:,0],uv[:,1],s=12,c='#ff65cc',marker='+',linewidths=.4) s=samples[condition] keep=np.ones(len(s.points),bool) if oid is None else s.object_id==oid for priority,color,marker,size in [(False,'#00d9ff','o',9),(True,'#ffff00','*',24)]: pv,pu=s.pixels_vu[keep & (s.priority_selected==priority)].T ax.scatter(pu,pv,s=size,c=color,marker=marker,edgecolors='black',linewidths=.2) ax.set(xlim=limits[:2],ylim=limits[2:],title=f'{condition} | {"All" if oid is None else ("Peg" if oid==PEG else "Box")} N={int(keep.sum())}') ax.axis('off') fig.suptitle(f'Source {frame.source_frame} | same crop per row | yellow=Priority, cyan=Surface, red=candidate, pink=GT eval\nMasks may be contaminated; absent object remains empty. No padding.') fig.savefig(output/'frames'/f'f{frame.source_frame:04d}_overlay.png',dpi=140);plt.close(fig)
def html_report(output, data, rows): def value(v): return 'N/A' if v is None else f'{v:.3f}' summary=[] for condition,s in data['conditions'].items(): g=s['geometry']['objects'] summary.append('<tr>'+''.join(f'<td>{html.escape(str(v))}</td>' for v in [condition, value(s['counts']['selected']['mean']), value(s['counts']['selected']['p50']), value(100*s['node_reduction_fraction']), value(100*g['peg']['structural']['2px_3mm']['sampling_retention']), value(100*g['box']['structural']['2px_3mm']['sampling_retention']), value(g['peg']['surface']['all']['distance_mm']['p95']), value(g['box']['surface']['all']['distance_mm']['p95'])])+'</tr>') table=[] for r in rows: source=r['source_frame'] links=f'<a href="frames/f{source:04d}_samples.npz">NPZ</a>' if source in REPRESENTATIVE: links+=f' <a href="frames/f{source:04d}_overlay.png">overlay</a>' table.append('<tr>'+''.join(f'<td>{v}</td>' for v in [source, r['areas']['peg']['raw'],r['areas']['peg']['valid'],r['areas']['box']['raw'],r['areas']['box']['valid'], *[r['conditions'][c]['selected'] for c in CONDITIONS],links])+'</tr>') plots=''.join(f'<a href="plots/{p.name}"><img src="plots/{p.name}" alt="{p.stem}"></a>' for p in sorted((output/'plots').glob('*.png'))) images=''.join(f'<a href="frames/f{s:04d}_overlay.png"><img src="frames/f{s:04d}_overlay.png" alt="Source {s}"></a>' for s in REPRESENTATIVE) dependencies=''.join(f'<li><a href="{html.escape(v)}">{html.escape(k)}</a></li>' for k,v in data['dependency_links'].items()) (output/'adaptive_node_budget.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><title>Task03-AB adaptive total node budget</title><style>body{font:15px system-ui;max-width:1500px;margin:28px auto;padding:0 16px;color:#17212b}img{width:100%;margin:15px 0}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{padding:7px;border:1px solid #ccd3da;text-align:right}th:first-child,td:first-child{text-align:left}pre{white-space:pre-wrap}a{color:#146cb2}</style><h1>Task03-AB — Adaptive Total Node Budget</h1>'''+f'<p>Run {data["run_id"]}. CPU only; ep000 source 0–120. All 121-frame gates passed before adaptive geometry evaluation.</p>' +'<p>First positive valid support fixes the causal reference. Pixel area is projected area, not physical 3D surface area. FixedMatched uses episode counts offline. Same S3 / 20° / .25 / seed0 / 3D FPS; Priority cap changes with requested budget.</p>' +'<p>Joint matcher: the same pair within 2px AND 3mm. Retention denominator is tracker-observable references. N/A is preserved. Gray bands mark recorded Box support loss, not independently proven occlusion. Sampling latency excludes PCA5 extraction, GT and I/O; aliases have no invented FPS calls. No GNN/BC, stale-cache integration, GPU or end-to-end 20Hz claim.</p>' +'<p><a href="adaptive_node_budget.json">Summary/config</a> · <a href="frame_metrics.json">All frame metrics</a> · <a href="latency.json">Raw/aggregated timing</a> · <a href="verification.json">Gates/preservation</a> · <a href="tests.log">Tests</a> · <a href="implementation.patch">Implementation diff</a></p>' +'<table><tr><th>Condition</th><th>Mean N</th><th>Median N</th><th>Reduction %</th><th>Peg retention %</th><th>Box retention %</th><th>Peg surface p95 mm</th><th>Box surface p95 mm</th></tr>'+''.join(summary)+'</table>' +plots+'<h2>Representative frames</h2>'+images+'<h2>All frame artifacts</h2><table><tr><th>Source</th><th>Peg raw</th><th>Peg valid</th><th>Box raw</th><th>Box valid</th><th>Fixed256</th><th>Adaptive</th><th>FixedMatched</th><th>Files</th></tr>'+''.join(table)+'</table>' +'<h2>Original read-only dependencies</h2><ul>'+dependencies+'</ul><details><summary>Policy / reference / matched control</summary><pre>' +html.escape(json.dumps(dict(policy=data['policy'],reference=data['reference_camera'],matched=data['matched']),indent=2))+'</pre></details></html>',encoding='utf-8')
def evaluate(preservation_before, tests_log=None): source=SOURCE original=json.loads((source/'comparison.json').read_text()) cfg=original['config'] episode=REPO/'visual/data/step2/ep000.npz' masks=REPO/'visual/results/runtime_tracking/ep000/masks.npz' camera='base_camera' saved=[json.loads((source/f'f{i:04d}_metrics.json').read_text())[KEY] for i in range(121)] counts=[tuple(r['objects'][n]['counts']['observed'] for n,_ in OBJECTS) for r in saved] policy=AreaBudget() planned=[policy.step(c,i)[0] for i,c in enumerate(counts)] matched=matched_budget([sum(c) for c in counts],planned) config=dict(task='03-AB', source_run_id=original['run_id'], input=str(episode), masks=str(masks), camera=camera, alpha=1, maximum=256, minimum_per_object=16, matched=matched, reference=policy.reference, reference_source=policy.reference_source, baseline=KEY, tolerances=TOLERANCES, seed=0, device='cpu', independent_episode=False, timing_repetitions=3, extraction='once per frame; lossless cache to enforce all-frame gates first', policy_inputs='current observed support counts and fixed first-positive reference only', python=platform.python_version(), numpy=np.__version__, platform=platform.platform()) with ExperimentLogger(team='visual',config=config,seed=0,model='task03ab_adaptive_node_budget',job_type='evaluate') as logger: output=logger.directory print('Output:',output,flush=True) for p in ('cache','frames','evaluated_source'): (output/p).mkdir() before=json.loads(Path(preservation_before).read_text()) write_json(output/'preservation_before.json',before) verification=dict(gates_passed=False,adaptive_geometry_executed=False,frame_gates=[], primary_tolerance='same pair 2px AND 3mm') try: for path, expected in ((episode,cfg['input_sha256']),(masks,cfg['masks_sha256'])): if digests(path)[1] != expected: raise AssertionError('input hash mismatch: '+str(path)) verification['input_hashes']={str(p.relative_to(REPO)):digests(p)[1] for p in (episode,masks)} verification['source_contract']=source_contract(source,cfg) with np.load(masks,allow_pickle=False) as ar: np.testing.assert_array_equal(ar['source_frame'],np.arange(121)) tracking=json.loads(masks.with_name('tracking.json').read_text()) if tracking['camera'] != camera: raise AssertionError('tracker camera mismatch') if digests(Path(tracking['input']))[1] != cfg['input_sha256']: raise AssertionError('tracker input provenance mismatch') if TOLERANCES != ((1.,.002),(2.,.003),(3.,.005)): raise AssertionError('joint tolerances changed') for relative in (*cfg['source_sha256'], 'visual/runtime/test/run_rim_bottleneck.py', 'visual/runtime/test/run_adaptive_node_budget.py', 'visual/runtime/test/test_adaptive_node_budget.py'): dest=output/'evaluated_source'/relative dest.parent.mkdir(parents=True,exist_ok=True) shutil.copyfile(REPO/relative,dest) patch='' for relative in ('visual/runtime/test/run_adaptive_node_budget.py','visual/runtime/test/test_adaptive_node_budget.py'): proc=subprocess.run(['git','diff','--no-index','--','/dev/null',relative],cwd=REPO,capture_output=True,text=True) patch+=proc.stdout (output/'implementation.patch').write_text(patch) if tests_log: shutil.copyfile(tests_log,output/'tests.log') required=[f'{camera}/seg','peg_id','box_id','peg_pose','box_pose','box_hole_pose','peg_half_sizes','box_hole_radii','seed'] with np.load(episode,allow_pickle=False) as ar: if len(ar[f'{camera}/depth']) != 121: raise AssertionError('episode frame count') gt={k:ar[k] for k in required} # never supplied to the budget helper or sampler robot_ids=cfg['robot_ids'] pools={c:[] for c in CONDITIONS} distance_pools={c:{} for c in CONDITIONS} gate_rows=[] reference_camera=None for index,frame in enumerate(iter_saved_rgbd(episode,masks,camera=camera)): if frame.source_frame != index: raise AssertionError('source mapping') evidence=extract_sampling_evidence(frame,'pca5') candidates=extract_candidates(evidence,SamplingConfig(),'S3') areas,count_ms,raw_ms=measure_areas(frame,evidence.frame.geometry) actual=tuple(areas[n]['valid'] for n,_ in OBJECTS) if actual != counts[index]: raise AssertionError('observed count mismatch') fixed=sample_points(evidence,SamplingConfig(),method='S3') validate_selection(fixed,evidence,SamplingConfig(),candidates) with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as archive: if int(archive['source_frame']) != index: raise AssertionError('archive source mapping') np.testing.assert_array_equal(archive['shape'],frame.depth.shape) for _,oid in OBJECTS: c=candidates[oid] np.testing.assert_array_equal(c.flat_index[c.metadata['structural_candidate']], archive[f'evidence/pca5/{oid}/20/orientation_flat']) exact_saved(fixed,archive) context=evaluation_context(frame,evidence,gt,camera,robot_ids) for name,oid in OBJECTS: reference=tuple(archive[f'evaluation/{name}/reference_{s}'] for s in ('uv','xyz')) for a,b in zip(reference,context['references'][name]): np.testing.assert_array_equal(a,b) context['references'][name]=reference context['matchers'][name]=CoverageMatcher(evidence.frame.geometry,oid,reference) score,dist=score_selection(fixed,context) np.testing.assert_equal(score['objects'],saved[index]['objects']) score['source_frame']=index pools['Fixed256'].append(score) for k,v in dist.items(): distance_pools['Fixed256'].setdefault(k,[]).append(v.astype(np.float32)) save_evidence(output/'cache'/f'f{index:04d}_evidence.npz',evidence) gate_rows.append(dict(source_frame=index,areas=areas,support_count_ms=count_ms, raw_area_diagnostics_ms=raw_ms,extraction_ms=evidence.timings_ms)) if index == policy.reference_source: reference_camera=dict(source_frame=index,frame_idx=frame.frame_idx,timestamp=frame.timestamp, shape=list(frame.depth.shape),camera=camera,intrinsic=frame.intrinsic.tolist(), cam2world=frame.cam2world.tolist(),areas=areas,unit='projected pixel count') verification['frame_gates'].append(dict(source_frame=index,support_exact=True,candidate_exact=True, fixed256_all_fields_exact=True,reference_exact=True,fixed256_original_metrics_exact=True)) if index%15 == 0: print(f'Gate {index+1}/121: support/candidates/selection/features/reference/metrics exact',flush=True) if len(verification['frame_gates']) != 121: raise AssertionError('all-frame gate incomplete') verification['gates_passed']=True write_json(output/'verification.json',verification) print('All 121 gates passed. Starting paired ablation.',flush=True) except Exception as exc: verification['failure']=dict(type=type(exc).__name__,message=str(exc)) write_json(output/'verification.json',verification) (output/'adaptive_node_budget.html').write_text('<!doctype html><meta charset="utf-8"><h1>Gate failed; adaptive geometry NOT RUN</h1><a href="verification.json">Verification</a>') raise
rows=[];timings=[];actual_policy=AreaBudget();warmups=[] for index,frame in enumerate(iter_saved_rgbd(episode,masks,camera=camera)): evidence=load_evidence(output/'cache'/f'f{index:04d}_evidence.npz') candidates=extract_candidates(evidence,SamplingConfig(),'S3') area=gate_rows[index]['areas'] current_counts=tuple(area[n]['valid'] for n,_ in OBJECTS) request,minimums=actual_policy.step(current_counts,index) if request != planned[index]: raise AssertionError('causal policy differs from count-only planning') configs=dict(Fixed256=SamplingConfig(),Adaptive=SamplingConfig(num_points=request,min_points=minimums), FixedMatched=SamplingConfig(num_points=matched['budget'])) owner={};unique={} for condition,c in configs.items(): signature=(c.num_points,tuple(min(m,a) for m,a in zip(c.min_points,current_counts))) owner[condition]=unique.setdefault(signature,condition) names=list(dict.fromkeys(owner.values())) if index == 0: for condition in names: sample_points(evidence,configs[condition],method='S3') warmups.append(dict(condition=condition,source_frame=0,measured=False)) selected={} budget_times=[] for repeat in range(3): start=perf_counter();check=requested_budget(current_counts,actual_policy.reference) budget_times.append((perf_counter()-start)*1000) if check != (request,minimums): raise AssertionError('deterministic budget') order=names[(index+repeat)%len(names):]+names[:(index+repeat)%len(names)] for condition in order: sample=sample_points(evidence,configs[condition],method='S3') measured=sampling_timing(sample) validate_selection(sample,evidence,configs[condition],candidates) if repeat: exact_result(sample,selected[condition]) else: selected[condition]=sample timings.append(dict(source_frame=index,repeat=repeat,condition=condition,executed=True, alias_of=None,order=order,timings_ms=measured)) for condition in CONDITIONS: if owner[condition] != condition: timings.append(dict(source_frame=index,repeat=repeat,condition=condition,executed=False, alias_of=owner[condition],timings_ms=None)) results={c:selected[owner[c]] for c in CONDITIONS} with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as ar: exact_saved(results['Fixed256'],ar) if request == 256: exact_saved(results['Adaptive'],ar) # No GT is supplied until all selections and deterministic checks are complete. context=evaluation_context(frame,evidence,gt,camera,robot_ids) with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as ar: for name,oid in OBJECTS: reference=tuple(ar[f'evaluation/{name}/reference_{s}'] for s in ('uv','xyz')) for a,b in zip(reference,context['references'][name]): np.testing.assert_array_equal(a,b) context['references'][name]=reference context['matchers'][name]=CoverageMatcher(evidence.frame.geometry,oid,reference) row=dict(gate_rows[index],minimum_total=sum(minimums),adaptive_budget_ms=budget_times, intrinsic=frame.intrinsic.tolist(),cam2world=frame.cam2world.tolist(),conditions={}) archive=dict(source_frame=np.array(index),shape=np.array(frame.depth.shape)) for name,oid in OBJECTS: c=candidates[oid] archive[f'support/{name}/flat_index']=c.flat_index archive[f'support/{name}/xyz']=c.points archive[f'candidate/{name}/flat_index']=c.flat_index[c.metadata['structural_candidate']] archive[f'candidate/{name}/xyz']=c.points[c.metadata['structural_candidate']] for suffix,a in zip(('uv','xyz'),context['references'][name]): archive[f'evaluation/{name}/reference_{suffix}']=a for condition,sample in results.items(): if condition == 'Fixed256': score=pools['Fixed256'][index] else: score,dist=score_selection(sample,context);score['source_frame']=index pools[condition].append(score) for k,v in dist.items(): distance_pools[condition].setdefault(k,[]).append(v.astype(np.float32)) general,dist=general_geometry(frame,evidence,candidates,sample,context) for k,v in dist.items(): distance_pools[condition].setdefault(k,[]).append(v.astype(np.float32)) object_rows={} for name,oid in OBJECTS: c=sample.counts[oid] object_rows[name]=dict(allocated=c['budget'],selected=c['selected'],priority=c['priority'], surface=c['surface_fps'],candidates=c['candidates'],selected_candidates=c['selected_candidates'], shortfall=c['budget']-c['selected'],minimum_support_shortfall=max(0,16-area[name]['valid']), density_per_valid_pixel=ratio(c['selected'],area[name]['valid']), density_per_raw_pixel=ratio(c['selected'],area[name]['raw'])) n=configs[condition].num_points row['conditions'][condition]=dict(requested=n,selected=len(sample.points), allocated_total=sum(sample.object_budgets.values()),priority=int(sample.priority_selected.sum()), surface=int((~sample.priority_selected).sum()),priority_cap=n//4, shortfall=n-len(sample.points),maximum_saturated=n==256,minimum_saturated=n==sum(minimums), alias_of=owner[condition] if owner[condition]!=condition else None, objects=object_rows,geometry=score,general=general) for field in FIELDS: archive[f'{condition}/{field}']=getattr(sample,field) for field,a in sample.metadata.items(): archive[f'{condition}/metadata/{field}']=a rows.append(row) np.savez_compressed(output/'frames'/f'f{index:04d}_samples.npz',**archive) if index in REPRESENTATIVE: overlay(output,frame,candidates,results,context) if index%15 == 0: print(f'Ablation {index+1}/121: adaptive request={request}, matched={matched["budget"]}',flush=True) add_temporal_and_pairs(rows) latency=dict(raw=timings,summary=latency_summary(timings),warmups=warmups, adaptive_budget_ms=distribution([np.median(r['adaptive_budget_ms']) for r in rows]), support_count_ms=distribution([r['support_count_ms'] for r in rows]), raw_area_diagnostics_ms=distribution([r['raw_area_diagnostics_ms'] for r in rows]), extraction_ms={k:distribution([r['extraction_ms'][k] for r in rows]) for k in rows[0]['extraction_ms']}, scope='CPU same process, 3 rotated repetitions; per-frame median then across frames. Raw diagnostic scan excluded; support count shared once. Aliases have timings_ms=null; effective statistics reference an actual owner call. Gather residual includes overhead. GT/I/O/plots/extraction excluded from sampling_total.') data=make_summary(rows,pools,distance_pools,matched,actual_policy) import os data.update(run_id=logger.run_id,source_run_id=original['run_id'],config=config, reference_camera=reference_camera,latency=latency['summary'], input_hashes=verification['input_hashes'],source_contract=verification['source_contract'], dependency_links={k:os.path.relpath(v,output) for k,v in dict( original_comparison=source/'comparison.json', original_html=source/'comparison.html', original_samples_frame0=source/'f0000_samples.npz', rgbd=episode, tracker_masks=masks).items()}) write_json(output/'adaptive_node_budget.json',data) write_json(output/'frame_metrics.json',rows) write_json(output/'latency.json',latency) plot_results(output,rows,timings) html_report(output,data,rows) verification.update(adaptive_geometry_executed=True,deterministic_repetitions=True, adaptive_request256_exact_frames=[r['source_frame'] for r in rows if r['conditions']['Adaptive']['requested']==256], preservation=preserve_check(before),evaluated_frames=len(rows),gpu_executed=False, source_snapshot_sha256={str(p.relative_to(output/'evaluated_source')):digests(p)[1] for p in (output/'evaluated_source').rglob('*') if p.is_file()}) if not verification['preservation']['unchanged']: raise AssertionError('pre-existing source/artifact changed') write_json(output/'verification.json',verification) for p in sorted(output.rglob('*')): if p.is_file() and p.name not in ('config.yaml','metadata.json','metrics.json','manifest.json') and not p.name.endswith('.tracking.json'): logger.link_output(p,kind='metrics' if p.suffix=='.json' else 'trajectory' if p.suffix=='.npz' else 'reports') logger.log({c:dict(mean_nodes=data['conditions'][c]['counts']['selected']['mean'], reduction=data['conditions'][c]['node_reduction_fraction']) for c in CONDITIONS},prefix='eval/task03ab') logger.record(evaluated_frames=121,evaluation_device='cpu',gpu_executed=False,source_run_id=original['run_id']) print('Completed:',output,flush=True) return output
def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--preservation-before',type=Path,required=True) parser.add_argument('--tests-log',type=Path) args=parser.parse_args() evaluate(args.preservation_before,args.tests_log)
if __name__ == '__main__': main()12"""Compatibility imports for the original PCA5 optimization experiments."""from visual.runtime.pca import (build_geometry, covariance_patches, smallest_eigenvector, local_plane_optimized, cropped_features, process_optimized, _bounds, _two_object_executor)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385{ "selection_source_hashes": { "sources_before": { "utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "visual/runtime/test/run_geometry_aware_sampling.py": "011fe12780cb14ed6ca52c3bffeeb19165164085c948d5c94cb8568ec02a6837", "visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "visual/runtime/test/run_local_structural_sampling.py": "4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "visual/runtime/test/run_priority_fps_metric_control.py": "c01afcd516f3cf2b1f1d34d5878be2376e849e50dc7c1b809854d8f5231d1ca9", "visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f", "visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "visual/runtime/test/test_local_structural_sampling.py": "d6758da4be04c7622a40ed9226503e6d2884de89f08992fc731200c8d21d7994", "visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "visual/runtime/test/test_priority_fps_metric_control.py": "92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565", "visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522" }, "sources_after": { "utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "visual/runtime/test/run_geometry_aware_sampling.py": "011fe12780cb14ed6ca52c3bffeeb19165164085c948d5c94cb8568ec02a6837", "visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "visual/runtime/test/run_local_structural_sampling.py": "4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "visual/runtime/test/run_priority_fps_metric_control.py": "c01afcd516f3cf2b1f1d34d5878be2376e849e50dc7c1b809854d8f5231d1ca9", "visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f", "visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "visual/runtime/test/test_local_structural_sampling.py": "d6758da4be04c7622a40ed9226503e6d2884de89f08992fc731200c8d21d7994", "visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "visual/runtime/test/test_priority_fps_metric_control.py": "92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565", "visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522" }, "inputs_before": { "experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/local_structural_sampling.json": "9842fe63d7df2ef37dee85ecbc49c03ed8f058c1f0f3ac72266a147c0ed03208", "experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/local_structural_sampling.npz": "c08ec5e58099bb36b8d4eafee836fb535a93475bbbb8035a7f8a7148f5f5f8d4", "experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/verification.json": "8f98da2dda275c17685a410feac1373764e6cf85294b62bcf01b3f14274e8639", "experiments/7f657cf88baf4f1f89e594252e243e1c/priority_fps_metric_control.json": "b06b6ff4a75af3017679af6474866b234693c8ddee875fa273787e5041bf05ac", "experiments/7f657cf88baf4f1f89e594252e243e1c/priority_fps_metric_control.npz": "59431ef2427510990adc4e994238de3552a0ff723905c6795b5cd9bae8a778a9", "experiments/7f657cf88baf4f1f89e594252e243e1c/verification.json": "406d1d9ffbf439a5e39ed59c61b6c16203c325311c989f0c6bc39d8689a5a38c", "experiments/aa5d71078e0841fd886b5026d6030ebc/priority_fps_trace.json": "330f451d1424ec05d237070443cd898f5f5b4f6118a1132cfcb06184075577e0", "experiments/d3f14ee494894daabb8ba2fab8e1b00c/diagnostic.json": "2a0346704763e2a5aca9ef3d52913699ced651501b031a8b1a49c57e6dcdfcff", "experiments/f36f1e9e2bb64866b8d6c792db158635/priority_fps_seed_control.json": "11d49e29ff4dda86fc1d0d51227251f53d49f40adfff21b775efdca45daa4927", "visual/data/step2/ep000.npz": "22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba", "visual/results/normal_comparison/4b1c377ae2044344a4f596b249627d89/comparison.json": "dcf0ccea29b10f70344e352eddb8b48bab348cf43996223ad874fe5b43412511", "visual/results/normal_comparison/4b1c377ae2044344a4f596b249627d89/f0000.npz": "801799c9ef1fefb464e0d24b244ab37ca341ea4715a214448406aa7aaf3217d2", "visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/f0000.npz": "62f4fe9782cc1d6cd1aa737491999255f7286b22f2a589d9a3152c440538df93", "visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/geometry.json": "6d93c76efa582ecadf2acbb3b6d0b9ae829179cc3e915be5ccc51cbec46fa846", "visual/results/runtime_tracking/ep000/masks.npz": "6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json": "a88035aa821b879f1e6b87cf5b477af13f0d5858568ca0efa7c26c364894e94c", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_metrics.json": "6df34b94fa8e513d8872c3259bfe5a3d60b5718875b80d1715e5f8b6522ebbe8", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz": "9f6d46356212bc43bd29ceb6df34c1a96ea70b3879f0bb4da2c6ccae535dd058", "visual/results/structural_edges/b622e76deceb419ab9c5aa80a8f8280c/comparison.json": "3096d2fda65176cbcc9e979fdc7a02e717f407132436818140cc9f1b40542cbd", "visual/results/structural_edges/b622e76deceb419ab9c5aa80a8f8280c/f0000_pairs.npz": "cb2320d63ed533270b1623e9128399514c51774f0471b4a7a5adbf71ded1d6f4" }, "inputs_after": { "experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/local_structural_sampling.json": "9842fe63d7df2ef37dee85ecbc49c03ed8f058c1f0f3ac72266a147c0ed03208", "experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/local_structural_sampling.npz": "c08ec5e58099bb36b8d4eafee836fb535a93475bbbb8035a7f8a7148f5f5f8d4", "experiments/1f7ad262dd2e4b2fb0ac805a4eda5278/verification.json": "8f98da2dda275c17685a410feac1373764e6cf85294b62bcf01b3f14274e8639", "experiments/7f657cf88baf4f1f89e594252e243e1c/priority_fps_metric_control.json": "b06b6ff4a75af3017679af6474866b234693c8ddee875fa273787e5041bf05ac", "experiments/7f657cf88baf4f1f89e594252e243e1c/priority_fps_metric_control.npz": "59431ef2427510990adc4e994238de3552a0ff723905c6795b5cd9bae8a778a9", "experiments/7f657cf88baf4f1f89e594252e243e1c/verification.json": "406d1d9ffbf439a5e39ed59c61b6c16203c325311c989f0c6bc39d8689a5a38c", "experiments/aa5d71078e0841fd886b5026d6030ebc/priority_fps_trace.json": "330f451d1424ec05d237070443cd898f5f5b4f6118a1132cfcb06184075577e0", "experiments/d3f14ee494894daabb8ba2fab8e1b00c/diagnostic.json": "2a0346704763e2a5aca9ef3d52913699ced651501b031a8b1a49c57e6dcdfcff", "experiments/f36f1e9e2bb64866b8d6c792db158635/priority_fps_seed_control.json": "11d49e29ff4dda86fc1d0d51227251f53d49f40adfff21b775efdca45daa4927", "visual/data/step2/ep000.npz": "22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba", "visual/results/normal_comparison/4b1c377ae2044344a4f596b249627d89/comparison.json": "dcf0ccea29b10f70344e352eddb8b48bab348cf43996223ad874fe5b43412511", "visual/results/normal_comparison/4b1c377ae2044344a4f596b249627d89/f0000.npz": "801799c9ef1fefb464e0d24b244ab37ca341ea4715a214448406aa7aaf3217d2", "visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/f0000.npz": "62f4fe9782cc1d6cd1aa737491999255f7286b22f2a589d9a3152c440538df93", "visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/geometry.json": "6d93c76efa582ecadf2acbb3b6d0b9ae829179cc3e915be5ccc51cbec46fa846", "visual/results/runtime_tracking/ep000/masks.npz": "6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json": "a88035aa821b879f1e6b87cf5b477af13f0d5858568ca0efa7c26c364894e94c", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_metrics.json": "6df34b94fa8e513d8872c3259bfe5a3d60b5718875b80d1715e5f8b6522ebbe8", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz": "9f6d46356212bc43bd29ceb6df34c1a96ea70b3879f0bb4da2c6ccae535dd058", "visual/results/structural_edges/b622e76deceb419ab9c5aa80a8f8280c/comparison.json": "3096d2fda65176cbcc9e979fdc7a02e717f407132436818140cc9f1b40542cbd", "visual/results/structural_edges/b622e76deceb419ab9c5aa80a8f8280c/f0000_pairs.npz": "cb2320d63ed533270b1623e9128399514c51774f0471b4a7a5adbf71ded1d6f4" }, "original_preservation": { "status": "PASS", "files": 4325, "all_sha256_unchanged": true }, "historical_task03e_sources": { "utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "visual/runtime/test/run_priority_fps_metric_control.py": "6c5e2373431ec7c7e390a7f77baa963ab2d649c2361b28c0f1553a542e20ac34", "visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "visual/runtime/test/test_priority_fps_metric_control.py": "34e0643471303d8f788f977f0bad7ae4829239c93e6c0af97ddbfe0ccc916b51", "visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522" } }, "reporting_source_sha256": { "visual/runtime/test/run_geometry_aware_sampling.py": "6fcfd638a929e793ba920297942f2b85eb6b00b066058dd0133d32a358648276", "visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f" }, "previous_run_files_before": { "experiments/2c3d733de35c4532b2b81a0a751b7ebf/attempt_failure.json": "2d8489eb8857c37a7c9a954d2aedf9346d473e1bd826ddd710af5f53ec829d7d", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/box_GT_auxiliary.png": "c602da201a9bc088847e9327f95a2bf4f8ee6f6c1567f2deaa3630be6b48e344", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/box_GT_auxiliary.png.tracking.json": "d7cf4ab124fd6d18bb05f83b29eadda82a053581c929b5878172fa8187930af1", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/candidate_3d_ecdf_tail.png": "54a9b838fc7128ab7c15ed145fb7ae3ab01bacc38c0a8f476bc50c58c989d429", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/candidate_3d_ecdf_tail.png.tracking.json": "fae9e38541b2fd11556e8ad7f2acca57896f9202caff99767fd24dd366c41bf8", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/candidate_XZ_coverage.png": "691ce0b1d4a587bdf3cb39cf83b9e036d8745056c1667f04c8e3d1f8f2d45c09", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/candidate_XZ_coverage.png.tracking.json": "4ff364302c5b04844e6a0ef6b5a5f84a9b5c69281c94c4da4a4323a8f657a461", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/compatibility.json": "b1d0539bdc9413196597b430567eae5d6f4126105faf366c027823459137692c", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/compatibility.json.tracking.json": "872b60defc574666b4578fb321af163bba8de0e4a215e8e9b60c3595f4573ca0", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/config.yaml": "ba1494d8a23de338afb4b2b8746275ce2e38b8a2c9e0a36b0c2ea9ad0b8bb2c9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.html": "8ec6cf74c6b0fb5d29601ccbebc6cbf2c656d844fa3a623269e5dc7fa9513954", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.html.tracking.json": "f0ef38938055e5d1771f242b0fd8b349f5828c605b4a2cb9ba02bba4a4390d77", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.json": "6230273ed917c7bcafc25a2f43a46d216a3c6b37b00aa3aa9d4c97d9f486fa1e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.json.tracking.json": "e965d628470bb1fa178bb3dfe97940976a1b7eba9f8334aabe6af82db2275dca", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.npz": "505329aaaab54bdd976a315454e4f5b8624f7a7b68e7e2016be99886e020e2ce", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/geometry_aware_sampling.npz.tracking.json": "79a03c846772e14989421e90b36d81be37e619417c29ab208483f39f6cf0ab39", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/git_start.diff": "2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/git_start.diff.tracking.json": "228310e628684141e11672bcbf491f0e89d8ae3fc9d838a1d2d3075430401719", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/git_status.txt": "c738ff3093e8a88dc1e204a503bc211627dc0fc803b8347e663feb96a0f54699", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/git_status.txt.tracking.json": "f6fa3be3efc826073fec68fe3e80be6e3e4055f73b37a6ec2792799d73474c42", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/implementation.patch": "aabf80ef55c629d5c6ce8afc07907245e0ad7e5cd27c5772e4e3c3abfc7229af", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/implementation.patch.tracking.json": "d1d89e65c938036f42b53cdb6a263fca6299f7dd2c3df43ba5b75de29011514e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/independent_regions.png": "2164f666f870d868b0464ba58f6c4c4646e15ea89cacc328166e0ab35bd00817", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/independent_regions.png.tracking.json": "53d24e379051a560080f8fa85d77031c02ff2cb90de5b095b12f9e5d9ff192e5", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/manifest.json": "a0def1fa9ae3d43d0ca6ba2084e8523f851e174b7a6e6d3b6abd6ffeb5509f0e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/metadata.json": "cd427fb57f13005aed9451ec7d17ebfbbaed9c9673d426f3fb3cc245ad8f7d9e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/metrics.json": "37517e5f3dc66819f61f5a7bb8ace1921282415f10551d2defa5c3eb0985b570", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/original_hashes.json": "d33c7ad487896020a741b982023b5ef87298bdb1a26de6cd8d2bacd6373f6eca", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/original_hashes.json.tracking.json": "c3d306296d04aadb8cd93506cf104250cab05d1eb1ac42d72689482271872938", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_and_selection.png": "34fffe7fbc42ba52159cb5743b92009c3e1f2a4d67278ece35414d9f7d5eaecc", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_and_selection.png.tracking.json": "6a96cd881fead9fb74c1dffe201a21065f996ce20670e7c43bdc9844a04e9493", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_diagnostics_before_selection.json": "875b83c1132752313b12b50ae8b6957c9de11a519bee06ce92073b33bd34ade2", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_diagnostics_before_selection.json.tracking.json": "de499e8cd55b6a46e9574b693cffac8b9007c2915d8191ebb53194e05fb1aacd", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_quota.png": "ba0d444d046db5cc84fce2a957b6fa27c4e0977cc52388bb81c5fdc29c00f101", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/patch_quota.png.tracking.json": "8d49e44d0544f22bf75c6a9ca2b42b60992efaf3309c868f34a55b08ef59c68b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/peg_GT_auxiliary.png": "7b9cbf88d81131233518433afb3318958353668a6912935d05616afca8450c37", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/peg_GT_auxiliary.png.tracking.json": "b721b24162492377a91a2452430f8982d3d648abb62a7fd7ed81a2a82b988cfe", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/preregistered_config.json": "ba1494d8a23de338afb4b2b8746275ce2e38b8a2c9e0a36b0c2ea9ad0b8bb2c9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/preregistered_config.json.tracking.json": "699f2c1f7f7786c59e9bc012bceaba22625c778eb649efd69965a62d5c83416e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/report.md": "1ff3e91546d35ba17d82119dca0b4398b14ab558b4dbb307b6b2f07abfee071d", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/report.md.tracking.json": "86fe41ec2d0eda0d0c43a525e9671e3a8ba2ad74ac524e9139ebbf894675f9f6", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/selection_before_gt.npz": "7978ecae2395dee91aa7ab70c193fee4149cfeb16f08bf9b505259d8276efc59", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/selection_before_gt.npz.tracking.json": "6f3d4a04d316e3efa7df15bb36af73a66c1cb4101084c49f6bc58200cba81c47", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_hashes.json": "ef02629ad7fa38e1891aa0215b605ebfff07edbf020f511a0def1af1be95f8fb", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_hashes.json.tracking.json": "c457fae8cf6a86d95c56e312c770bf5f9e3adaff46caa662ec82b3f69cb3891c", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/utils/experiment_artifacts.py.tracking.json": "a394d893334899be9cf2513709b6def94b9b752a2d3c75ef74fbcec05a87656b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/utils/experiment_logger.py.tracking.json": "00b402f7fcd0b28c83b3d95fa8b118bc48181d3b6057911f9bf721ecc0681269", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/edge_evidence.py.tracking.json": "7300858b9cf9cfc4b21d5cfe9a740c3d8186ca12ac6a4e775587afef3022296e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/geometry.py.tracking.json": "3fbdb1f86d10cb0df0d10b966ba042f0c8adcf7bf39df1ab72fdc640ce5dbd3e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/grounding.py.tracking.json": "0cdeaf8d5cebc60e0a2224a2d0fb29fba88e4510965861f61fc2e9614df9d477", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/initialization.py.tracking.json": "277a9f80755d891762c65c4b9edcfe0787d4976862bf3d62b52729916b1c760c", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/normal_estimators.py.tracking.json": "5c5b37ed06dd670af5462d32cc0297365b69a093a5f105e3367c62b21d385538", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/pca.py.tracking.json": "65c92a98fe175fa3a20625023511c613666a1b9f8abbd5521b66a118d6ba02dd", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/rgbd.py.tracking.json": "1637044d27dfd7696b556a749600c151fa29e2bb970726d6ef9491f54b4c8c0b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/sampling.py.tracking.json": "419d250f7789abd5dbd016111999486a2f73b5adcc12576ee0d4b6eaa2ad0c05", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/benchmark_pca_cuda.py.tracking.json": "038ead3ddef46440597169c4a327fafdb34760c0ca4922e48f3a6760c278c9ac", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/benchmark_pca_streaming.py.tracking.json": "f8b583d5ae6fa25a7274257ab5c5b3ae649054485e96f930a1b83304e488b817", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/normal_diagnostics.py.tracking.json": "d353e30b5023bdf14545a140a7780172bcf9f26cf714b358af3b097178b9aecc", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/normal_estimators.py.tracking.json": "513542fb88aef9273b76a01cedb63a57e6f5985c5db08a60c3aaaf4b410e3b10", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/pca_optimized.py.tracking.json": "84cf192ad0303f3b9f2e44aab0f3a5ddbfad993299c7c09c686171ba07937c09", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/pca_torch.py.tracking.json": "3693fb8055c262e0cf6f32a9694ed67f9de9f753366c139ab174fe8a0c7ca338", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/pca_triton.py.tracking.json": "80d8abc2bce05e6b567ba725d2666d03fb673dc1a333cbc57181f833476243a3", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_adaptive_node_budget.py.tracking.json": "b1b1c820c3b4cb34757fdb692a6610a7f454eaf7479eea704ca6cd2d0b240e5f", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_geometry.py.tracking.json": "b765679dd0985785b5f0024841e1e9589cf5f8e6ad747832a6a980715f4c21bd", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_geometry_aware_sampling.py": "011fe12780cb14ed6ca52c3bffeeb19165164085c948d5c94cb8568ec02a6837", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_geometry_aware_sampling.py.tracking.json": "3b0e442393f474ce2388adce83eabcb21136fab9e947c952efa05db0056d2616", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_grounding.py.tracking.json": "8283617c8eaf5a6a4ffc50cdb7d2de3f64be54d77fbf447ed0deb53c2208e5f1", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_local_structural_sampling.py": "4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_local_structural_sampling.py.tracking.json": "8206588dc843145f24f35766951b6ef836db2c6182232f37d6ca826f6c6a3b3f", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_normal_comparison.py.tracking.json": "c604a39898e1e27d67df9b6e2288eafb1d6a738609d53ecdf68f8d90844a29b4", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_normal_diagnostics.py.tracking.json": "ecbe38bbd2226975b6d60aff76ec9daccc0fcfa0c82b54daae59a533f643df72", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_pca_optimization.py.tracking.json": "c57b3de08644ead270da977e8fb1b01849fb1392efb35b3f87e051f1d70613bc", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_priority_fps_metric_control.py": "c01afcd516f3cf2b1f1d34d5878be2376e849e50dc7c1b809854d8f5231d1ca9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_priority_fps_metric_control.py.tracking.json": "9886a1ba9ed11d2b9b09be51e0717dd0053a0957fe711263077fd8ddbeece64c", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_priority_fps_seed_control.py.tracking.json": "490b11b298b86204ca3dc4a9d0cb58d9eb14472d54289b04808f6202ff56c507", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_priority_fps_trace.py.tracking.json": "5e81416ace87d9aa03947dca76c31f281298e9306d989b1aa0128ecdd3645188", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_rgbd.py.tracking.json": "419f76f9f206f0d57db6bfe3ad327a36121913f1c5b616a2e1c38f7c68abfbda", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_rim_bottleneck.py.tracking.json": "7fc116b02656d39974b53d71b440c978719a27b6611ab42a6ea570b98f861933", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_sampling.py.tracking.json": "06c9871b9484dd34aad6f27c3b6b1be371e105d76c301e12f84b8831dd01c559", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_structural_edges.py.tracking.json": "6c90fe83a480daa2c9de67b0c488cf20a663024aaf5d1eac4e3d474cfe376ed8", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/run_tracking.py.tracking.json": "166f0b6c7606f58384f8249bd6bc4c2ecae1ecb09f5103b13b9b5e1fa6f287f0", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/sampling_evaluation.py.tracking.json": "4a0cc046b3ffccf99bbc9f5f7c0429e9d858c06d4489ca70773f625af872385c", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/sampling_plots.py.tracking.json": "9d1ea76b1f6b4f9432688982de6b97c0f3f23347f73445576ccebfda5b8c1ef9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/structural_edges.py.tracking.json": "0977f384219137893a6fd81aee19978bae31f135f5acfd0117140535072234d2", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_adaptive_node_budget.py.tracking.json": "3699f37b442e255f1d48f58e842093c44b5760480b3f02ab4719e62e723fc830", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_geometry.py.tracking.json": "79d76515c536a6c99b14279dbd12d7b633ecd8d46b2cb1caf3ae595ed4451b7e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_geometry_aware_sampling.py.tracking.json": "f02d00e0560cf77aee5dd0f92624428ae07f65b58d9d2f33cdad9f06e93a8fc3", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_geometry_evaluation.py.tracking.json": "42f46bb59e3f1190112b4f5db2f3a7cde24fa46802357c37385315b311a7f68c", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_initialization.py.tracking.json": "6816e907b39ec78a9a6e9ec4e8eec026321355f5b58098e30403684fa7c20dbd", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_local_structural_sampling.py": "d6758da4be04c7622a40ed9226503e6d2884de89f08992fc731200c8d21d7994", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_local_structural_sampling.py.tracking.json": "f49eee156fea21c11e45a2661eab6c68a81c08bb9b28308e0037cb6821b8e219", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_normal_comparison.py.tracking.json": "1975bd0ae37a8413cdd44c3812221b47b86df24bf3006dddc0f4ae6a69a5a3ec", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_normal_diagnostics.py.tracking.json": "96bf60fcef0f638364e5e3aeaed167c15c30c7d0f31a536f3bdb2ec5ac87b5be", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_pca_optimized.py.tracking.json": "4c69dd9b71fe608705591477002b550a8902896c154c810f94b6ce5d511f0557", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_priority_fps_metric_control.py": "92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_priority_fps_metric_control.py.tracking.json": "c5c4bf8b4b29111052564dc218ec14be0c96b341b6f27474f2b4e601f402486a", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_priority_fps_seed_control.py.tracking.json": "d6bc1def4346783a9a850c09c3c8bc686d8ddb039eac82f0b45d7b9c72abe2b4", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_priority_fps_trace.py.tracking.json": "69dd8d931739a1be057cd9f931215ac156d078080598f8622fd95a56c3903009", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_rgbd.py.tracking.json": "b17a4acfca5494988a40f569f10ed90160b1b55eea6224f6f1e2fda3d651aee9", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_rgbd_evaluation.py.tracking.json": "041a9969a90bd00e90ee5d0831413e642b7458e226e21d4ddc22cf26abdfb275", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_sampling.py.tracking.json": "9aff0b136d92319cf56af1de7e67d38011a42e6a2a561707bf1b0d9cd86351bd", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_sampling_evaluation.py.tracking.json": "eb255af9dab05812a9b28661e82c54bfb8d8710a462fbbb7129a63ed998179b5", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_sampling_geometry.py.tracking.json": "d36f626b3de4b9260323a3a2e0592f42bd83936b1cd4a1b4b321b836104e42d5", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/test/test_structural_edges.py.tracking.json": "e552859165607d73896e01f6d1c3a70a60350061105d96ad5c9e43a8c6f7452e", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/source_snapshot/visual/runtime/tracking.py.tracking.json": "37f78e5b71898c3fb01669f16cc09f910fbf64a5f4a77c787a14a9451ab78602", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/surface_depth_tradeoff.png": "4b435cbe234dafea7403249306348388206d4afd5e391c613a4b4392ffb5fef5", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/surface_depth_tradeoff.png.tracking.json": "52da4d706a5ae6f4669c7a04c05a7ac4588d50fc912202db8c948d2f81f1a3e6", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/tests.log": "c8bd75d18bb1b302bfc155e0b54afac8db076df823c692250a7abe0544b21877", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/tests.log.tracking.json": "2c4a42d03605b3adbdcfaf1210e120939a36744146ac848a3b04b7a031b4e2db", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/verification.json": "4fbb605112f319103364b475ad185d07fdca56cd64e81248b7da0490be0008d6", "experiments/2c3d733de35c4532b2b81a0a751b7ebf/verification.json.tracking.json": "d49f9883912e5e3acd8fa7e759d35f4c836a9ea654d667b8399ac3db81bd62fa" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""PCA5 optimization: paired fidelity, fixed GT evaluation and CPU latency.
Keeps existing outputs and estimators. Excludes initial grounding by using thesame saved masks; tracker-inclusive timing is a separate explicit benchmark."""from __future__ import annotations
import argparsefrom dataclasses import replacefrom pathlib import Pathimport platformfrom time import perf_counterimport sys
import numpy as np
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.geometry import GeometryFrame, GeometryParameters, build_organized_geometry, compute_geometric_featuresfrom visual.runtime.rgbd import iter_saved_rgbd, PEGfrom visual.runtime.test.normal_estimators import local_planefrom visual.runtime.test.normal_diagnostics import angular_error, quantize, rays, stats, synthetic_casefrom visual.runtime.test.pca_optimized import process_optimizedfrom visual.runtime.test.run_normal_comparison import Pool, real_truth, save_json
METHODS = ('reference_pca5', 'optimized_eigh', 'optimized_analytic', 'optimized_parallel')
def reference(frame): start = perf_counter(); geometry = build_organized_geometry(frame); t1 = perf_counter() p = GeometryParameters() normals = {i: local_plane(geometry, i, 5, p) for i in geometry.object_masks}; t2 = perf_counter() features = {i: compute_geometric_features(geometry, i, *normals[i], p) for i in geometry.object_masks}; end = perf_counter() return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, dict(geometry=(t1-start)*1000, normals=(t2-t1)*1000, discontinuity_features=(end-t2)*1000, total=(end-start)*1000))
def run_method(frame, method, profile=None): if method=='optimized_parallel':return process_optimized(frame,solver='analytic',profile=profile,parallel=True) return reference(frame) if method=='reference_pca5' else process_optimized(frame, solver=method.removeprefix('optimized_'), profile=profile)
def fidelity(expected, actual): row = dict(validity_differences=0, other_field_differences=0, normal_max_deg=0., variation_max_deg=0., threshold_flips={str(t): 0 for t in (5, 10, 20, 30)}) np.testing.assert_array_equal(expected.geometry.xyz, actual.geometry.xyz) for oid, a in expected.objects.items(): b = actual.objects[oid] row['validity_differences'] += int(np.count_nonzero(a.normal_valid != b.normal_valid)) row['validity_differences'] += int(np.count_nonzero(a.normal_variation_valid != b.normal_variation_valid)) common = a.normal_valid & b.normal_valid if common.any(): row['normal_max_deg'] = max(row['normal_max_deg'], float(angular_error(a.normals[common], b.normals[common]).max())) vv = a.normal_variation_valid & b.normal_variation_valid if vv.any(): row['variation_max_deg'] = max(row['variation_max_deg'], float(np.rad2deg(np.abs(a.normal_variation_rad[vv]-b.normal_variation_rad[vv])).max())) for key in a.__dataclass_fields__: if key in ('normals', 'normal_variation_rad', 'normal_valid', 'normal_variation_valid'): continue aa, bb = getattr(a, key), getattr(b, key) equal = (aa == bb) | (np.isnan(aa) & np.isnan(bb)) if np.issubdtype(aa.dtype, np.floating) else aa==bb row['other_field_differences'] += int(np.count_nonzero(~equal)) for t in (5, 10, 20, 30): row['threshold_flips'][str(t)] += int(np.count_nonzero(vv & ((np.rad2deg(a.normal_variation_rad)>t) != (np.rad2deg(b.normal_variation_rad)>t)))) return row
def combine_fidelity(rows): return dict(samples=len(rows), validity_differences=sum(r['validity_differences'] for r in rows), other_field_differences=sum(r['other_field_differences'] for r in rows), normal_max_deg=max((r['normal_max_deg'] for r in rows), default=0.), variation_max_deg=max((r['variation_max_deg'] for r in rows), default=0.), threshold_flips={str(t):sum(r['threshold_flips'][str(t)] for r in rows) for t in (5, 10, 20, 30)})
def synthetic_observations(k): for kind in ('front', 'tilted', 'crease', 'step'): for z in (.2, .25, .35, .6, 1.): for phase in (0., .00025, .0005, .00075): f, truth, regions = synthetic_case(kind, k, z0=z, phase_m=phase) for mode in ('float', 'floor', 'nearest'): yield dict(geometry=kind, z0_m=z, phase_m=phase, quantization=mode), f if mode=='float' else replace(f, depth=quantize(f.depth, mode)), truth, regions for z in (.25, .6): for slope in (.2, .8): for azimuth in (0, 45, 90, 135): f, _, regions = synthetic_case('tilted', k, z0=z, phase_m=.00025) a, b = slope*np.cos(np.deg2rad(azimuth)), slope*np.sin(np.deg2rad(azimuth)) ray = rays(f.depth.shape, k) depth = ((z+.00025)/(1-a*ray[..., 0]-b*ray[..., 1])).astype(np.float32) f = replace(f, depth=depth) truth = np.broadcast_to(np.array([a, b, -1.])/np.sqrt(a*a+b*b+1), (*depth.shape, 3)) for mode in ('float', 'floor', 'nearest'): yield dict(geometry='direction', z0_m=z, slope=slope, azimuth_deg=azimuth, quantization=mode), f if mode=='float' else replace(f, depth=quantize(f.depth, mode)), truth, regions
def plot(output, frame, results): import matplotlib.pyplot as plt fig, axes = plt.subplots(2, len(METHODS)+1, figsize=(4*(len(METHODS)+1), 9), constrained_layout=True) axes[0, 0].imshow(frame.rgb); axes[0, 0].set_title('Same observation / saved tracking masks') axes[1, 0].imshow(frame.rgb); axes[1, 0].set_title('Normal valid=yellow / invalid=dark') for col, method in enumerate(METHODS, 1): var = np.full(frame.depth.shape, np.nan); valid = var.copy() for f in results[method].objects.values(): var[f.normal_variation_valid] = np.rad2deg(f.normal_variation_rad[f.normal_variation_valid]) valid[f.valid_points] = f.normal_valid[f.valid_points] axes[0, col].imshow(var, cmap=plt.get_cmap('turbo').with_extremes(bad='#cccccc'), vmin=0, vmax=45) axes[1, col].imshow(valid, cmap=plt.get_cmap('viridis').with_extremes(bad='#cccccc'), vmin=0, vmax=1) axes[0, col].set_title(method+' variation (0-45 deg)') axes[1, col].set_title(method+' normal validity') for ax in axes.ravel(): ax.axis('off') fig.suptitle(f'Source {frame.source_frame}: same PCA5 support; implementation optimization only') fig.savefig(output/f'f{frame.source_frame:04d}.png', dpi=120); plt.close(fig)
def evaluate(input_path, masks_path, output_root, *, repeats=5, synthetic=True): if repeats < 1: raise ValueError('repeats must be positive') input_path, masks_path = Path(input_path).resolve(), Path(masks_path).resolve() frames = list(iter_saved_rgbd(input_path, masks_path)) with np.load(input_path, allow_pickle=False) as a: gt = {k:a[k] for k in ['base_camera/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed']} sources = [Path(__file__), Path(__file__).with_name('pca_optimized.py'), Path(__file__).with_name('pca_torch.py'), Path(__file__).with_name('normal_estimators.py')] cfg = dict(task='pca5_optimization', input=str(input_path), masks=str(masks_path), repeats=repeats, methods=list(METHODS), input_sha256=digests(input_path)[1], masks_sha256=digests(masks_path)[1], source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in sources}, initial_grounding_excluded=True, tracking_included=False, final_graph_handoff_implemented=False, cpu_normal_target_p95_ms=10, cpu_geometry_target_p95_ms=25, final_target_period_ms=50, same_neighbourhood=True, pca_dtype='float64', synthetic=synthetic, python=platform.python_version(), platform=platform.platform(), numpy=np.__version__, timing='one warmup each, round-robin order, full per-method build/normal/features, no I/O/GT/metrics') with ExperimentLogger(team='visual', config=cfg, seed=int(gt['seed']), model='pca5_optimization', job_type='evaluate') as logger: output = Path(output_root)/logger.run_id; output.mkdir(parents=True, exist_ok=False) print('Output:',output,flush=True) source_dir=output/'source'; source_dir.mkdir() for p in sources: (source_dir/p.name).write_bytes(p.read_bytes()) for method in METHODS: run_method(frames[0], method) pool, records = Pool(), [] all_fidelity = {m:[] for m in METHODS[1:]} timings = {m:[] for m in METHODS} profiles = [] for idx, frame in enumerate(frames): results = {} for repeat in range(repeats): offset = (idx+repeat)%len(METHODS) for method in METHODS[offset:]+METHODS[:offset]: p = {} if method=='optimized_analytic' and repeat==0 else None result = run_method(frame, method, profile=p) timings[method].append(dict(source_frame=frame.source_frame, repeat=repeat, **result.timings_ms)) if repeat==0: results[method]=result if p is not None: profiles.append(dict(source_frame=frame.source_frame, objects=p)) truths, regions, _ = real_truth(frame, results['reference_pca5'], gt, 'base_camera') record = dict(source_frame=frame.source_frame, fidelity={}, metrics={}) for method in METHODS[1:]: f = fidelity(results['reference_pca5'], results[method]); record['fidelity'][method]=f; all_fidelity[method].append(f) for method in METHODS: rows = {} for name, oid in [('peg',0),('box',1)]: for key, region in regions[name].items(): rows[name+'/'+key] = pool.add(method+'/'+name+'/'+key, results[method].objects[oid], region, truths[name]['normals'] if key.startswith('plane_') else None) record['metrics'][method]=rows if frame.source_frame in (0, 15, 45, 80, 120): plot(output, frame, results) records.append(record) if idx==0 or (idx+1)%20==0: print('Real frames',idx+1,'/',len(frames),flush=True) summary = pool.summary() syn_rows=[]; syn_fidelity={m:[] for m in METHODS[1:]} if synthetic: from visual.runtime.test.run_normal_comparison import response_metrics for idx, (condition, frame, truth, regions) in enumerate(synthetic_observations(frames[0].intrinsic)): results = {m:run_method(frame,m) for m in METHODS} row=dict(condition=condition, methods={}, fidelity={}) for method in METHODS[1:]: f=fidelity(results['reference_pca5'],results[method]);syn_fidelity[method].append(f);row['fidelity'][method]=f for method in METHODS: row['methods'][method]={key:response_metrics(results[method].objects[PEG],region,truth) for key,region in regions.items()} syn_rows.append(row) if (idx+1)%48==0: print('Synthetic conditions',idx+1,'/288',flush=True) latency = {m:{k:stats([r[k] for r in timings[m]]) for k in ['geometry','normals','discontinuity_features','total']} for m in METHODS} fidelity_summary={m:combine_fidelity(all_fidelity[m]) for m in METHODS[1:]} syn_summary={m:combine_fidelity(syn_fidelity[m]) for m in METHODS[1:]} for part in [fidelity_summary, syn_summary] if synthetic else [fidelity_summary]: for r in part.values(): if r['validity_differences'] or r['other_field_differences'] or r['normal_max_deg']>.001 or r['variation_max_deg']>.001: raise AssertionError('same-estimator fidelity tolerance failed') data=dict(run_id=logger.run_id,config=cfg,evaluated_frames=len(frames),latency_ms=latency, fidelity=fidelity_summary,summary=summary,frames=records,profile=profiles,timing_samples=timings, synthetic=dict(conditions=len(syn_rows),fidelity=syn_summary,cases=syn_rows)) save_json(output/'optimization.json',data) body=''.join(f'<p><img style="width:100%" src="{p.name}"></p>' for p in sorted(output.glob('*.png'))) (output/'optimization.html').write_text(f'<!doctype html><meta charset="utf-8"><title>PCA5 optimization</title><h1>PCA5 optimization</h1><p>Run {logger.run_id}. Initial grounding excluded; saved tracking masks. Final Graph handoff is not implemented. <a href="optimization.json">Metrics, fidelity, latency, source hashes</a>.</p>'+body) for path in output.iterdir(): if path.is_file(): logger.link_output(path,kind='metrics' if path.suffix=='.json' else 'reports') logger.log(latency,prefix='eval/pca5_optimization/latency_ms');logger.log(fidelity_summary,prefix='eval/pca5_optimization/fidelity') logger.record(evaluation_device='cpu',gpu_executed=False,initial_grounding_excluded=True,evaluated_frames=len(frames)) return output
def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') p.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') p.add_argument('--out',type=Path,default=REPO/'visual/results/pca_optimization') p.add_argument('--repeats',type=int,default=5) p.add_argument('--no-synthetic',action='store_true') a=p.parse_args();print(evaluate(a.input,a.masks,a.out,repeats=a.repeats,synthetic=not a.no_synthetic))
if __name__=='__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Current-observation Structural priority / Surface FPS, internal NumPy metadata.
No GT, cache, final node features, graph edges or Vision--Graph packaging. XYZremains in the source CV-camera frame. Selection roles are not semantic types."""from __future__ import annotations
from dataclasses import dataclass, fieldfrom numbers import Integralfrom time import perf_counter
import numpy as np
from visual.runtime.geometry import ( GeometryFrame, GeometryParameters, estimate_surface_normals,)from visual.runtime.pca import build_geometry, cropped_features, local_plane_optimizedfrom visual.runtime.normal_estimators import finite_differencefrom visual.runtime.edge_evidence import PairEvidence, pair_evidencefrom visual.runtime.rgbd import PEG, BOX, TrackedRGBDFrame
METHODS = ('S0', 'S1', 'S2', 'S3', 'S4')
def _integer(value, name): if not isinstance(value, Integral) or isinstance(value, (bool, np.bool_)) or value < 0: raise ValueError(f'{name} must be a nonnegative integer')
@dataclass(frozen=True)class SamplingConfig: """Experimental defaults, not adopted architecture/hyperparameters.
Reserve minimums first, then apportion remaining capacity by observed point counts (or their square roots). Largest remainder, capped by availability; exact ties use ascending object ID. Structural slots are a GLOBAL maximum floor(num_points*ratio), including independently capped S4 depth-only slots. """ num_points: int = 256 structural_ratio: float = .25 min_points: tuple[int, int] = (16, 16) allocation: str = 'observed_points' seed: int = 0 orientation_threshold_deg: float = 20. depth_priority_fraction: float = .25 sampling: str = 'fps'
def __post_init__(self): _integer(self.num_points, 'num_points'); _integer(self.seed, 'seed') if len(self.min_points) != 2: raise ValueError('min_points must contain Peg and Box minimums') for n in self.min_points: _integer(n, 'object minimum') if sum(self.min_points) > self.num_points: raise ValueError('sum of object minimums exceeds num_points') for name in ('structural_ratio', 'depth_priority_fraction'): x = getattr(self, name) if not np.isfinite(x) or not 0 <= x <= 1: raise ValueError(f'{name} must be finite in [0,1]') if not np.isfinite(self.orientation_threshold_deg) or not 0 <= self.orientation_threshold_deg <= 180: raise ValueError('orientation threshold must be in [0,180] degrees') if self.allocation not in ('observed_points', 'sqrt_observed_points'): raise ValueError('unknown allocation rule') if self.sampling != 'fps': raise ValueError('only fps sampling is supported')
def allocate_budget(total, capacities, minimums=(0, 0), weights=None): """Capped proportional integer apportionment, deterministic and availability aware.""" _integer(total, 'budget') cap = np.asarray(capacities) mins = np.asarray(minimums) if cap.shape != (2,) or mins.shape != (2,): raise ValueError('expected two object counts') for x in (*cap, *mins): _integer(x, 'capacity/minimum') if mins.sum() > total: raise ValueError('minimums exceed total budget') cap, mins = cap.astype(np.int64), mins.astype(np.int64) weight = cap.astype(float) if weights is None else np.asarray(weights, float) if weight.shape != (2,) or not np.isfinite(weight).all() or (weight < 0).any(): raise ValueError('weights must be two finite nonnegative values') out = np.minimum(cap, mins) left = min(total, int(cap.sum()))-int(out.sum()) while left: room = cap-out w = np.where(room > 0, weight, 0) if not w.any(): w = (room > 0).astype(float) quota = left*w/w.sum() take = np.minimum(room, np.floor(quota).astype(np.int64)) out += take; left -= int(take.sum()) # Largest fractional remainder; saturated objects are skipped. If a # quota exceeded capacity, the next pass redistributes the surplus. order = np.argsort(-(quota-np.floor(quota)), kind='stable') for i in order: if out[i] < cap[i] and left: out[i] += 1; left -= 1 return out
def fps_indices(points, count, *, seed=0, initial=()): """Legacy pointcloud.fps distance update, returning unique source row indices.
No random pre-reduction. Uniform seeded first row; argmax ties choose the first source row. An initial selection seeds distances for Surface coverage. All initial rows precede newly selected rows. Even coincident XYZ is never selected twice by row index. Computes squared distances in float64. """ _integer(count, 'FPS count'); _integer(seed, 'FPS seed') xyz = np.asarray(points, dtype=float) if xyz.ndim != 2 or xyz.shape[1] != 3 or not np.isfinite(xyz).all(): raise ValueError('FPS requires finite [N,3] observed coordinates') initial = np.asarray(initial, dtype=np.int64) if initial.ndim != 1 or len(np.unique(initial)) != len(initial) or ((initial < 0) | (initial >= len(xyz))).any(): raise ValueError('initial FPS rows must be distinct valid indices') count = min(count, len(xyz)) if len(initial) > count: raise ValueError('initial rows exceed FPS count') if not count: return np.empty(0, np.int64) chosen = list(initial) distance = np.full(len(xyz), np.inf) x, y, z = (np.ascontiguousarray(xyz[:, i]) for i in range(3)) def update(j): np.minimum(distance, (x-x[j])**2+(y-y[j])**2+(z-z[j])**2, out=distance) distance[j] = -np.inf for j in chosen: update(j) if not chosen: chosen.append(int(np.random.default_rng(seed).integers(len(xyz)))) update(chosen[-1]) while len(chosen) < count: j = int(distance.argmax()); chosen.append(j); update(j) return np.asarray(chosen, np.int64)
@dataclass(frozen=True)class SamplingEvidence: """Detector output before thresholding. Contains observations only.""" frame: GeometryFrame pairs: dict[int, PairEvidence] estimator: str timings_ms: dict[str, float]
@dataclass(frozen=True)class ObjectCandidates: """Only valid observed rows, in original raster order; all evidence stays aligned.""" flat_index: np.ndarray points: np.ndarray metadata: dict[str, np.ndarray]
@dataclass(frozen=True)class SampledPoints: """Internal selection, variable N; no padding, no final GNN feature encoding.
priority_selected / depth_priority_selected record selection paths, whereas metadata['structural_candidate'] records detector eligibility. Surface FPS may select more detector candidates than the structural priority slot cap. """ source_frame: int camera: str points: np.ndarray pixels_vu: np.ndarray flat_index: np.ndarray object_id: np.ndarray priority_selected: np.ndarray depth_priority_selected: np.ndarray metadata: dict[str, np.ndarray] object_budgets: dict[int, int] counts: dict[int, dict[str, int]] timings_ms: dict[str, float] = field(default_factory=dict)
def extract_sampling_evidence(frame: TrackedRGBDFrame, estimator='pca5', parameters=GeometryParameters()): """Reuse Task02 estimators and pair operator; optimized PCA5 analytic solver.""" if estimator not in ('baseline', 'fd2', 'pca5'): raise ValueError('unknown normal estimator') t0 = perf_counter(); geometry = build_geometry(frame); t1 = perf_counter() normals = {} for oid in (PEG, BOX): if estimator == 'baseline': normals[oid] = estimate_surface_normals(geometry, oid, parameters) elif estimator == 'fd2': normals[oid] = finite_difference(geometry, oid, 2, parameters) else: normals[oid] = local_plane_optimized(geometry, oid, parameters, solver='analytic') t2 = perf_counter() features = {i: cropped_features(geometry, i, *normals[i], parameters) for i in (PEG, BOX)} t3 = perf_counter() pairs = {i: pair_evidence(geometry, i, *normals[i], parameters) for i in (PEG, BOX)} t4 = perf_counter() timing = dict(geometry=(t1-t0)*1000, normals=(t2-t1)*1000, features=(t3-t2)*1000, pair_evidence=(t4-t3)*1000, extraction_total=(t4-t0)*1000) result = GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timing) return SamplingEvidence(result, pairs, estimator, timing)
def extract_candidates(evidence: SamplingEvidence, config: SamplingConfig, method='S3'): """Threshold at observed pixels; boundary flags alone never imply eligibility.""" if method not in METHODS: raise ValueError('unknown sampling method') expected = dict(S1='baseline', S2='fd2', S3='pca5', S4='pca5') if method in expected and evidence.estimator != expected[method]: raise ValueError('method and normal estimator disagree') g = evidence.frame.geometry result = {} for oid in (PEG, BOX): idx = np.flatnonzero(g.observed_mask(oid)) f = evidence.frame.objects[oid] maps = evidence.pairs[oid].candidates(config.orientation_threshold_deg) metadata = {name: getattr(f, name).reshape((-1, 3) if name == 'normals' else (-1,))[idx].copy() for name in f.__dataclass_fields__} metadata.update({f'{name}_evidence': m.ravel()[idx] for name, m in maps.items() if name != 'union'}) orientation = maps['orientation'].ravel()[idx] depth_only = maps['depth'].ravel()[idx] & ~orientation metadata.update(orientation_score_deg=np.rad2deg(f.normal_variation_rad.ravel()[idx]), orientation_candidate=orientation, depth_only_candidate=depth_only, structural_candidate=orientation | (depth_only if method == 'S4' and config.depth_priority_fraction > 0 else False)) result[oid] = ObjectCandidates(idx, g.xyz.reshape(-1, 3)[idx].copy(), metadata) return result
def sample_points(evidence: SamplingEvidence, config=SamplingConfig(), *, method='S3'): """Object budgets -> Structural FPS -> remaining-support FPS seeded by priority.""" t0 = perf_counter(); objects = extract_candidates(evidence, config, method); t1 = perf_counter() available = np.array([len(objects[i].points) for i in (PEG, BOX)]) weights = np.sqrt(available) if config.allocation == 'sqrt_observed_points' else available budgets = allocate_budget(config.num_points, available, config.min_points, weights) cap = int(np.floor(config.num_points*config.structural_ratio)) if method != 'S0' else 0 capacities = np.array([min(budgets[i], int(objects[i].metadata['structural_candidate'].sum())) for i in (PEG, BOX)]) slots = allocate_budget(cap, capacities, weights=budgets) depth_cap = int(np.floor(cap*config.depth_priority_fraction)) if method == 'S4' else 0 depth_capacity = [min(slots[i], int(objects[i].metadata['depth_only_candidate'].sum())) for i in (PEG, BOX)] depth_slots = allocate_budget(depth_cap, depth_capacity, weights=budgets) t2 = perf_counter() selections, priority_sizes, depth_sizes = {}, {}, {} for i in (PEG, BOX): obj = objects[i]; m = obj.metadata # Each object always uses its own stream, invariant to missing other objects. seed = int(np.random.SeedSequence([config.seed, i]).generate_state(1)[0]) oi = np.flatnonzero(m['orientation_candidate']) di = np.flatnonzero(m['depth_only_candidate']) # Unused depth reservation can be used by orientation, never vice versa. dn = min(int(depth_slots[i]), len(di)) on = min(int(slots[i])-dn, len(oi)) orientation = oi[fps_indices(obj.points[oi], on, seed=seed)] depth = di[fps_indices(obj.points[di], dn, seed=seed,)] selections[i] = np.concatenate((orientation, depth)) priority_sizes[i], depth_sizes[i] = on+dn, dn t3 = perf_counter() for i in (PEG, BOX): seed = int(np.random.SeedSequence([config.seed, i]).generate_state(1)[0]) selections[i] = fps_indices(objects[i].points, int(budgets[i]), seed=seed, initial=selections[i]) t4 = perf_counter() flat, xyz, ids, priority, depth_priority, metadata = [], [], [], [], [], {} counts = {} for i in (PEG, BOX): obj = objects[i]; rows = selections[i]; n = len(rows); pn = priority_sizes[i]; dn = depth_sizes[i] flat.append(obj.flat_index[rows]); xyz.append(obj.points[rows]); ids.append(np.full(n, i, np.int64)) priority.append(np.arange(n) < pn) depth_priority.append((np.arange(n) >= pn-dn) & (np.arange(n) < pn)) for name, values in obj.metadata.items(): metadata.setdefault(name, []).append(values[rows]) counts[i] = dict(observed=len(obj.points), budget=int(budgets[i]), candidates=int(obj.metadata['structural_candidate'].sum()), priority=pn, orientation_priority=pn-dn, depth_priority=dn, surface_fps=n-pn, selected_candidates=int(obj.metadata['structural_candidate'][rows].sum()), selected=n) flat = np.concatenate(flat) timing = dict(candidate_selection=(t1-t0)*1000, budget_allocation=(t2-t1)*1000, structural_sampling=(t3-t2)*1000, surface_fps=(t4-t3)*1000) result = SampledPoints(evidence.frame.source_frame, evidence.frame.camera, np.concatenate(xyz), np.column_stack(np.unravel_index(flat, evidence.frame.geometry.valid_depth.shape)), flat, np.concatenate(ids), np.concatenate(priority), np.concatenate(depth_priority), {k: np.concatenate(v) for k, v in metadata.items()}, {i: int(budgets[i]) for i in (PEG, BOX)}, counts, timing) timing['sampling_total'] = (perf_counter()-t0)*1000 timing['geometry_sampling_total'] = evidence.timings_ms['extraction_total']+timing['sampling_total'] return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Analytical GT error cases and the two-artifact RGB-D evaluation workflow."""
import jsonimport osfrom pathlib import Pathimport reimport tempfileimport unittestfrom unittest.mock import patch
import imageio.v2 as imageioimport numpy as np
from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFramefrom visual.runtime.test.run_rgbd import compare_object, depth_colors, evaluate, summarizefrom utils.experiment_artifacts import plan_upload
def frame(predicted, depth=None): height, width = predicted.shape return TrackedRGBDFrame( source_frame=0, camera="test_camera", rgb=np.zeros((height, width, 3), dtype=np.uint8), depth=np.ones((height, width), dtype=np.float32) if depth is None else depth, intrinsic=np.array([[100, 0, 0], [0, 100, 0], [0, 0, 1]], dtype=np.float32), cam2world=np.eye(4, dtype=np.float32), tcp_pose=np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.float32), masks={PEG: predicted, BOX: np.zeros_like(predicted)}, frame_idx=0, timestamp=0.0, )
class RGBDEvaluationTest(unittest.TestCase): def test_perfect_mask_has_unit_iou_and_zero_surface_error(self): mask = np.zeros((3, 4), dtype=bool) mask[1, 1:3] = True result = compare_object(frame(mask), PEG, mask) for key in ("iou", "precision", "recall"): self.assertEqual(result[key], 1) for key in ("centroid_error_mm", "chamfer_mm", "predicted_to_gt_mm", "gt_to_predicted_mm"): self.assertEqual(result[key], 0)
def test_shifted_pixel_has_analytical_ten_mm_error(self): predicted = np.zeros((3, 4), dtype=bool) gt = np.zeros_like(predicted) predicted[1, 2] = gt[1, 1] = True observation = frame(predicted) observation.cam2world[:3, :3] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] observation.cam2world[:3, 3] = [1, 2, 3] result = compare_object(observation, PEG, gt) self.assertEqual(result["iou"], 0) self.assertAlmostEqual(result["chamfer_mm"], 10, places=3) self.assertAlmostEqual(result["centroid_error_mm"], 10, places=3)
def test_extra_pixel_checks_chamfer_normalization_and_direction(self): predicted = np.zeros((3, 4), dtype=bool) gt = np.zeros_like(predicted) predicted[1, 1:3] = True gt[1, 1] = True result = compare_object(frame(predicted), PEG, gt) self.assertEqual(result["iou"], 0.5) self.assertEqual(result["recall"], 1) self.assertAlmostEqual(result["predicted_to_gt_mm"], 5, places=4) self.assertEqual(result["gt_to_predicted_mm"], 0) self.assertAlmostEqual(result["chamfer_mm"], 2.5, places=4) self.assertAlmostEqual(result["centroid_error_mm"], 5, places=4)
def test_missing_predictions_are_not_hidden_as_zero_geometry_error(self): empty = np.zeros((3, 4), dtype=bool) gt = empty.copy() gt[1, 1] = True missed = compare_object(frame(empty), PEG, gt) absent = compare_object(frame(empty), BOX, empty) self.assertEqual(missed["iou"], 0) self.assertEqual(missed["recall"], 0) self.assertIsNone(missed["precision"]) self.assertIsNone(missed["chamfer_mm"]) self.assertIsNone(absent["iou"]) hallucinated = compare_object(frame(gt), PEG, empty) summary = summarize([ {"objects": {"peg": missed, "box": absent}}, {"objects": {"peg": hallucinated, "box": absent}}, ]) self.assertEqual(summary["peg"]["visible_iou"]["mean"], 0) self.assertEqual(summary["peg"]["missed_visible_frames"], 1) self.assertEqual(summary["peg"]["false_positive_invisible_frames"], 1) self.assertEqual(summary["peg"]["geometry_unavailable_visible_frames"], 1) self.assertEqual(summary["peg"]["chamfer_mm"]["count"], 0) self.assertIsNone(summary["peg"]["chamfer_mm"]["mean"])
def test_invalid_depth_is_excluded_and_video_uses_a_fixed_scale(self): depth = np.array([[0, -1, np.nan, np.inf], [0.5, 0.5, 1, 2]], dtype=np.float32) mask = np.ones(depth.shape, dtype=bool) result = compare_object(frame(mask, depth), PEG, mask) self.assertEqual(result["predicted_depth_pixels"], 4) self.assertEqual(result["predicted_valid_depth_fraction"], 0.5) self.assertEqual(result["chamfer_mm"], 0) colored = depth_colors(depth, 0.2, 1.5) self.assertFalse(colored[0].any()) np.testing.assert_array_equal(colored[1, 0], colored[1, 1]) np.testing.assert_array_equal(colored[1, 0], depth_colors(np.array([[0.5]]), 0.2, 1.5)[0, 0]) np.testing.assert_array_equal(colored[1, 3], depth_colors(np.array([[1.5]]), 0.2, 1.5)[0, 0]) self.assertFalse(np.array_equal(colored[1, 0], colored[1, 2]))
def test_report_and_decodable_video_follow_sparse_source_frames(self): count, height, width = 3, 24, 32 segmentation = np.zeros((count, height, width), dtype=np.int16) segmentation[:, 5:10, 3:8] = 18 segmentation[:, 10:16, 19:25] = 19 source = np.array([0, 2], dtype=np.int32) peg = segmentation[source] == 18 peg[1] = False # Only the second selected frame is missed. rgb = np.full((count, height, width, 3), 120, dtype=np.uint8) episode = { "test_camera/rgb": rgb, "test_camera/depth": np.ones((count, height, width), dtype=np.float32), "test_camera/intrinsic": np.repeat(np.array([[[100, 0, 16], [0, 100, 12], [0, 0, 1]]], dtype=np.float32), count, axis=0), "test_camera/cam2world": np.repeat(np.eye(4, dtype=np.float32)[None], count, axis=0), "test_camera/seg": segmentation, "tcp_pose": np.tile([0, 0, 0, 1, 0, 0, 0], (count, 1)).astype(np.float32), "frame_idx": np.array([10, 11, 12]), "timestamp": np.array([0, 0.05, 0.1]), "peg_id": 18, "box_id": 19, "seed": 42, } with tempfile.TemporaryDirectory() as root: root = Path(root) episode_path, masks_path = root / "episode.npz", root / "masks.npz" np.savez(episode_path, **episode) np.savez(masks_path, source_frame=source, peg=peg, box=segmentation[source] == 19) with patch.dict(os.environ, {"WANDB_MODE": "disabled", "EXPERIMENTS_DIR": str(root / "experiments")}): output = evaluate(episode_path, masks_path, camera="test_camera", output_root=root / "results") self.assertEqual({path.name for path in output.iterdir() if not path.name.endswith(".tracking.json")}, {"gt_report.html", "depth.mp4"}) report = (output / "gt_report.html").read_text() data = json.loads(re.search(r'id="evaluation-data">(.*?)</script>', report, re.S).group(1)) self.assertEqual([row["source_frame"] for row in data["frames"]], [0, 2]) self.assertEqual([row["frame_idx"] for row in data["frames"]], [10, 12]) self.assertEqual(data["gt_segmentation_ids"], {"peg": 18, "box": 19}) self.assertEqual(data["summary"]["peg"]["visible_iou"]["mean"], 0.5) self.assertEqual(data["summary"]["peg"]["chamfer_mm"]["count"], 1) self.assertEqual(data["summary"]["box"]["visible_iou"]["mean"], 1) self.assertEqual(data["video_fps"], 10) with imageio.get_reader(output / "depth.mp4") as video: self.assertEqual(video.count_frames(), 2) self.assertEqual(video.get_meta_data()["fps"], 10) rendered = video.get_data(0) self.assertEqual(rendered.shape[-1], 3) self.assertGreater(rendered.std(), 10) for artifact in ("gt_report.html", "depth.mp4"): link = json.loads((output / f"{artifact}.tracking.json").read_text()) self.assertEqual(link["run_id"], output.name) metadata = json.loads((root / "experiments" / output.name / "metadata.json").read_text()) self.assertEqual(metadata["team"], "visual") self.assertEqual(metadata["status"], "finished") self.assertEqual(metadata["evaluated_frames"], 2) plans = plan_upload(root / "experiments" / output.name, ["reports", "rollouts", "metrics"]) self.assertEqual(set(plans), {"rollouts"}) self.assertTrue(any(item.path.endswith("gt_report.html") for item in plans["rollouts"]["files"]))
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944"""Task03-F offline spatial-stratification control; production code is read-only.
WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_local_structural_sampling --baseline PATHOnly S3 ep000 Frame0 Local is selected. Actual Global is always read from Task03-E."""from __future__ import annotations
import argparseimport hashlibimport htmlfrom html.parser import HTMLParserimport jsonimport osfrom pathlib import Pathimport platformimport shutilimport subprocessimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport numpy as npfrom scipy.spatial import cKDTree
from utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import OrganizedGeometryfrom visual.runtime.rgbd import iter_saved_rgbdfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_priority_fps_metric_control as priorfrom visual.runtime.test.run_rim_bottleneck import require_equal, source_contract, write_json
REPO = prior.REPOSOURCE = REPO / 'visual/results/sampling' / prior.SOURCE_RUNBASELINE_ID = '7f657cf88baf4f1f89e594252e243e1c'BASELINE = REPO / 'experiments' / BASELINE_IDREPORT = REPO / 'docs/visual-graph-integration/03f_local_structural_sampling.md'STEM = 'local_structural_sampling'TESTS = ['visual.runtime.test.' + n for n in ( 'test_local_structural_sampling', 'test_sampling', 'test_sampling_geometry', 'test_sampling_evaluation', 'test_priority_fps_metric_control')]
# Preregistered constants: written to config + snapshot BEFORE any run FPS/tests.RULES = dict(max_leaves=8, min_child_capacity=4, priority=32, seed=0, split_leaf='largest capacity; tie smallest flat', axis='largest valid UV span; tie u', cut='minimum count imbalance; tie smaller coordinate; never split equal coordinates', group_order='minimum flat ascending; rows flat ascending', quota='capacity-capped round robin in group ID order', anchor='whole-C seeded first row; actual stored anchor verified without FPS replay', rng='same object seed per group; anchor uses initial without RNG draw', ties='existing FPS first input row', metric='Camera XY lambda=0', surface='existing actual 3D FPS initialized with all P', fallback='one leaf=global contract; N<32 all C in group FPS order; N=0 no P; no padding', zero_quota='skip group; if anchor quota=0 no forced anchor', uv_bins=[4, 4], xyz_bins=[2, 2, 2], grid_bounds='actual X / synthetic observed C bbox; half-open except final boundary', distances='independent Euclidean C->P 3D mm and UV px; percentiles numpy linear', normalized='divide raw metres/pixels by corresponding bbox diagonal', na='null scalar summaries for empty/zero diagonal; raw unavailable distance NaN in NPZ only', gt='evaluation only after selection; existing same-pair 2px AND 3mm', causal_caveat='grouping, quota and group initialization change together; no factorial attribution')
FIXTURES = dict(shape=[1024, 1024], focal_px=1600., principal_uv=[511.5, 511.5], near_depth_m=.8, far_depth_m=1.6, seed=0, synthetic_object_id=0, line_endpoints_m=[[-.12, 0., 0.], [.12, 0., 0.]], line_candidates=128, dense_candidates=128, dense_fraction=.25, segments_m=[[[ -.105, -.06, 0.],[-.075, -.06, 0.]], [[ -.03, 0., 0.],[.03, 0., 0.]], [[ -.06, .06, 0.],[.06, .06, 0.]]], candidates_per_segment=64, reference_per_segment=128, noise_centre_m=[.10, .02, 0.], noise_step_m=.001, noise_count=8, parameter_samples='midpoints (i+.5)/N; extra dense points offset by quarter cell', projection='pinhole, np.rint (ties to even), image bounds; retain original camera XYZ', collision='one row per pixel: keep smallest generated source ID, then sort flat; never refill', occlusion='near image central quarter width: 384 <= u < 640; same rule for references', boundary='outer 10% of observed bbox on nonzero axes; occlusion boundary <=1px', names=['line_uniform', 'line_dense', 'separated_clean', 'separated_noise', 'camera_near', 'camera_far', 'camera_occluded'])
def uv_from_flat(flat, shape): flat = np.asarray(flat) if flat.ndim != 1 or flat.dtype.kind not in 'iu' or len(np.unique(flat)) != len(flat): raise ValueError('unique integer source indices required') if len(shape) != 2 or min(shape) <= 0 or ((flat < 0) | (flat >= np.prod(shape))).any(): raise ValueError('invalid raster source') return np.column_stack((flat % shape[1], flat // shape[1]))
def spatial_groups(flat, shape): """UV only, no XYZ, score, object name or annotation arguments.""" flat = np.asarray(flat) uv = uv_from_flat(flat, shape) if len(flat) and not np.all(flat[:-1] < flat[1:]): raise ValueError('candidate rows must be original flat ascending') leaves = [np.arange(len(flat), dtype=np.int64)] if len(flat) else [] splits = [] while len(leaves) < RULES['max_leaves']: chosen = None for li in sorted(range(len(leaves)), key=lambda i: (-len(leaves[i]), int(flat[leaves[i][0]]))): rows = leaves[li] axes = [] for axis in (0, 1): values, counts = np.unique(uv[rows, axis], return_counts=True) left = np.cumsum(counts)[:-1] valid = np.flatnonzero((left >= 4) & (len(rows)-left >= 4)) if len(valid): cut = min(valid, key=lambda j: (abs(int(2*left[j]-len(rows))), int(values[j]))) axes.append((int(values[-1]-values[0]), axis, float(values[cut]+values[cut+1])/2)) if axes: _, axis, boundary = min(axes, key=lambda a: (-a[0], a[1])) chosen = li, rows, axis, boundary break if chosen is None: break li, rows, axis, boundary = chosen low = rows[uv[rows, axis] < boundary] high = rows[uv[rows, axis] >= boundary] splits.append(dict(parent_min_flat=int(flat[rows[0]]), capacity=len(rows), axis='uv'[axis], boundary=boundary, child_capacity=[len(low), len(high)])) leaves[li:li+1] = [low, high] leaves.sort(key=lambda rows: int(flat[rows[0]])) membership = np.empty(len(flat), np.int64) for gid, rows in enumerate(leaves): membership[rows] = gid return leaves, membership, splits
def allocate(capacities, count): n = np.asarray(capacities, dtype=np.int64) if count < 0 or (n < 0).any(): raise ValueError('nonnegative budget/capacity required') remaining = min(int(count), int(n.sum())) q = np.zeros_like(n) while remaining: for g in range(len(n)): if remaining and q[g] < n[g]: q[g] += 1 remaining -= 1 return q
def choose_priority(flat, xyz, shape, seed, anchor=None, count=32): """Selection inputs only. Source rows remain exact; transformed XYZ is temporary.""" flat, xyz = np.asarray(flat), np.asarray(xyz) if xyz.shape != (len(flat), 3) or not np.isfinite(xyz).all(): raise ValueError('finite aligned candidate XYZ required') leaves, membership, splits = spatial_groups(flat, shape) quota = allocate([len(g) for g in leaves], min(count, len(flat))) if not len(flat): return dict(P=flat.copy(), rows=np.empty(0, np.int64), membership=membership, quota=quota, splits=splits, initial_flat=[], capacities=[]) if anchor is None: anchor = int(flat[np.random.default_rng(seed).integers(len(flat))]) ar = np.flatnonzero(flat == anchor) if len(ar) != 1: raise ValueError('anchor must occur exactly once') ag = int(membership[ar[0]]) order = ([ag] if quota[ag] else []) + [g for g in range(len(leaves)) if g != ag and quota[g]] selected, first = [], [None] * len(leaves) for gid in order: rows = leaves[gid] initial = np.flatnonzero(rows == ar[0]) if gid == ag else () local = fps_indices(prior.metric_coordinates(xyz[rows], 0.), int(quota[gid]), seed=seed, initial=initial) selected.extend(rows[local].tolist()) first[gid] = int(flat[rows[local[0]]]) rows = np.asarray(selected, np.int64) return dict(P=flat[rows].copy(), rows=rows, membership=membership, quota=quota, splits=splits, initial_flat=first, capacities=[len(g) for g in leaves])
def select_local(candidate_flat, candidate_xyz, support_flat, support_xyz, shape, seed, anchor, budget): """No annotation arguments and no access to GT globals.""" support_flat, support_xyz = np.asarray(support_flat), np.asarray(support_xyz) uv_from_flat(support_flat, shape) if len(support_flat) and not np.all(support_flat[:-1] < support_flat[1:]): raise ValueError('support order required') rows = np.searchsorted(support_flat, candidate_flat) if (rows >= len(support_flat)).any() or not np.array_equal(support_flat[rows], candidate_flat): raise ValueError('candidate outside support') np.testing.assert_array_equal(support_xyz[rows], candidate_xyz) p = choose_priority(candidate_flat, candidate_xyz, shape, seed, anchor) initial = np.searchsorted(support_flat, p['P']) frows = fps_indices(support_xyz, budget, seed=seed, initial=initial) f = support_flat[frows] return dict(P=p['P'], S=f[len(initial):], F=f, xyz=support_xyz[frows].copy(), grouping=p, shortfall=max(0, budget-len(f)))
def summary(values): a = np.asarray(values, float) a = a[np.isfinite(a)] if not len(a): return dict(count=0, mean=None, p50=None, p95=None, max=None, status='N/A') return dict(count=len(a), mean=float(a.mean()), p50=float(np.percentile(a, 50)), p95=float(np.percentile(a, 95)), max=float(a.max()), status='defined')
def nearest(query, points): return cKDTree(points).query(query)[0] if len(points) else np.full(len(query), np.nan)
def grid_definition(points, bins): points = np.asarray(points, float) if not len(points): return dict(lo=[0.] * len(bins), hi=[0.] * len(bins), bins=[1] * len(bins), empty=True) lo, hi = points.min(0), points.max(0) return dict(lo=lo.tolist(), hi=hi.tolist(), bins=[b if hi[i] > lo[i] else 1 for i,b in enumerate(bins)], empty=False)
def grid_ids(points, definition): lo, hi, bins = (np.asarray(definition[k]) for k in ('lo', 'hi', 'bins')) span = hi-lo scaled = np.divide(np.asarray(points)-lo, span, out=np.zeros_like(np.asarray(points), dtype=float), where=span>0) index = np.minimum(np.maximum(np.floor(scaled*bins).astype(int), 0), bins-1) return np.ravel_multi_index(index.T, bins) if len(index) else np.empty(0, np.int64)
def spatial_metrics(flat, xyz, pflat, pxyz, support_flat, support_xyz, shape): uv, puv, xuv = (uv_from_flat(f, shape) for f in (flat, pflat, support_flat)) dmm, dpx = nearest(xyz, pxyz)*1000, nearest(uv, puv) definitions = dict(uv=grid_definition(xuv, [4,4]), xyz=grid_definition(support_xyz, [2,2,2])) raw = dict(distance_mm=dmm, distance_px=dpx) metrics = dict(candidate_count=len(flat), priority_count=len(pflat), selected_fraction=len(pflat)/len(flat) if len(flat) else None, grids={}) for unit, distance, coordinates, definition in ( ('mm', dmm, xyz, definitions['xyz']), ('px', dpx, uv, definitions['uv'])): diagonal = float(np.linalg.norm(np.asarray(definition['hi'])-definition['lo'])) denom = diagonal * (1000 if unit == 'mm' else 1) norm = distance/denom if denom > 0 else np.full(len(distance), np.nan) raw['normalized_'+unit] = norm raw['ecdf_'+unit] = np.sort(distance[np.isfinite(distance)]) worst = int(np.nanargmax(distance)) if np.isfinite(distance).any() else None metrics[unit] = dict(raw=summary(distance), normalized=summary(norm), bbox_diagonal=denom, worst=None if worst is None else dict(flat_index=int(flat[worst]), xyz_m=xyz[worst].tolist(), uv=uv[worst].tolist())) for kind, cpoints, ppoints in (('uv',uv,puv), ('xyz',xyz,pxyz)): definition = definitions[kind] cid, pid = grid_ids(cpoints, definition), grid_ids(ppoints, definition) raw[kind+'_candidate_region'] = cid raw[kind+'_priority_region'] = pid cells = [] for rid in range(int(np.prod(definition['bins']))): mask = cid == rid nc, np_ = int(mask.sum()), int((pid == rid).sum()) area = float(np.prod((np.asarray(definition['hi'])-definition['lo'])/definition['bins'])) if kind == 'uv' else None cells.append(dict(id=rid, candidate_count=nc, priority_count=np_, priority_share=np_/len(pflat) if len(pflat) else None, selection_rate=np_/nc if nc else None, candidate_density_per_px2=nc/area if area else None, distance_mm=summary(dmm[mask]), distance_px=summary(dpx[mask]))) occupied = [r for r in cells if r['candidate_count']] metrics['grids'][kind] = dict(definition=definition, cells=cells, candidate_occupied_regions=len(occupied), empty_priority_region_ids=[r['id'] for r in occupied if not r['priority_count']], selected_region_fraction=sum(r['priority_count'] > 0 for r in occupied)/len(occupied) if occupied else None, max_priority_share=max((r['priority_count']/len(pflat) for r in cells), default=0.) if len(pflat) else None, equal_region_mean_p95_mm=summary([r['distance_mm']['p95'] for r in occupied if r['distance_mm']['p95'] is not None])['mean'], equal_region_mean_p95_px=summary([r['distance_px']['p95'] for r in occupied if r['distance_px']['p95'] is not None])['mean']) return metrics, raw
def synthetic_fixture(name): """Generate fixed candidates and separate evaluator annotations, no FPS/detector.""" if name not in FIXTURES['names']: raise ValueError('unknown fixed fixture') isline = name.startswith('line_') endpoints = np.array([FIXTURES['line_endpoints_m']] if isline else FIXTURES['segments_m'], float) count = FIXTURES['line_candidates'] if isline else FIXTURES['candidates_per_segment'] points, labels, references, ref_labels = [], [], [], [] for sid, (start, end) in enumerate(endpoints): t = (np.arange(count)+.5)/count points.extend(start+(end-start)*t[:,None]); labels.extend([sid]*count) tr = (np.arange(128)+.5)/128 references.extend(start+(end-start)*tr[:,None]); ref_labels.extend([sid]*128) if name == 'line_dense': # Quarter-cell offset prevents coincident generated XYZ with the base line. t = (np.arange(128)+.25)/128*.25 points.extend(endpoints[0,0]+(endpoints[0,1]-endpoints[0,0])*t[:,None]); labels.extend([0]*128) if name == 'separated_noise': centre = np.array(FIXTURES['noise_centre_m']) offsets = np.array([(i%4, i//4, 0.) for i in range(8)])*FIXTURES['noise_step_m'] points.extend(centre+offsets); labels.extend([-1]*8) depth = FIXTURES['far_depth_m'] if name == 'camera_far' else FIXTURES['near_depth_m'] points, references = np.asarray(points), np.asarray(references) points[:,2] += depth; references[:,2] += depth def project(xyz): return np.rint(xyz[:,:2]/xyz[:,2,None]*FIXTURES['focal_px']+FIXTURES['principal_uv']).astype(np.int64) uv, ruv = project(points), project(references) h,w = FIXTURES['shape'] keep = ((uv >= 0) & (uv < [w,h])).all(1) visible = ((ruv >= 0) & (ruv < [w,h])).all(1) if name == 'camera_occluded': keep &= ~((uv[:,0] >= 384) & (uv[:,0] < 640)) visible &= ~((ruv[:,0] >= 384) & (ruv[:,0] < 640)) generated = np.flatnonzero(keep) projected = uv[generated,1]*w+uv[generated,0] _, first = np.unique(projected, return_index=True) # unique values sorted flat; first generated ID wins generated = generated[first] flat = uv[generated,1]*w+uv[generated,0] annotation = dict(structure_id=np.array(labels)[generated], reference_xyz=references, reference_structure_id=np.array(ref_labels), reference_visible=visible, lengths_m=np.linalg.norm(endpoints[:,1]-endpoints[:,0],axis=1), generated_id=generated) return dict(flat=flat, xyz=points[generated], shape=(h,w)), annotation, dict( generated_count=len(points), in_view_before_collision=int(keep.sum()), observed_count=len(flat), collision_count=int(keep.sum()-len(flat)), excluded_references=int((~visible).sum()))
def evaluate_synthetic(data, annotation, chosen): flat, xyz, shape = data['flat'], data['xyz'], data['shape'] rows = np.searchsorted(flat, chosen) pxyz = xyz[rows] metrics, raw = spatial_metrics(flat, xyz, chosen, pxyz, flat, xyz, shape) visible = annotation['reference_visible'] distances = nearest(annotation['reference_xyz'][visible], pxyz)*1000 labels = annotation['reference_structure_id'][visible] metrics['reference_mm'] = summary(distances) metrics['structures'] = {str(s):dict(length_m=float(length), selected=int((annotation['structure_id'][rows] == s).sum()), reference_mm=summary(distances[labels == s])) for s,length in enumerate(annotation['lengths_m'])} metrics['noise_selected'] = int((annotation['structure_id'][rows] == -1).sum()) metrics['noise_priority_fraction'] = metrics['noise_selected']/len(chosen) if len(chosen) else None uv = uv_from_flat(flat, shape); lo,hi = uv.min(0),uv.max(0); span=hi-lo border = (((uv <= lo+.1*span) | (uv >= hi-.1*span)) & (span > 0)).any(1) # Boundary annotation is evaluator-only; near/far/occlusion all use the same definition. occ = ((np.abs(uv[:,0]-384) <= 1) | (np.abs(uv[:,0]-640) <= 1)) if annotation.get('occluded', False) else np.zeros(len(flat),bool) metrics['boundary'] = {name:dict(candidates=int(mask.sum()), priority=int(mask[rows].sum())) for name,mask in [('outer_10pct',border),('occlusion_1px',occ)]} raw['visible_reference_distance_mm'] = distances return metrics, raw
def load_actual(): """Read only S3 geometry/source/evidence; no GT evaluation before Local is fixed.""" comparison = json.loads((SOURCE/'comparison.json').read_text()) config = comparison['config'] contracts = source_contract(SOURCE, config) for key in ('input','masks'): require_equal(prior.sha(config[key]), config[key+'_sha256'], 'original '+key) frame = next(iter_saved_rgbd(config['input'], config['masks'], camera=config['camera'])) require_equal(frame.source_frame, 0, 'Frame0') samples = np.load(SOURCE/'f0000_samples.npz', allow_pickle=False) old = json.loads((BASELINE/(prior.STEM+'.json')).read_text()) require_equal(old['run_id'], BASELINE_ID, 'baseline identity') cases, baselines = {}, {} with np.load(prior.TASK01/'f0000.npz', allow_pickle=False) as dense, np.load(BASELINE/(prior.STEM+'.npz'), allow_pickle=False) as saved: for field in ('intrinsic','cam2world'): np.testing.assert_array_equal(dense[field], getattr(frame,field)) np.testing.assert_array_equal(dense['xyz'][...,2][dense['valid_depth']], frame.depth[dense['valid_depth']]) geometry = OrganizedGeometry(dense['xyz'].copy(),dense['valid_depth'].copy(), {oid:dense[name+'/object_mask'].copy() for name,oid in prior.OBJECTS.items()},dense['overlap_mask'].copy()) for name,oid in prior.OBJECTS.items(): np.testing.assert_array_equal(geometry.object_masks[oid], frame.masks[oid]) prefix = 'S3/'+name case = {k:saved[prefix+'/'+k].copy() for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz')} candidate, support = case['candidate_flat'], case['support_flat'] np.testing.assert_array_equal(candidate, samples[f'evidence/pca5/{oid}/20/orientation_flat']) np.testing.assert_array_equal(support,np.flatnonzero(geometry.observed_mask(oid))) for kind in ('candidate','support'): np.testing.assert_array_equal(case[kind+'_xyz'],geometry.xyz.reshape(-1,3)[case[kind+'_flat']]) count,anchor = prior.EXPECTED['S3',name] require_equal(len(candidate),count,'candidate count') seed = prior.fps_seed(0,oid) require_equal(int(candidate[np.random.default_rng(seed).integers(len(candidate))]),anchor,'seeded anchor') key='S3_n256_r0.25_t20_s0' mask=samples[key+'/object_id'] == oid features={k.split('/metadata/')[1]:samples[k][mask].copy() for k in samples.files if k.startswith(key+'/metadata/')} require_equal(len(features),23,'feature field count') case.update(name=name,oid=oid,method='S3',first=anchor,seed=seed,budget=prior.BUDGET[name], saved_flat=samples[key+'/flat_index'][mask].copy(),saved_features=features) chosen={s:saved[prefix+'/0.0/'+s+'/flat_index'].copy() for s in ('P','S','F')} chosen['xyz']=saved[prefix+'/0.0/F/xyz'].copy() require_equal((len(chosen['P']),len(chosen['F']),int(chosen['P'][0])),(32,case['budget'],anchor),'stored budget/anchor') np.testing.assert_array_equal(chosen['F'],np.r_[chosen['P'],chosen['S']]) np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(support,chosen['F'])]) cases[name],baselines[name]=case,chosen return frame,geometry,samples,cases,baselines,old,config,contracts
def plots(output, frame, cases, selections, result, arrays, synthetic): plt.rcParams.update({'font.size':9}) fig, axes=plt.subplots(2,3,figsize=(16,10),constrained_layout=True) for i,name in enumerate(prior.OBJECTS): case=cases[name]; uv=uv_from_flat(case['candidate_flat'],frame.depth.shape) group=selections[name]['local']['grouping'] axes[i,0].scatter(*uv.T,c=group['membership'],cmap='tab10',s=8) for j,method in enumerate(('global','local'),1): ax=axes[i,j]; ax.scatter(*uv.T,c='#9ca3af',s=3,alpha=.5) selected=uv_from_flat(selections[name][method]['P'],frame.depth.shape) ax.scatter(*selected.T,c='#ef7b22',s=25,label='Priority') definition=result['actual'][name][method]['spatial']['grids']['uv']['definition'] for axis in (0,1): boundaries=np.linspace(definition['lo'][axis],definition['hi'][axis],definition['bins'][axis]+1) for b in boundaries: (ax.axvline if axis==0 else ax.axhline)(b,c='#416b9c',alpha=.3,lw=.8) worst=result['actual'][name][method]['spatial']['px']['worst']['uv'] ax.scatter(*worst,c='red',marker='x',s=80,label='max C->P pixel gap') ax.legend(fontsize=7) for j,ax in enumerate(axes[i]): ax.set(title=f'{name}: '+('UV candidate strata (not physical edges)' if j==0 else ('global','local')[j-1]+' / independent 4x4 grid'),xlabel='u (px)',ylabel='v (px)') ax.invert_yaxis() fig.savefig(output/'candidate_groups.png',dpi=140);plt.close(fig) fig,axes=plt.subplots(2,2,figsize=(13,9),constrained_layout=True) for i,name in enumerate(prior.OBJECTS): for j,unit in enumerate(('mm','px')): for method in ('global','local'): values=arrays[f'{name}/{method}/spatial/ecdf_{unit}'] axes[i,j].plot(values,np.arange(1,len(values)+1)/len(values),label=method) axes[i,j].set(title=f'{name}: all C -> P',xlabel=unit,ylabel='ECDF');axes[i,j].legend() fig.savefig(output/'candidate_distance_ecdf.png',dpi=140);plt.close(fig) fig,axes=plt.subplots(2,2,figsize=(14,9),constrained_layout=True) for i,name in enumerate(prior.OBJECTS): for j,kind in enumerate(('uv','xyz')): for method,color in [('global','#2878b5'),('local','#e67f22')]: cells=result['actual'][name][method]['spatial']['grids'][kind]['cells'] x=np.arange(len(cells));off=-.18 if method=='global' else .18 vals=[c['distance_mm']['p95'] if c['distance_mm']['p95'] is not None else np.nan for c in cells] axes[i,j].bar(x+off,vals,.34,label=method,color=color) axes[i,j].set(title=f'{name}: independent {kind} regions (empty C = blank)',xlabel='region ID',ylabel='C -> P p95 (mm)');axes[i,j].legend() fig.savefig(output/'independent_regions.png',dpi=140);plt.close(fig) fig,axes=plt.subplots(3,3,figsize=(17,13),constrained_layout=True) for ax,(name,(data,annotation,chosen)) in zip(axes.flat,synthetic.items()): uv=uv_from_flat(data['flat'],data['shape']) ax.scatter(*uv.T,c=chosen['local']['membership'],cmap='tab10',s=8,alpha=.55) for method,marker,color in [('global','o','#1666a2'),('local','x','#d76012')]: p=uv_from_flat(chosen[method]['P'],data['shape']) ax.scatter(*p.T,marker=marker,facecolors='none' if marker=='o' else color,edgecolors=color,s=40,label=method) ax.set(title=f'{name} (N={len(uv)})',xlabel='u (px)',ylabel='v (px)');ax.invert_yaxis();ax.legend(fontsize=7) for ax in list(axes.flat)[7:]:ax.axis('off') fig.suptitle('Synthetic sampler stress tests: supplied candidates / UV strata / Priority (no GT labels in selection)') fig.savefig(output/'synthetic_seven.png',dpi=140);plt.close(fig) for name in prior.OBJECTS: fig,axes=plt.subplots(2,2,figsize=(13,10),constrained_layout=True) refs=arrays[name+'/reference_uv'] for i,method in enumerate(('global','local')): for j,stage in enumerate(('P','F')): ax=axes[i,j];ax.imshow(frame.rgb) prefix=f'{name}/{method}/{stage}' covered=arrays[prefix+'/covered'];matched=arrays[prefix+'/matched_node'] uv=arrays[prefix+'/pixels_vu'][:,::-1] ax.scatter(*refs[~covered].T,c='#df2b68',marker='x',s=15,label='missing GT reference') ax.scatter(*refs[covered].T,c='#16b38b',s=12,label='covered GT reference') ax.scatter(*uv[~matched].T,facecolors='none',edgecolors='#e6a534',s=28,label='other selected node') ax.scatter(*uv[matched].T,facecolors='none',edgecolors='#2972dc',s=80,label='joint matching node') ax.set(xlim=(refs[:,0].min()-12,refs[:,0].max()+12),ylim=(refs[:,1].max()+12,refs[:,1].min()-12), title=f'{name} {method} {stage}: {matched.sum()} nodes / {covered.sum()} references') ax.legend(fontsize=7) fig.suptitle('GT auxiliary evaluation (separate from GT-free UV strata)') fig.savefig(output/f'{name}_gt_auxiliary.png',dpi=140);plt.close(fig) fig,axes=plt.subplots(2,2,figsize=(13,9),constrained_layout=True) for i,name in enumerate(prior.OBJECTS): for j,method in enumerate(('global','local')): case=cases[name];ax=axes[i,j];support=case['support_xyz'] ax.scatter(support[:,0]*1000,support[:,2]*1000,c='#a9b4bd',s=.5,alpha=.3) for stage,color in [('P','#e87a20'),('S','#2aa3ab')]: xyz=support[np.searchsorted(case['support_flat'],selections[name][method][stage])] ax.scatter(xyz[:,0]*1000,xyz[:,2]*1000,c=color,s=12,label=stage) ax.set(title=f'{name} {method} unfiltered X / P / S',xlabel='camera X (mm)',ylabel='camera Z (mm)');ax.legend() fig.savefig(output/'unfiltered_depth_xz.png',dpi=140);plt.close(fig) fig,axes=plt.subplots(1,3,figsize=(16,5),constrained_layout=True) names=[n+' '+m for n in prior.OBJECTS for m in ('global','local')] rows=[result['actual'][n][m]['gt'] for n in prior.OBJECTS for m in ('global','local')] x=np.arange(4) axes[0].bar(x-.17,[r['surface_distance_mm']['mean'] for r in rows],.34,label='mean') axes[0].bar(x+.17,[r['surface_distance_mm']['p95'] for r in rows],.34,label='p95');axes[0].legend() axes[0].set(title='X -> Final actual 3D',ylabel='mm') for i,(field,title) in enumerate([('negative','Known-negative union P'),('depth','P beyond X depth p95')],1): v=[r['occupancy']['negative_roi']['known_negative_union']['P']['count'] if field=='negative' else r['occupancy']['depth_quantile_occupancy']['P']['z_gt_X_p95']['numerator'] for r in rows] axes[i].bar(x,v);axes[i].set(title=title,ylabel='nodes / 32') for ax in axes:ax.set_xticks(x,names,rotation=25,ha='right') fig.savefig(output/'surface_negative_tradeoff.png',dpi=140);plt.close(fig)
def tables(result): lines=['| 대상 | 방식 | C→P 3D p50 / p95 / max mm | UV p95 px | UV 점유 구역 선택 / 후보 구역 | UV 구역 동등 평균 p95 mm | Surface mean / p95 mm |', '| --- | --- | ---: | ---: | ---: | ---: | ---: |'] f=lambda x:'N/A' if x is None else f'{x:.3f}' for name,row in result['actual'].items(): for method in ('global','local'): r=row[method];s=r['spatial'];d=s['mm']['raw'];g=s['grids']['uv'];surface=r['gt']['surface_distance_mm'] occupied=g['candidate_occupied_regions'];selected=occupied-len(g['empty_priority_region_ids']) lines.append(f"| {name} | {method} | {' / '.join(f(d[k]) for k in ('p50','p95','max'))} | {f(s['px']['raw']['p95'])} | {selected}/{occupied} | {f(g['equal_region_mean_p95_mm'])} | {f(surface['mean'])} / {f(surface['p95'])} |") return lines
def answers(result): out=[] for name,row in result['actual'].items(): g,l=(row[m]['spatial'] for m in ('global','local')) out.append(f"{name}: C→P p95 {g['mm']['raw']['p95']:.3f}→{l['mm']['raw']['p95']:.3f}mm, max {g['mm']['raw']['max']:.3f}→{l['mm']['raw']['max']:.3f}mm; UV 후보 점유 구역 중 P=0은 {len(g['grids']['uv']['empty_priority_region_ids'])}→{len(l['grids']['uv']['empty_priority_region_ids'])}개다.") return out
def create_documents(output, result, test_summary): rel=lambda p:os.path.relpath(p,REPORT.parent) f=lambda x:'N/A' if x is None else f'{x:.3f}' lines=['# Task03-F — Generalizable Local Geometry Preservation','', f"실행 UUID: `{result['run_id']}`. ep000 Frame 0 S3의 저장 Global λ=0과 Local UV spatial stratification control을 비교했다.", '', '제한된 예산에서 후보의 국소 공간 보존과 실제 구조·Surface의 trade-off를 검증한다. 후보 수를 균형 있게 나누는 UV 분할이며 structural component detection, geometry-aware grouping, density-invariant sampling이 아니다. Grouping·quota·group별 초기화가 함께 달라지므로 효과를 quota 하나에 귀속하지 않는다.', '', '## 실행 조건과 사전 고정','', '- num_points=256, structural_ratio=.25, threshold=20°, seed=0. C/X 및 원본 XYZ·pixel·source 불변. P 각 32, Peg F=129, Box F=127. 실제 Global FPS 호출은 0회다.', '- 최대 8 leaf, split 최소 4후보, 최대 capacity leaf부터 UV 유효 span 축/균형 cut, capacity-capped round robin과 기존 Camera XY FPS를 사용했다. Surface는 원본 3D FPS다.', '- 8/4는 이번 K=32 control 설정이다. 일반 budget의 성능을 보장하지 않는다. 규칙·평가 구역·7개 fixture·N/A 정의를 config/source snapshot에 고정한 뒤 테스트·선택을 수행했다.', '- GT pose·rim·face-pair·ROI는 실제 선택 저장 후에만 평가에 사용했다. Task-Relevance Scoring은 구현하지 않았다.', '', '## GT-free 공간 보존','',*tables(result),'',*answers(result),'', '전체 p95는 후보 밀도에 가중된다. 독립 UV 4×4 및 XYZ 최대 2×2×2 구역의 count·밀도·선택률·p95/max·동등 구역 통계와 raw/normalized 거리·ECDF는 JSON/NPZ에 저장했다. C에는 false response가 섞이므로 지표 변화를 구조 검출 정확도 변화로 치환하지 않는다. 최댓값은 관측 C 위의 미피복 위치이며 연속 빈 공간의 크기를 복원한 값이 아니다.', '', '## Peg seam / Box rim 보조 평가','', '같은 point/reference pair의 2px AND 3mm matcher를 재사용했다. Peg observed 462(GT visible 464), Box 103. nodes는 실제 matching node 수, refs는 unique reference 수다. 구간 복수 귀속은 ambiguous이며 Peg 물리적 간격은 N/A다.', '', '| 대상 | 방식 | C nodes / refs | P nodes / refs | S nodes / refs | F nodes / refs | Surface 추가 refs | Negative union P / S / F |', '| --- | --- | ---: | ---: | ---: | ---: | ---: | --- |'] for name,row in result['actual'].items(): for method in ('global','local'): r=row[method]['gt'];st=r['stages'];counts=['%d / %d'%(st[s]['structural_matching_nodes'],st[s]['unique_reference_count']) for s in ('C','P','S','F')] neg=r['occupancy']['negative_roi']['known_negative_union'] lines.append(f"| {name} | {method} | "+' | '.join(counts)+f" | {r['coverage']['differences']['S_minus_P']['count']} | "+' / '.join(str(neg[s]['count']) for s in ('P','S','F'))+' |') lines+=['','| 대상 | 후보 C / support X | Leaf capacity (ID 순서) | Quota | Global / Local exact feature rows |', '| --- | ---: | --- | --- | ---: |'] for name,row in result['actual'].items(): s=row['global']['spatial'];group=row['grouping'] available=[row[m]['gt']['feature_availability']['exact_available_rows'] for m in ('global','local')] lines.append(f"| {name} | {s['candidate_count']} / {row['global']['gt']['occupancy']['depth_m']['X']['count']} | {group['capacities']} | {group['quota']} | {available[0]} / {available[1]} |") lines+=['','| 대상 | 구간 | observed | C refs | Global P / F refs | Local P / F refs | Global / Local F nodes |', '| --- | --- | ---: | ---: | ---: | ---: | ---: |'] for name,row in result['actual'].items(): g,l=(row[m]['gt']['stages'] for m in ('global','local')) for label,c in g['C']['segments'].items(): v=lambda stages,s:stages[s]['segments'][label] lines.append(f"| {name} | {label} | {c['observed_references']} | {c['coverage_count']} | {v(g,'P')['coverage_count']} / {v(g,'F')['coverage_count']} | {v(l,'P')['coverage_count']} / {v(l,'F')['coverage_count']} | {v(g,'F')['matching_node_count']} / {v(l,'F')['matching_node_count']} |") lines+=['', '`rim_axis1_-1`의 기존 0/26은 평가 전용 실패 사례다. X/C의 지원과 P/S/F의 보존 reference·matching node·source 목록을 별도 저장했다. 이 구간 개선을 필수 성공 조건으로 삼거나 이를 보고 재선택하지 않았다.', '', '## Synthetic sampler stress test','', '3종 총 7개 고정 fixture, K=32, 같은 C·anchor·Camera XY λ=0·기존 FPS다. Synthetic에서는 P만 비교하며 detector/normal/tracker/Surface를 만들지 않았다. 구조/noise/reference annotation은 평가 전용이다. 투영 충돌은 생성 ID가 작은 한 점만 남기고 flat 순으로 정렬하며 refill하지 않았다. 실제 camera XYZ를 보존했다.', '', '| Fixture | 생성 / 충돌 전 / 관측 C | Global / Local C→P p95 mm | Global / Local 정규화 p95 | Global / Local reference→P p95 mm | Global / Local noise P |', '| --- | ---: | ---: | ---: | ---: | ---: |'] for name,row in result['synthetic'].items(): g,l=(row[m] for m in ('global','local'));c=row['counts'] lines.append(f"| {name} | {c['generated_count']} / {c['in_view_before_collision']} / {c['observed_count']} | {f(g['mm']['raw']['p95'])} / {f(l['mm']['raw']['p95'])} | {f(g['mm']['normalized']['p95'])} / {f(l['mm']['normalized']['p95'])} | {f(g['reference_mm']['p95'])} / {f(l['reference_mm']['p95'])} | {g['noise_selected']} / {l['noise_selected']} |") lines+=['','| Fixture | 구조 | 길이 m | Global / Local 선택 수 | Global / Local reference p95 mm |', '| --- | --- | ---: | ---: | ---: |'] for name,row in result['synthetic'].items(): for sid,g in row['global']['structures'].items(): l=row['local']['structures'][sid] lines.append(f"| {name} | {sid} | {g['length_m']:.3f} | {g['selected']} / {l['selected']} | {f(g['reference_mm']['p95'])} / {f(l['reference_mm']['p95'])} |") lines+=['','| Fixture | 외곽 띠 후보 수 | Global / Local 외곽 띠 P | 가림 경계 후보 / Global P / Local P |', '| --- | ---: | ---: | ---: |'] for name,row in result['synthetic'].items(): g,l=(row[m]['boundary'] for m in ('global','local')) lines.append(f"| {name} | {g['outer_10pct']['candidates']} | {g['outer_10pct']['priority']} / {l['outer_10pct']['priority']} | {g['occlusion_1px']['candidates']} / {g['occlusion_1px']['priority']} / {l['occlusion_1px']['priority']} |") lines+=['','가림 fixture에서는 짧은 선분 하나만 관측에 남고, 지정한 가림 경계 1px 띠에는 후보가 없다. 이 사례의 동률과 경계 점유 0은 복잡한 부분 가림 또는 경계 noise에 대한 강건성 증거가 아니다. Fixture를 결과에 맞게 바꾸지 않았다.',''] lines+=['','## 최종 질문별 판단','',*result['interpretation_ko'],'', '## 원거리 depth와 Surface·ROI trade-off','', '원거리 positive depth를 필터링하지 않았다. 평가 bbox는 전체 observed X에서 정하므로 depth outlier가 3D bbox 대각선을 키우고 XYZ 격자를 넓혀 후보를 일부 구역에 몰아넣을 수 있다. 따라서 정규화 거리·구역 점유만으로 개선을 판단하지 않으며 raw 거리와 UV 결과를 함께 본다. 아래 X depth와 bbox는 두 방식에 동일하다.', '', '| 대상 | X depth median / p95 / max m | XYZ bbox 대각선 mm | P depth median / p95 Global → Local | P z>X p95 Global / Local |', '| --- | ---: | ---: | --- | ---: |'] for name,row in result['actual'].items(): g,l=(row[m]['gt']['occupancy'] for m in ('global','local'));x=g['depth_m']['X'] lines.append(f"| {name} | {x['median']:.4f} / {x['p95']:.4f} / {x['max']:.4f} | {row['global']['spatial']['mm']['bbox_diagonal']:.3f} | {g['depth_m']['P']['median']:.4f}/{g['depth_m']['P']['p95']:.4f} → {l['depth_m']['P']['median']:.4f}/{l['depth_m']['P']['p95']:.4f} | {g['depth_quantile_occupancy']['P']['z_gt_X_p95']['numerator']} / {l['depth_quantile_occupancy']['P']['z_gt_X_p95']['numerator']} |") lines+=['','| 대상 | 방식 | 3D / UV bbox 정규화 p95 | XYZ 후보 점유 구역 / P=0 구역 | 최대 3D 미피복 후보 source / UV / XYZ m |', '| --- | --- | ---: | --- | --- |'] for name,row in result['actual'].items(): for method in ('global','local'): s=row[method]['spatial'];w=s['mm']['worst'];g=s['grids']['xyz'] lines.append(f"| {name} | {method} | {s['mm']['normalized']['p95']:.6f} / {s['px']['normalized']['p95']:.6f} | {g['candidate_occupied_regions']} / {g['empty_priority_region_ids']} | {w['flat_index']} / {w['uv']} / {w['xyz_m']} |") lines+=['','Box의 X depth max 30.726m를 유지한 XYZ 격자에서는 C가 단 한 구역에 들어갔다. 이 coarse 격자는 이 관측에서 국소 분산을 구별하지 못한다. 작은 정규화 거리 역시 큰 bbox 분모의 영향이 있으므로 raw 거리와 UV 격자를 병기했다.',''] lines+=['','Known-negative ROI는 겹칠 수 있어 union으로 중복을 제거했다. 일반 Surface나 관측 경계 자체를 자동으로 오선택이라 판정하지 않는다.','', '## Feature·검증·재현 범위','', '- 같은 S3 Task03 baseline metadata가 있는 source에만 23 field를 exact gather했다. Availability mask·compact positions를 저장하고 나머지 feature는 생성하지 않았다. Geometry-level offline 검증이며 완전한 Vision Tensor 출력 검증은 아니다.', f'- 필수 계약 테스트: {test_summary}. PASS/FAIL/SKIP와 원본 hash·NPZ readback·상대 링크·PNG 검증은 verification.json에 기록했다. 성능 개선은 테스트 PASS 조건이 아니다.', '- 기존 ExperimentLogger(team=visual, job_type=evaluate), UUID/project/group 및 artifact inventory를 재사용했다. WANDB_MODE=disabled이며 업로드는 하지 않았다. Git 시작 상태가 dirty이므로 source snapshot·변경 전 diff·implementation diff를 함께 보관했다.', '- CPU NumPy/SciPy offline 실행만 수행했다. Simulator·renderer·CUDA/GPU/backend, 새 episode, 학습/GNN/BC, production sampler/normal/feature/tracking 변경, dependency 설치·외부 업로드·Git commit은 미실행이다.', '- 실험 완료와 알고리즘 채택은 별개다. 한 frame과 7개 synthetic fixture로 일반화를 입증하지 않는다. 일반 sampling 방식 채택에는 독립 형상·관측·episode·센서에서 동일 설정 검증이 필요하다. Task-Relevance Scoring은 향후 독립 비교로 남긴다.', '', '## 산출물',''] for p in sorted(output.iterdir()): if p.is_file() and not p.name.endswith('.tracking.json') and p.name not in ('metadata.json','metrics.json','config.yaml','manifest.json'): lines.append(f'- [{p.name}]({rel(p)})') if 'report_recovery' in result: recovery=result['report_recovery'] lines+=['','## 문서 생성 오류와 재실행 구분','', f"최초 수치 실행 `{recovery['selection_run_id']}`는 계약 테스트·선택·평가·PNG 생성 후 HTML의 원본 PNG 파일명 링크 검사에서 실패했다. 실패 기록과 당시 source/config/선택/수치는 보존했다. 현재 UUID는 그 저장 결과를 읽은 **문서 후처리 실행**이며 실제·synthetic FPS 및 성능 평가를 다시 실행하지 않았다. Group·quota·fixture·threshold·seed는 바꾸지 않았다.", '', f"- [실패 기록]({rel(REPO/'experiments'/recovery['selection_run_id']/'attempt_failure.json')})", f"- [최초 수치 JSON]({rel(REPO/'experiments'/recovery['selection_run_id']/(STEM+'.json'))})", f"- [최초 선택/source 보존 자료]({rel(REPO/'experiments'/recovery['selection_run_id']/'source_hashes.json')})"] lines+=['','## 기존 근거','', '- [승인된 계획](03f_local_structural_sampling_plan.md)', '- [Task03-E 보고서](03e_priority_fps_metric_control.md)', f'- [Task03-E 원본 JSON]({rel(BASELINE/(prior.STEM+".json"))}), [원본 NPZ]({rel(BASELINE/(prior.STEM+".npz"))})', f'- [Task03 원본 comparison]({rel(SOURCE/"comparison.json")}), [원본 samples]({rel(SOURCE/"f0000_samples.npz")})', '- [runner](../../visual/runtime/test/run_local_structural_sampling.py), [계약 테스트](../../visual/runtime/test/test_local_structural_sampling.py)', '', '재실행은 새 보호 baseline.json과 새 UUID에서만 수행한다. 기존 보고서가 있으면 overwrite를 거부한다. 결과 제출 후 다음 알고리즘 선택 없이 중단한다.',''] REPORT.write_text('\n'.join(lines),encoding='utf-8') shutil.copyfile(REPORT,output/'report.md') images=[('candidate_groups.png','GT-free candidate strata and independent evaluation grid'), ('candidate_distance_ecdf.png','Global / Local C to P ECDF'),('independent_regions.png','Independent spatial regions'), ('synthetic_seven.png','Seven fixed synthetic fixtures'),('peg_gt_auxiliary.png','Peg seam: GT auxiliary evaluation'), ('box_gt_auxiliary.png','Box rim: GT auxiliary evaluation'),('unfiltered_depth_xz.png','Unfiltered positive depth'), ('surface_negative_tradeoff.png','Surface and known-negative trade-offs')] links=[p for p in output.iterdir() if p.is_file() and not p.name.endswith('.tracking.json')] def html_table(rows): cells=[line.strip('|').split('|') for line in rows] return '<div style="overflow-x:auto"><table><thead><tr>'+''.join('<th>'+html.escape(c.strip())+'</th>' for c in cells[0])+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+html.escape(c.strip())+'</td>' for c in row)+'</tr>' for row in cells[2:])+'</tbody></table></div>' syn_table=['| Fixture | N | Reference p95 Global mm | Reference p95 Local mm | Noise P Global/Local |','| --- | --- | --- | --- | --- |'] for name,row in result['synthetic'].items(): syn_table.append(f"| {name} | {row['counts']['observed_count']} | {row['global']['reference_mm']['p95']:.3f} | {row['local']['reference_mm']['p95']:.3f} | {row['global']['noise_selected']} / {row['local']['noise_selected']} |") blocks=['<!doctype html><html lang="ko"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">', '<title>Task03-F Local geometry sampling</title><style>body{max-width:1250px;margin:32px auto;padding:0 20px;font:16px/1.6 system-ui;color:#203044;background:#f6f8fb}img{width:100%;height:auto;background:white}section{margin:32px 0}pre{white-space:pre-wrap;background:white;padding:20px}table{border-collapse:collapse;background:white;width:100%;font-size:14px}th,td{padding:10px;border:1px solid #dde3eb;text-align:left}a{color:#146bc0}h2{margin-top:40px}</style>', '<h1>Task03-F · Local geometry sampling</h1>', '<p>UV spatial stratification control. Candidate-count splits, not physical components. Grouping, quota and per-group initialization change together. GT annotations are evaluation-only. No production policy is adopted.</p>', f'<p>Run: {result["run_id"]} · <a href="{html.escape(os.path.relpath(REPORT,output))}">Markdown report</a> · <a href="{html.escape(os.path.relpath(BASELINE/(prior.STEM+".json"),output))}">Original Global JSON</a> · <a href="{html.escape(os.path.relpath(BASELINE/(prior.STEM+".npz"),output))}">Original Global NPZ</a> · <a href="{html.escape(os.path.relpath(SOURCE/"f0000_samples.npz",output))}">Task03 samples</a> · <a href="{html.escape(os.path.relpath(SOURCE/"f0000_overlay.png",output))}">Task03 PNG</a></p>', '<h2>Measured comparison</h2>'+html_table(tables(result)), '<h2>Seven fixed synthetic fixtures</h2>'+html_table(syn_table), '<h2>Findings and failures</h2><pre>'+html.escape('\n\n'.join(result['interpretation_ko']))+'</pre>'] for filename,title in images: blocks.append(f'<section><h2>{html.escape(title)}</h2><a href="{filename}"><img src="{filename}" alt="{html.escape(title)}"></a></section>') blocks.append('<p>Occlusion fixture leaves only one short segment visible; no candidates fall in the fixed 1px occlusion boundary band. It does not establish robustness to boundary noise. Box support includes positive depth up to 30.726m: all candidates lie in one coarse XYZ evaluation region. Raw distances and UV regions remain necessary.</p>') blocks+=['<h2>Raw files / provenance</h2><ul>']+[f'<li><a href="{html.escape(p.name)}">{html.escape(p.name)}</a></li>' for p in sorted(links)]+['</ul>', '<script>window.addEventListener("load",()=>{document.body.dataset.imagesComplete=String([...document.images].every(i=>i.complete&&i.naturalWidth>0&&i.naturalHeight>0));document.body.dataset.imageCount=document.images.length;});</script></html>'] (output/(STEM+'.html')).write_text('\n'.join(blocks),encoding='utf-8')
def interpretation(result): """Describe measured failures without tuning or a composite success score.""" a=result['actual'];s=result['synthetic'] selection=lambda fixture,method:[r['selected'] for r in s[fixture][method]['structures'].values()] p95=lambda fixture,method:s[fixture][method]['reference_mm']['p95'] bg,bl=(a['box'][m]['spatial'] for m in ('global','local')) items=['1. 공간 누락: '+' '.join(answers(result))+ f" Box pixel p95는 {bg['px']['raw']['p95']:.3f}→{bl['px']['raw']['p95']:.3f}px로 좋아졌지만 3D tail과 실제 rim 보존은 악화됐다. " '독립 UV 구역의 점유 개수도 같아 점유율만으로 차이를 설명할 수 없다. Group quota 충족은 성능 근거가 아니다.'] items.append('2. 밀도·길이 편향: 균일→조밀 직선의 reference p95는 Global ' f"{p95('line_uniform','global'):.3f}→{p95('line_dense','global'):.3f}mm, Local {p95('line_uniform','local'):.3f}→{p95('line_dense','local'):.3f}mm다. " f"길이 비 1:2:4 clean 구조의 선택 수는 Global {selection('separated_clean','global')}, Local {selection('separated_clean','local')}다. " '후보 수 기반 분할과 균등 quota는 실제 길이나 면적을 균등 보존하는 규칙이 아니다.') items.append('3. Noise: 8개 noise 후보의 선택 수는 ' f"Global {s['separated_noise']['global']['noise_selected']}/32, Local {s['separated_noise']['local']['noise_selected']}/32다. " f"실제 세 구조 선택 수는 clean→noise에서 Global {selection('separated_clean','global')}→{selection('separated_noise','global')}, " f"Local {selection('separated_clean','local')}→{selection('separated_noise','local')}다. " '이 fixture에서는 noise에 더 많은 예산을 쓰는 현상은 관찰되지 않았다. Noise 추가에 따른 구조별 배분 변화는 남으며, 이를 일반적인 noise 강건성으로 확대하지 않는다.') camera=[] for n in ('camera_near','camera_far','camera_occluded'): r=s[n] camera.append(f"{n}: C={r['counts']['observed_count']}, reference p95 G/L={p95(n,'global'):.3f}/{p95(n,'local'):.3f}mm, " f"C→P 정규화 p95 G/L={r['global']['mm']['normalized']['p95']:.4f}/{r['local']['mm']['normalized']['p95']:.4f}") items.append('4. 거리·가림 민감도: '+'; '.join(camera)+ '. 가림은 남은 visible reference만 평가하며, 관측 불가능 geometry 복원을 요구하지 않는다. 정수 투영 충돌·후보 순서·seeded anchor도 조건 간 달라질 수 있어 scale 하나의 인과 효과로 분리하지 않는다.') actual=[] for name,row in a.items(): g,l=(row[m]['gt'] for m in ('global','local')) actual.append(f"{name} Final refs {g['stages']['F']['unique_reference_count']}→{l['stages']['F']['unique_reference_count']}, " f"Surface mean/p95 {g['surface_distance_mm']['mean']:.3f}/{g['surface_distance_mm']['p95']:.3f}→{l['surface_distance_mm']['mean']:.3f}/{l['surface_distance_mm']['p95']:.3f}mm, " f"negative P {g['occupancy']['negative_roi']['known_negative_union']['P']['count']}→{l['occupancy']['negative_roi']['known_negative_union']['P']['count']}/32") items.append('5. 실제 구조와 Surface: '+'; '.join(actual)+ '. 구간별 증가와 감소는 보조 평가 표에 모두 제시했다. Box 한 구간의 개선으로 다른 구조 손실을 상쇄했다고 판단하지 않는다.') items.append('6. 추가 검증 판단: 실제 Peg/Box의 3D tail과 GT 보존, 긴 구조·밀도 변화의 reference 보존에서 전반적 열세다. ' '현재 설정은 공간 배분의 단순 control로 남길 수 있으나 일반 geometry preservation 정책 후보로 적극 채택할 근거는 얻지 못했다. ' '더 구조적인 grouping이 필요한지 검토할 이유는 생겼지만, 이 실험은 그 대안의 우월성을 검증하지 않았다. ' '동일 설정의 독립 형상·관측·episode 검증 전에는 채택하지 않는다. GNN/BC 성능 개선은 주장하지 않는다.') return items
def verify_documents(output): class Links(HTMLParser): def __init__(self): super().__init__();self.targets=[] def handle_starttag(self,tag,attrs): self.targets.extend(v for k,v in attrs if k in ('href','src')) parser=Links();parser.feed((output/(STEM+'.html')).read_text()) for target in parser.targets: if not (output/target).is_file():raise ValueError('missing HTML target '+target) import re targets=re.findall(r'\]\(([^)]+)\)',REPORT.read_text()) for target in targets: if not (REPORT.parent/target).is_file():raise ValueError('missing Markdown target '+target) decoded={} for path in output.glob('*.png'): pixels=plt.imread(path) if pixels.ndim!=3 or min(pixels.shape[:2])<400 or pixels.std()<.01:raise ValueError('empty PNG '+path.name) decoded[path.name]=list(pixels.shape) return dict(status='PASS',html_targets=len(parser.targets),markdown_targets=len(targets),png_decoded=decoded)
def add_arrays(arrays,prefix,data): arrays.update({prefix+'/'+k:np.asarray(v) for k,v in data.items()})
def protected(baseline): current=prior.hashes([REPO/p for p in baseline['hashes']]) require_equal(current,baseline['hashes'],'all original source/input/artifact/dirty files') return dict(status='PASS',file_count=len(current),all_sha256_unchanged=True)
def run(baseline_path): if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required') if REPORT.exists():raise FileExistsError('refuse to overwrite result report') baseline_path=Path(baseline_path) baseline=json.loads(baseline_path.read_text());protected(baseline) sources=list((REPO/'visual/runtime').glob('*.py'))+list((REPO/'visual/runtime/test').glob('*.py'))+[ REPO/'utils/experiment_logger.py',REPO/'utils/experiment_artifacts.py'] source_hashes=prior.hashes(sources) old=json.loads((BASELINE/(prior.STEM+'.json')).read_text()) input_hashes=prior.hashes([REPO/p for p in old['config']['input_sha256']]+[ BASELINE/(prior.STEM+'.json'),BASELINE/(prior.STEM+'.npz'),BASELINE/'verification.json']) for path,digest in old['config']['input_sha256'].items():require_equal(prior.sha(REPO/path),digest,'Task03-E input '+path) config=dict(task='03-F',source_run_id=BASELINE_ID,task03_source_run_id=prior.SOURCE_RUN, episode='ep000',frame=0,method='S3(PCA5)',num_points=256,structural_ratio=.25,threshold_deg=20, seed=0,priority_count=32,final_budgets=prior.BUDGET,rules=RULES,synthetic_fixtures=FIXTURES, source_sha256=source_hashes,input_sha256=input_hashes,python=platform.python_version(), numpy=np.__version__,device='cpu',simulator_executed=False,gpu_executed=False, actual_global_fps_replayed=False,production_policy_adopted=False) with ExperimentLogger(team='visual',config=config,seed=0,model='task03f_uv_spatial_stratification',job_type='evaluate') as logger: output=logger.directory try: write_json(output/'git_start.json',baseline) shutil.copyfile(baseline_path.with_name('git_start.diff'),output/'git_start.diff') for path in sources: dest=output/'source_snapshot'/path.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,dest) write_json(output/'preregistered_config.json',config) # Materialize fixtures and their identities BEFORE any FPS in tests or performance comparison. fixtures={name:synthetic_fixture(name) for name in FIXTURES['names']} write_json(output/'fixture_manifest.json',{name:dict(counts=counts, flat_sha256=prior.array_sha(data['flat']),xyz_sha256=prior.array_sha(data['xyz']), annotation_sha256={k:prior.array_sha(v) for k,v in ann.items()}) for name,(data,ann,counts) in fixtures.items()}) frozen_hash=prior.sha(output/'preregistered_config.json') with (output/'tests.log').open('w') as log: process=subprocess.run([sys.executable,'-m','unittest',*TESTS,'-v'],cwd=REPO,stdout=log,stderr=subprocess.STDOUT) if process.returncode:raise RuntimeError('required contract tests failed; no actual Local FPS executed') test_text=(output/'tests.log').read_text() test_summary=next(line for line in test_text.splitlines() if line.startswith('Ran '))+'; '+test_text.splitlines()[-1] print(test_summary,flush=True) frame,geometry,samples,cases,global_selection,old,old_config,contracts=load_actual() selections={};arrays={};result=dict(run_id=logger.run_id,source_run_id=BASELINE_ID,config=config, source_contract=contracts,actual={},synthetic={},performance_success_required=False) # This is the ONLY actual sampling block; no Global FPS call. for name,case in cases.items(): local=select_local(case['candidate_flat'],case['candidate_xyz'],case['support_flat'],case['support_xyz'], frame.depth.shape,case['seed'],case['first'],case['budget']) require_equal((len(local['P']),len(local['F'])),(32,case['budget']),'actual fixed budgets') selections[name]={'global':global_selection[name],'local':local} for field in ('candidate_flat','candidate_xyz','support_flat','support_xyz'):arrays[name+'/'+field]=case[field] group=local['grouping'] add_arrays(arrays,name+'/group',dict(membership=group['membership'],quota=group['quota'],capacities=group['capacities'])) for method,chosen in selections[name].items(): np.testing.assert_array_equal(chosen['F'],np.r_[chosen['P'],chosen['S']]) require_equal(len(np.unique(chosen['F'])),case['budget'],'unique selection') require_equal(int(chosen['P'][0]),case['first'],'same initial anchor') for stage in ('P','S','F'): add_arrays(arrays,f'{name}/{method}/{stage}',dict(flat_index=chosen[stage], xyz=case['support_xyz'][np.searchsorted(case['support_flat'],chosen[stage])])) for method in ('global','local'): joined=np.concatenate([selections[name][method]['F'] for name in prior.OBJECTS]) require_equal((len(joined),len(np.unique(joined))),(256,256),'cross-object budget and unique sources') # Persist selection boundary before loading annotations; failures cannot trigger reselection. np.savez_compressed(output/'selection_before_gt.npz',**arrays) print('Only S3 Peg/Box Local selected and persisted; Global replay calls=0. Loading evaluation annotations.',flush=True) with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal: contexts=prior.evaluation_inputs(frame,geometry,samples,edges,normal) peg_labels,peg_members=prior.peg_labels(normal['evaluation/peg/face'],normal['evaluation/peg/gt_visible'], normal['evaluation/peg/seam_endpoints'],contexts['peg']['reference'][0]) with np.load(old_config['input'],allow_pickle=False) as episode: box_labels,box_specs,box_transform=prior.rim_labels(contexts['box']['reference'][1],frame.cam2world, episode['box_pose'][0],episode['box_hole_pose'][0],float(episode['box_hole_radii'])) gate={} for name,case in cases.items(): context=contexts[name];labels=peg_labels if name=='peg' else box_labels add_arrays(arrays,name,dict(reference_uv=context['reference'][0],reference_xyz=context['reference'][1], observable=context['observable'],reference_segment=labels)) row={} for method,chosen in selections[name].items(): pxyz=case['support_xyz'][np.searchsorted(case['support_flat'],chosen['P'])] spatial,raw=spatial_metrics(case['candidate_flat'],case['candidate_xyz'],chosen['P'],pxyz, case['support_flat'],case['support_xyz'],frame.depth.shape) gt,data=prior.score_case(case,chosen,context,frame,labels,{} if name=='peg' else box_specs,None if name=='peg' else box_transform) add_arrays(arrays,f'{name}/{method}/spatial',raw);add_arrays(arrays,f'{name}/{method}',data) row[method]=dict(spatial=spatial,gt=gt) if method=='global': previous=old['cases']['S3/'+name]['conditions']['0.0'] for field in ('coverage','stages','surface_distance_mm','occupancy','feature_availability'): require_equal(gt[field],previous[field],'stored baseline evaluation '+name+'/'+field) gate[name]=dict(status='PASS',all_saved_baseline_evaluation_exact=True,global_fps_calls=0) group=selections[name]['local']['grouping'] row['grouping']={k:v.tolist() if isinstance(v,np.ndarray) else v for k,v in group.items() if k not in ('P','rows')} row['paired']=dict(priority_shared=len(np.intersect1d(selections[name]['global']['P'],selections[name]['local']['P'])), final_shared=len(np.intersect1d(selections[name]['global']['F'],selections[name]['local']['F']))) # Reference support and exact match sources on the designated auxiliary failure case. if name=='box': columns=np.flatnonzero(labels=='rim_axis1_-1');matcher=context['matcher'];audit={} for method in ('global','local'): audit[method]={} for stage,flat in dict(X=case['support_flat'],C=case['candidate_flat'],**{k:selections[name][method][k] for k in ('P','S','F')}).items(): adj=matcher.adjacencies['2px_3mm'][np.searchsorted(matcher.flat,flat)][:,columns] audit[method][stage]=dict(matching_flat_indices=flat[adj.getnnz(axis=1)>0].tolist(), covered_reference_ids=columns[adj.getnnz(axis=0)>0].tolist(),denominator=26) row['rim_axis1_-1_audit']=audit result['actual'][name]=row result['baseline_gate']=gate result['peg_memberships']=peg_members synthetic={} for name,(data,annotation,counts) in fixtures.items(): seed=prior.fps_seed(0,0);flat,xyz=data['flat'],data['xyz'] anchor=int(flat[np.random.default_rng(seed).integers(len(flat))]);ar=int(np.flatnonzero(flat==anchor)[0]) global_rows=fps_indices(prior.metric_coordinates(xyz,0.),32,seed=seed,initial=[ar]) chosen={'global':dict(P=flat[global_rows]),'local':choose_priority(flat,xyz,data['shape'],seed,anchor)} # Performance evaluator sees annotations only after both selections are fixed. annotation['occluded']=name=='camera_occluded' row=dict(counts=counts,anchor=anchor) for method in ('global','local'): metric,raw=evaluate_synthetic(data,annotation,chosen[method]['P']) row[method]=metric;add_arrays(arrays,f'synthetic/{name}/{method}',dict(P=chosen[method]['P'],**raw)) add_arrays(arrays,'synthetic/'+name,dict(candidate_flat=flat,candidate_xyz=xyz, group_membership=chosen['local']['membership'],group_quota=chosen['local']['quota'],**annotation)) row['grouping']={k:v.tolist() if isinstance(v,np.ndarray) else v for k,v in chosen['local'].items() if k not in ('P','rows')} result['synthetic'][name]=row;synthetic[name]=(data,annotation,chosen) require_equal(prior.sha(output/'preregistered_config.json'),frozen_hash,'frozen config') result['interpretation_ko']=interpretation(result) result['contract_status']='PASS' write_json(output/(STEM+'.json'),result);np.savez_compressed(output/(STEM+'.npz'),**arrays) with np.load(output/(STEM+'.npz'),allow_pickle=False) as saved: for k,v in arrays.items():np.testing.assert_array_equal(saved[k],v,err_msg=k) plots(output,frame,cases,selections,result,arrays,synthetic) preservation=protected(baseline) require_equal(prior.hashes(sources),source_hashes,'executed sources unchanged') require_equal(prior.hashes([REPO/p for p in input_hashes]),input_hashes,'input arrays/artifacts unchanged') write_json(output/'source_hashes.json',dict(sources_before=source_hashes,sources_after=prior.hashes(sources), inputs_before=input_hashes,inputs_after=prior.hashes([REPO/p for p in input_hashes]),preservation=preservation, historical_task03e_sources=old['config']['source_sha256'])) write_json(output/'git_end.json',dict(git_status=subprocess.check_output(['git','status','--short'],cwd=REPO).decode(),original_preservation=preservation)) verification=dict(status='PASS',required_tests=dict(summary=test_summary,modules=TESTS, pass_count=sum(' ... ok' in l or l=='ok' for l in test_text.splitlines()),fail_count=0,skip_count=sum(' ... skipped' in l for l in test_text.splitlines())), baseline_gate=gate,original_preservation=preservation,config_frozen_sha256=frozen_hash, real_fps_calls=dict(global_baseline=0,local_priority=sum(int((selections[n]['local']['grouping']['quota']>0).sum()) for n in prior.OBJECTS),local_surface=2), synthetic_fps_calls=dict(global_priority=7,local_priority=sum(int((c['local']['quota']>0).sum()) for _,_,c in synthetic.values())), original_xyz_source_pixel_object_role_alignment=True,npz_exact_readback=True, source_input_hashes_unchanged=True,feature_unavailable_explicit=True, same_pair_joint_reference_denominators=True,gt_independence='annotation-free selection helpers + synthetic contract tests', performance_improvement_is_not_pass_criterion=True,production_policy_adopted=False, skipped=['simulator','renderer','CUDA/GPU','independent episodes/objects/sensors','normal/candidate recalculation', 'feature reconstruction','production changes','task relevance scoring','external upload','dependency install','commit']) write_json(output/'verification.json',verification) # Include placeholder targets before documents are generated; overwrite only files owned by this new run. (output/'implementation.patch').touch();(output/(STEM+'.html')).touch() create_documents(output,result,test_summary) diff=b'' for path in (Path(__file__),Path(__file__).with_name('test_local_structural_sampling.py'),REPORT): proc=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,stdout=subprocess.PIPE) if proc.returncode!=1:raise ValueError('failed to capture implementation patch') diff+=proc.stdout (output/'implementation.patch').write_bytes(diff) verification['document_checks']=verify_documents(output) write_json(output/'verification.json',verification) for path in sorted(output.rglob('*')): if path.is_file() and not path.name.endswith('.tracking.json') and path.name not in ('metadata.json','manifest.json','config.yaml','metrics.json'): logger.link_output(path,kind='reports') logger.link_output(REPORT,kind='reports') logger.record(source_run_id=BASELINE_ID,task03_source_run_id=prior.SOURCE_RUN,actual_global_fps_replayed=False, simulator_executed=False,gpu_executed=False,production_policy_adopted=False) logger.log({n:{m:dict(candidate_p95_mm=r[m]['spatial']['mm']['raw']['p95'], final_refs=r[m]['gt']['stages']['F']['unique_reference_count'],surface_mean_mm=r[m]['gt']['surface_distance_mm']['mean']) for m in ('global','local')} for n,r in result['actual'].items()},step=0,prefix='eval/task03f') print(output,flush=True) except Exception as exc: write_json(output/'attempt_failure.json',dict(status='FAIL',exception_type=type(exc).__name__,reason=str(exc), no_automatic_reselection=True,existing_attempt_preserved=True)) print('Failed attempt preserved at '+str(output),flush=True) raise return output
def postprocess(previous,baseline_path): """New, explicitly linked reporting execution. Never calls sampling/evaluation.""" import ast if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required') previous=Path(previous).resolve() original=json.loads((previous/(STEM+'.json')).read_text()) if REPORT.exists() and REPORT.read_bytes()!=(previous/'report.md').read_bytes(): raise FileExistsError('refuse to replace a report not generated by this numeric attempt') baseline=json.loads(Path(baseline_path).read_text());protected(baseline) old_tree=ast.parse((previous/'source_snapshot'/Path(__file__).relative_to(REPO)).read_text()) new_tree=ast.parse(Path(__file__).read_text()) frozen_names=['spatial_groups','allocate','choose_priority','select_local','spatial_metrics','synthetic_fixture','evaluate_synthetic','load_actual'] for name in frozen_names: old=next(n for n in old_tree.body if isinstance(n,ast.FunctionDef) and n.name==name) new=next(n for n in new_tree.body if isinstance(n,ast.FunctionDef) and n.name==name) require_equal(ast.dump(new),ast.dump(old),'unchanged selection/metric/fixture definition '+name) require_equal(original['config']['rules'],RULES,'unchanged rules') require_equal(original['config']['synthetic_fixtures'],FIXTURES,'unchanged fixture constants') previous_hashes=prior.hashes([p for p in previous.rglob('*') if p.is_file()]) config=dict(task='03-F-report-recovery',source_run_id=BASELINE_ID, task03_source_run_id=prior.SOURCE_RUN,selection_run_id=original['run_id'], numeric_payload_sha256=prior.sha(previous/(STEM+'.npz')), fixed_sampling_config=original['config'],this_execution_fps_calls=0, source_sha256=prior.hashes([Path(__file__),Path(__file__).with_name('test_local_structural_sampling.py')])) with ExperimentLogger(team='visual',config=config,seed=0,model='task03f_uv_report_recovery',job_type='evaluate') as logger: output=logger.directory for filename in (STEM+'.npz','selection_before_gt.npz','tests.log','fixture_manifest.json', 'preregistered_config.json','git_start.json','git_start.diff'): shutil.copyfile(previous/filename,output/filename) for path in previous.glob('*.png'):shutil.copyfile(path,output/path.name) shutil.copytree(previous/'source_snapshot',output/'selection_source_snapshot') for path in (Path(__file__),Path(__file__).with_name('test_local_structural_sampling.py')): dest=output/'source_snapshot'/path.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,dest) if REPORT.exists(): shutil.copyfile(REPORT,output/'previous_failed_report.md') REPORT.unlink() # Own just-created report, exact archived copy checked above; no pre-task report existed. result=dict(original,run_id=logger.run_id,report_recovery=dict(selection_run_id=original['run_id'], reason='original Task03 PNG filename link corrected; stored selection/evaluation reused unchanged', this_execution_fps_calls=0,performance_recomputed=False)) write_json(output/(STEM+'.json'),result) old_verification=json.loads((previous/'verification.json').read_text()) verification=dict(old_verification,report_recovery=result['report_recovery'],this_execution_fps_calls=0, required_tests=dict(old_verification['required_tests'],execution_run_id=original['run_id']), numeric_npz_byte_identical=prior.sha(output/(STEM+'.npz'))==prior.sha(previous/(STEM+'.npz')), frozen_algorithm_ast_unchanged=frozen_names,original_preservation=protected(baseline)) write_json(output/'verification.json',verification) write_json(output/'source_hashes.json',dict(selection_execution=original['run_id'], selection_source_hashes=json.loads((previous/'source_hashes.json').read_text()), report_sources=prior.hashes([Path(__file__),Path(__file__).with_name('test_local_structural_sampling.py')]), previous_execution_files_before=previous_hashes)) write_json(output/'git_end.json',dict(git_status=subprocess.check_output(['git','status','--short'],cwd=REPO).decode())) (output/'implementation.patch').touch();(output/(STEM+'.html')).touch() create_documents(output,result,old_verification['required_tests']['summary']) diff=b'' for path in (Path(__file__),Path(__file__).with_name('test_local_structural_sampling.py'),REPORT): delta=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,stdout=subprocess.PIPE) if delta.returncode!=1:raise ValueError('implementation diff capture failed') diff+=delta.stdout (output/'implementation.patch').write_bytes(diff) verification['document_checks']=verify_documents(output) require_equal(prior.hashes([REPO/p for p in previous_hashes]),previous_hashes,'failed numeric execution retained byte-exact') verification['original_preservation']=protected(baseline) write_json(output/'verification.json',verification) for path in sorted(output.rglob('*')): if path.is_file() and not path.name.endswith('.tracking.json') and path.name not in ('metadata.json','manifest.json','config.yaml','metrics.json'): logger.link_output(path,kind='reports') logger.link_output(REPORT,kind='reports') logger.record(source_run_id=BASELINE_ID,selection_run_id=original['run_id'], report_only=True,numeric_npz_byte_identical=True,this_execution_fps_calls=0) print(output,flush=True) return output
def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--baseline',required=True,type=Path,help='pre-implementation protected hashes and git_start.diff') parser.add_argument('--render-saved',type=Path,help='new report-only UUID from a preserved completed numeric attempt; no FPS/evaluation') args=parser.parse_args() if args.render_saved:postprocess(args.render_saved,args.baseline) else:run(args.baseline)
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134{ "status": "PASS", "compatibility": { "peg": { "status": "PASS", "pairs": 23876, "right": 11964, "down": 11912, "source_object_support_pixel_exact": true, "depth_jump_strict_gt": true, "reference_angles_exact_from_saved_reference_normals": true, "candidate_threshold_membership_exact": true, "saved_row_validity_membership_exact": true, "optimized_pair_numeric_identity": "N/A: full optimized PCA5 pair angles not stored", "optimized_connection_gate_identity": "N/A: endpoint candidate equality does not prove low-angle pair gate equality" }, "box": { "status": "PASS", "pairs": 23645, "right": 11835, "down": 11810, "source_object_support_pixel_exact": true, "depth_jump_strict_gt": true, "reference_angles_exact_from_saved_reference_normals": true, "candidate_threshold_membership_exact": true, "saved_row_validity_membership_exact": true, "optimized_pair_numeric_identity": "N/A: full optimized PCA5 pair angles not stored", "optimized_connection_gate_identity": "N/A: endpoint candidate equality does not prove low-angle pair gate equality" } }, "original_preservation": { "status": "PASS", "files": 4325, "all_sha256_unchanged": true }, "required_tests": { "summary": "Ran 93 tests in 0.704s; OK", "modules": [ "visual.runtime.test.test_geometry_aware_sampling", "visual.runtime.test.test_local_structural_sampling", "visual.runtime.test.test_priority_fps_metric_control", "visual.runtime.test.test_sampling", "visual.runtime.test.test_sampling_geometry", "visual.runtime.test.test_sampling_evaluation", "visual.runtime.test.test_priority_fps_trace", "visual.runtime.test.test_priority_fps_seed_control" ], "failed": 0 }, "all_C_exactly_one_patch": true, "quota_capacity_and_sum": true, "fixed_P_F_budgets": true, "P_subset_C_subset_X_F_subset_X": true, "source_pixel_xyz_object_role_alignment": true, "P_S_no_overlap": true, "npz_exact_readback": true, "pre_GT_archive_sha256_unchanged": true, "GT_independence": "full-rule synthetic annotation perturbation + annotation-free actual helpers; actual selection rerun=0", "joint_matching_and_reference_denominators": true, "baseline_and_UV_saved_metric_exact": true, "optimized_pair_identity": "N/A", "synthetic_performance": "N/A", "source_input_hashes_unchanged": true, "feature_unavailable_explicit": true, "preregistered_config_sha256": "ba1494d8a23de338afb4b2b8746275ce2e38b8a2c9e0a36b0c2ea9ad0b8bb2c9", "actual_fps_calls": { "global_baseline": 0, "priority_patch": 10, "global_fallback": 0, "surface": 2 }, "no_generalization_or_adoption_claim": true, "skipped": [ "simulator", "renderer", "GPU/CUDA/MPS/PCL", "normal/candidate extraction", "sweep", "other frames/episodes", "full-rule synthetic performance", "feature reconstruction", "production", "external upload", "install", "commit" ], "document_checks": { "status": "PASS", "html_links": 23, "markdown_links": 22, "png_decoded": { "patch_and_selection.png": [ 1400, 2380, 4 ], "peg_GT_auxiliary.png": [ 1540, 1960, 4 ], "candidate_3d_ecdf_tail.png": [ 1400, 1960, 4 ], "surface_depth_tradeoff.png": [ 1400, 2520, 4 ], "candidate_XZ_coverage.png": [ 1400, 1960, 4 ], "patch_quota.png": [ 1400, 2240, 4 ], "independent_regions.png": [ 1400, 2100, 4 ], "box_GT_auxiliary.png": [ 1540, 1960, 4 ] } }}123version https://git-lfs.github.com/spec/v1oid sha256:505329aaaab54bdd976a315454e4f5b8624f7a7b68e7e2016be99886e020e2cesize 198556512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.sampling import fps_indicesfrom visual.runtime.test.run_priority_fps_trace import trace_order
class PriorityFPSTraceTests(unittest.TestCase): def test_exact_tie_and_preselection_competition(self): points = np.array([[0., 0., 0.], [1., 0., 0.], [-1., 0., 0.], [0., 2., 0.]]) order = np.array([0, 3, 1, 2]) refs = np.array([[0, 0], [1, 0], [0, 1], [0, 0]], bool) with patch('visual.runtime.test.run_priority_fps_trace.np.random.default_rng', side_effect=AssertionError('trace must not consume RNG')): trace = trace_order(points, order, np.arange(4), np.ones(4), refs) self.assertIsNone(trace[0]['argmax_value_m2']) self.assertEqual(trace[1]['rim_A']['max_min_squared_distance_m2'], 1.) self.assertEqual(trace[1]['uncovered_rim_B']['remaining_count'], 2) self.assertEqual(trace[2]['exact_tie_count'], 2) self.assertEqual(trace[2]['tied_local_indices'], [1, 2]) self.assertEqual(trace[2]['first_tied_local_index'], 1) self.assertEqual(trace[2]['new_reference_ids'], [0]) self.assertEqual(trace[-1]['cumulative_reference_count'], 2)
def test_wrong_tie_winner_fails(self): points = np.array([[0., 0., 0.], [1., 0., 0.], [-1., 0., 0.], [0., 2., 0.]]) with self.assertRaisesRegex(AssertionError, 'first argmax'): trace_order(points, [0, 3, 2, 1], np.arange(4), np.ones(4), np.zeros((4, 0), bool))
def test_fps_consumes_one_initial_integer_draw(self): points = np.array([[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) actual_factory = np.random.default_rng calls = {'factory': 0, 'integers': 0} class Spy: def __init__(self, seed): self.inner = actual_factory(seed) def integers(self, *args, **kwargs): calls['integers'] += 1 return self.inner.integers(*args, **kwargs) def factory(seed): calls['factory'] += 1 return Spy(seed) with patch('visual.runtime.sampling.np.random.default_rng', side_effect=factory): order = fps_indices(points, 4, seed=17) self.assertEqual(calls, {'factory': 1, 'integers': 1}) self.assertEqual(int(order[0]), int(actual_factory(17).integers(len(points))))
def test_duplicate_xyz_and_annotation_independence(self): points = np.array([[0., 0., 0.], [0., 0., 0.], [1., 0., 0.], [-1., 0., 0.]], np.float32) order = fps_indices(points, 4, seed=5) self.assertEqual(len(np.unique(order)), 4) flat = np.arange(4) refs_a = np.zeros((4, 2), bool) refs_b = np.ones((4, 2), bool) a = trace_order(points, order, flat, np.ones(4), refs_a) b = trace_order(points, order, flat, np.ones(4), refs_b, {'negative': np.ones(4, bool)}) self.assertEqual([x['candidate_local_index'] for x in a], [x['candidate_local_index'] for x in b]) self.assertEqual([x['argmax_value_m2'] for x in a], [x['argmax_value_m2'] for x in b]) np.testing.assert_array_equal(order, fps_indices(points, 4, seed=5))
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Numerical contracts for evaluation truth, quantization and scale interventions."""from dataclasses import replaceimport unittest
import numpy as np
from visual.runtime.geometry import process_geometryfrom visual.runtime.test.normal_diagnostics import ( angular_error, box_primitives, metrics, normal_blockers, oracle, quantize, ray_box, real_regions, rim_region, subframe, synthetic_case, synthetic_frame,)
K = np.array([[256., 0, 256], [0, 256, 256], [0, 0, 1]])
class NormalDiagnosticsTest(unittest.TestCase): def test_paired_quantization_alone_creates_planar_variation(self): frame, truth, regions = synthetic_case('tilted', K, z0=.25, phase_m=.00025) before = frame.depth.copy() clean = metrics(process_geometry(frame).objects[0], regions['plane'], truth) q = replace(frame, depth=quantize(frame.depth)) noisy = metrics(process_geometry(q).objects[0], regions['plane'], truth) self.assertLess(clean['angular_error_deg']['p95'], .003) self.assertLess(clean['variation_deg']['p95'], .005) self.assertGreater(noisy['angular_error_deg']['p95'], 10) self.assertGreater(noisy['high_20_fraction_of_valid'], .1) self.assertEqual(clean['normals'], noisy['normals']) self.assertEqual(noisy['depth_discontinuity'], 0) np.testing.assert_array_equal(before, frame.depth) delta = q.depth.astype(float)-frame.depth self.assertLessEqual(delta.max(), 1e-7) self.assertGreaterEqual(delta.min(), -.0010001)
def test_front_plane_quantization_preserves_zero_variation(self): frame, truth, regions = synthetic_case('front', K, z0=.25025) result = process_geometry(replace(frame, depth=quantize(frame.depth))).objects[0] row = metrics(result, regions['plane'], truth) self.assertEqual(row['variation_deg']['max'], 0.) self.assertEqual(row['angular_error_deg']['max'], 0.)
def test_step_preserves_jump_with_missing_normals(self): frame, truth, regions = synthetic_case('step', K) f = process_geometry(frame).objects[0] row = metrics(f, regions['edge_band'], truth) self.assertEqual(row['depth_discontinuity'], 500) self.assertEqual(int(f.normal_valid[131:381, 255:257].sum()), 0) self.assertEqual(row['high_20_count'], 0) self.assertEqual(row['normal_valid_fraction'], 2/3)
def test_subsampling_keeps_source_pixel_centres_in_cv(self): frame, _, _ = synthetic_case('tilted', K) original = process_geometry(frame).geometry.xyz for stride in (2, 4): sub = subframe(frame, stride) np.testing.assert_array_equal(sub.depth, frame.depth[::stride, ::stride]) np.testing.assert_allclose(process_geometry(sub).geometry.xyz, original[::stride, ::stride], atol=0, rtol=0)
def test_ray_box_parallel_outside_and_signed_face(self): dirs = np.array([[0., 0, 1], [0, 1, 0], [0, 0, -1]]) z, face = ray_box(np.array([0., 0, -2]), dirs, np.zeros(3), np.ones(3)) self.assertEqual(z[0], 1.) self.assertEqual(face[0], 4) # -z face self.assertTrue(np.isnan(z[1:]).all())
def test_pose_oracle_and_plane_roi_do_not_depend_on_variation(self): k = np.array([[100., 0, 32], [0, 100, 32], [0, 0, 1]]) frame = synthetic_frame(np.full((64, 64), .3, np.float32), k, np.ones((64, 64), bool)) pose = np.array([0., 0, .4, 1, 0, 0, 0]) half = np.array([.07, .07, .1]) truth = oracle(frame, pose, [(np.zeros(3), half)]) gt = np.isfinite(truth['depth']) result = process_geometry(frame) regions, _, _ = real_regions(frame, result, gt, truth, 0, half) self.assertGreater(regions['plane_interior'].sum(), 100) np.testing.assert_allclose(truth['depth'][gt], .3, atol=1e-14) error = angular_error(result.objects[0].normals, truth['normals']) self.assertLess(np.nanmax(error[regions['plane_interior']]), 1e-5) result.objects[0].normal_variation_rad[:] = 2. regions2, _, _ = real_regions(frame, result, gt, truth, 0, half) np.testing.assert_array_equal(regions['plane_interior'], regions2['plane_interior'])
def test_hollow_box_oracle_has_open_hole_and_physical_rim(self): # Local x points toward camera, local y/z span the image. k = np.array([[100., 0, 64], [0, 100, 64], [0, 0, 1]]) frame = synthetic_frame(np.full((128, 128), .4, np.float32), k, np.ones((128, 128), bool)) # Rotation around local y by +90deg: world x<-local z, world z<- -local x. pose = np.array([0., 0, .5, np.sqrt(.5), 0, np.sqrt(.5), 0]) truth = oracle(frame, pose, box_primitives(.1, .025, np.array([0., 0.]))) self.assertTrue(np.isnan(truth['depth'][64, 64])) self.assertAlmostEqual(truth['depth'][64, 80], .4) visible = np.isfinite(truth['depth']) rim, _ = rim_region(frame, truth, visible, pose, .1, .025, np.array([0., 0.])) self.assertGreater(rim.sum(), 30) self.assertFalse(rim[64, 80]) # Outer face far from physical aperture edge. hidden, _ = rim_region(frame, truth, np.zeros_like(visible), pose, .1, .025, np.array([0., 0.])) self.assertEqual(hidden.sum(), 0)
def test_mask_cut_only_removes_support_and_reasons_cover_loss(self): frame, truth, _ = synthetic_case('front', K, z0=.25025) mask = frame.masks[0].copy(); mask[:, 256:] = False result = process_geometry(replace(frame, masks={0: mask})) row = metrics(result.objects[0], mask, truth) self.assertEqual(row['high_5_count'], 0) self.assertEqual(row['depth_discontinuity'], 0) blockers = normal_blockers(result, 0) self.assertEqual(blockers['unexplained'], 0) self.assertEqual(blockers['unavailable'], blockers['reasons_nonexclusive']['mask'])
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475"""Task 02-A: paired quantization and saved RGB-D normal reliability diagnostics.
CPU only, fresh UUID output directory, no inference, estimator changes or uploads.Run with WANDB_MODE=disabled for entirely local experiment tracking."""from __future__ import annotations
import argparsefrom dataclasses import fields, replaceimport htmlimport importlib.metadataimport jsonfrom pathlib import Pathimport platformimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.patches import Patchimport numpy as np
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import GeometryParameters, process_geometryfrom visual.runtime.rgbd import BOX, PEG, iter_saved_rgbdfrom visual.runtime.test.normal_diagnostics import ( angular_error, box_primitives, dilate, endpoints, erode, metrics, normal_blockers, oracle, pose_rotation, quantize, real_regions, rim_region, scale_probe, stats, synthetic_case,)
OBJECTS = {'peg': PEG, 'box': BOX}COLORS = {'plane': '#00ffcc', 'seam': '#ff8000', 'rim': '#ffdd00', 'occlusion': '#ff55cc', 'contamination': '#ff2222', 'mask_cut': '#4488ff'}
def save_json(path, value): path.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n', encoding='utf-8')
def summarize_rows(rows, values, errors=None): """Micro averages and pooled quantiles; no averaging per-frame percentiles.""" keys = ('region_pixels', 'points', 'normals', 'variation_valid', 'depth_discontinuity', 'mask_boundary', 'invalid_depth_boundary', 'incomplete_normal_neighbours', 'high_5_count', 'high_10_count', 'high_20_count', 'high_30_count', 'jump_or_high20_count') total = {k: sum(r[k] for r in rows) for k in keys} n, nv, vv = total['points'], total['normals'], total['variation_valid'] total.update(frames=len(rows), normal_valid_fraction=nv/n if n else None, variation_valid_fraction=vv/n if n else None, variation_deg=stats(np.concatenate(values))) rn = total['region_pixels'] total.update(observed_fraction_of_region=n/rn if rn else None, normal_fraction_of_region=nv/rn if rn else None, jump_or_high20_fraction_of_region=total['jump_or_high20_count']/rn if rn else None) total['variation_hist_5deg'] = np.sum([r['variation_hist_5deg'] for r in rows], axis=0).tolist() for t in (5, 10, 20, 30): total[f'high_{t}_fraction_of_valid'] = total[f'high_{t}_count']/vv if vv else None total[f'high_{t}_fraction_of_points'] = total[f'high_{t}_count']/n if n else None if errors is not None: total['angular_error_deg'] = stats(np.concatenate(errors)) return total
def synthetic_experiment(output, intrinsic): rows, primaries, scales = [], {}, [] for kind in ('front', 'tilted', 'crease', 'step'): for z in (.2, .25, .35, .6, 1.): for phase in (0., .00025, .0005, .00075): frame, truth, regions = synthetic_case(kind, intrinsic, z0=z, phase_m=phase) original = process_geometry(frame) float_feature = original.objects[PEG] runs = {'float': (frame, original)} for mode in ('floor', 'nearest'): changed = replace(frame, depth=quantize(frame.depth, mode)) runs[mode] = (changed, process_geometry(changed)) row = dict(geometry=kind, z0_m=z, phase_m=phase, conditions={}) for mode, (observation, result) in runs.items(): f = result.objects[PEG] row['conditions'][mode] = dict( regions={k: metrics(f, m, truth) for k, m in regions.items()}, all_support=metrics(f, f.valid_points, truth), depth_change_mm=stats((observation.depth-frame.depth)[frame.masks[PEG]]*1000)) rows.append(row) if z == .25 and phase == .00025: primaries[kind] = (frame, truth, regions, runs) if kind == 'tilted' and phase == .00025: qframe, qresult = runs['floor'] scales.append(dict(z0_m=z, rows=scale_probe(qframe, qresult.objects[PEG], PEG, regions['plane'], truth))) # Controls: observation cuts of an exactly flat surface do not create a corner. frame, truth, _ = synthetic_case('front', intrinsic, z0=.25025) mask = frame.masks[PEG].copy(); mask[:, 256:] = False cut = replace(frame, masks={PEG: mask}) hole_depth = frame.depth.copy(); hole_depth[240:272, 240:272] = 0 hole = replace(frame, depth=hole_depth) controls = {} for name, observation in [('mask_cut', cut), ('invalid_depth_hole', hole)]: result = process_geometry(observation) controls[name] = dict(metrics=metrics(result.objects[PEG], observation.masks[PEG], truth), blockers=normal_blockers(result, PEG)) synthetic_plot(output/'synthetic.png', primaries) return dict(primary_z0_m=.25, primary_phase_m=.00025, primary_quantization='floor', depth_sweep_m=[.2, .25, .35, .6, 1.], phase_sweep_m=[0, .00025, .0005, .00075], slope_xy=[.4, -.25], crease_slopes_xy=[[-.6, .15], [.6, .15]], step_m=.05, mask_bounds_vu=[128, 384, 128, 384], edge_band_half_width_px=3, planar_border_margin_px=3, controls=controls, cases=rows, scale_sweep=scales)
def synthetic_plot(path, primary): fig, axes = plt.subplots(4, 5, figsize=(18, 13), constrained_layout=True) for axs, (kind, (frame, truth, regions, runs)) in zip(axes, primary.items()): clean, q = runs['float'][1].objects[PEG], runs['floor'][1].objects[PEG] images = [np.where(frame.masks[PEG], frame.depth, np.nan)*1000, np.rad2deg(clean.normal_variation_rad), np.rad2deg(q.normal_variation_rad), angular_error(q.normals, truth), np.where(q.valid_points, q.normal_valid.astype(float)+2*q.depth_discontinuity, np.nan)] titles = [f'{kind}: float depth (mm)', 'Float variation (deg)', '1mm floor variation (deg)', '1mm floor normal error (deg)', 'Normal valid=1, depth jump=+2'] for j, (ax, a, title) in enumerate(zip(axs, images, titles)): im = ax.imshow(a, vmin=0 if j in (1, 2, 3, 4) else None, vmax=45 if j in (1, 2, 3) else 3 if j == 4 else None, cmap='turbo') ax.set(xlim=(122, 390), ylim=(390, 122), title=title); ax.axis('off') fig.colorbar(im, ax=ax, shrink=.7) fig.suptitle('Paired synthetic observations: same camera, masks and extractor; only depth quantized\n' 'fx=fy=256; z0=250.25mm; no noise or filtering', fontsize=14) fig.savefig(path, dpi=130); plt.close(fig)
def real_plot(path, frame, result, regions, maps, oracles): fig, axes = plt.subplots(3, 4, figsize=(18, 14), constrained_layout=True) axes = axes.ravel() axes[0].imshow(frame.rgb); axes[0].set_title('RGB with evaluation regions') plane = regions['peg']['plane_interior'] overlays = dict(plane=plane, seam=regions['peg']['face_seam_2px'], rim=regions['box']['hole_rim'], occlusion=regions['peg']['occlusion_2px']|regions['box']['occlusion_2px'], contamination=(result.objects[PEG].valid_points & regions['peg']['contamination'])| (result.objects[BOX].valid_points & regions['box']['contamination']), mask_cut=regions['peg']['same_plane_tracker_cut_2px']) for name, mask in overlays.items(): if mask.any(): axes[0].contour(mask, levels=[.5], colors=[COLORS[name]], linewidths=.65) axes[0].legend(handles=[Patch(color=COLORS[k], label=k) for k in COLORS], fontsize=8, loc='upper right') support = result.objects[PEG].valid_points | result.objects[BOX].valid_points d = np.where(support, frame.depth*1000, np.nan) im = axes[1].imshow(d, cmap='turbo', vmin=150, vmax=700) axes[1].set_title('Observed depth (mm), fixed scale'); fig.colorbar(im, ax=axes[1], shrink=.7) for name, base in [('peg', 2), ('box', 7)]: f = result.objects[OBJECTS[name]] var = np.rad2deg(f.normal_variation_rad) error = angular_error(f.normals, oracles[name]['normals']) error[~regions[name]['gt_visible']] = np.nan panel = [(var, 'normal variation (deg)', 45, 'turbo'), (np.where(f.valid_points, f.normal_valid, np.nan), 'normal validity', 1, 'viridis'), (error, 'normal error vs GT (deg)', 45, 'turbo')] for j, (a, title, vmax, cmap) in enumerate(panel): im = axes[base+j].imshow(a, cmap=cmap, vmin=0, vmax=vmax) axes[base+j].set_title(f'{name}: {title}'); fig.colorbar(im, ax=axes[base+j], shrink=.7) boundary = np.zeros((*frame.depth.shape, 3)) boundary[..., 0] = f.depth_discontinuity boundary[..., 1] = f.mask_boundary boundary[..., 2] = f.depth_validity_boundary axes[base+3].imshow(boundary) axes[base+3].set_title(f'{name}: jump / mask / invalid = R/G/B') # Peg-only zoom shows quantization terraces and selected broad planar interior. y, x = np.nonzero(plane) if len(x): lo_x, hi_x, lo_y, hi_y = max(0, x.min()-8), x.max()+8, max(0, y.min()-8), y.max()+8 else: lo_x, hi_x, lo_y, hi_y = 0, 511, 0, 511 f = result.objects[PEG] axes[6].imshow(np.where(f.valid_points, frame.depth*1000, np.nan), cmap='turbo') if plane.any(): axes[6].contour(plane, [.5], colors=['#00ffcc'], linewidths=.6) axes[6].set_title('Peg depth terraces; cyan=verified plane ROI') axes[6].set(xlim=(lo_x, hi_x), ylim=(hi_y, lo_y)) axes[11].imshow(np.rad2deg(f.normal_variation_rad), cmap='turbo', vmin=0, vmax=45) if plane.any(): axes[11].contour(plane, [.5], colors=['#00ffcc'], linewidths=.6) axes[11].set_title('Same Peg crop: variation (0-45 deg)') axes[11].set(xlim=(lo_x, hi_x), ylim=(hi_y, lo_y)) # Full panels share a fixed object viewport for comparisons between frames. for i, ax in enumerate(axes): if i not in (6, 11): ax.set(xlim=(0, 511), ylim=(511, 0)) ax.axis('off') fig.suptitle(f'Source {frame.source_frame}: observed features; GT used only to evaluate regions\n' 'Black validity=unavailable; NaN variation is missing, not zero. Scales fixed across frames.', fontsize=14) fig.savefig(path, dpi=130); plt.close(fig)
def boundary_plot(path, frame, result, regions): fig, axes = plt.subplots(2, 4, figsize=(16, 10), constrained_layout=True) for axs, (name, object_id) in zip(axes, OBJECTS.items()): f = result.objects[object_id] region = regions[name] axs[0].imshow(frame.rgb) for key, color in [('face_seam_2px', '#ff8000'), ('occlusion_2px', '#ff55cc'), ('same_plane_tracker_cut_2px', '#4488ff'), ('hole_rim', '#ffff00')]: if key in region and region[key].any(): axs[0].contour(region[key], [.5], colors=[color], linewidths=.8) axs[0].set_title(f'{name}: GT seam=orange, rim=yellow\nocclusion=pink, same-face mask cut=blue') im = axs[1].imshow(np.rad2deg(f.normal_variation_rad), cmap='turbo', vmin=0, vmax=45) axs[1].set_title('Observed normal variation (deg)'); fig.colorbar(im, ax=axs[1], shrink=.65) axs[2].imshow(np.where(f.valid_points, f.normal_valid, np.nan), cmap='viridis', vmin=0, vmax=1) axs[2].set_title('Normal valid: yellow=1, dark=0') boundary = np.stack((f.depth_discontinuity, f.mask_boundary, f.depth_validity_boundary), -1).astype(float) axs[3].imshow(boundary) axs[3].set_title('Observed jump / mask / invalid = R/G/B') contour = region.get('hole_rim', region['face_seam_2px']) if contour.any(): for ax in axs[1:]: ax.contour(contour, [.5], colors=['white'], linewidths=.65) y, x = np.nonzero(f.object_mask | region['gt_visible']) bounds = (max(0, x.min()-8), min(511, x.max()+8), min(511, y.max()+8), max(0, y.min()-8)) if len(x) else (0, 511, 511, 0) for ax in axs: ax.set(xlim=bounds[:2], ylim=bounds[2:]); ax.axis('off') fig.suptitle(f'Frame {frame.source_frame}: boundary detail; evaluation regions may overlap\n' 'White outline in feature maps: visible physical hole rim (Box) or face seam (Peg).', fontsize=13) fig.savefig(path, dpi=150); plt.close(fig)
def profile_plot(path, frame, result, regions, truth): # Dominant face and its longer image axis, selected independently of features. plane = regions['plane_interior'] if not plane.any(): return labels, counts = np.unique(truth['face'][plane], return_counts=True) face = labels[counts.argmax()] face_roi = plane & (truth['face'] == face) row_counts, col_counts = face_roi.sum(axis=1), face_roi.sum(axis=0) along_v = col_counts.max() > row_counts.max() fixed = int(np.argmax(col_counts if along_v else row_counts)) line_roi = face_roi[:, fixed] if along_v else face_roi[fixed] coords = np.flatnonzero(line_roi) lo, hi = int(coords.min()), int(coords.max()) coord = np.arange(lo, hi+1) vi, ui = (coord, fixed) if along_v else (fixed, coord) good = line_roi[coord] f = result.objects[PEG] fig, axes = plt.subplots(3, 1, figsize=(11, 7), sharex=True, constrained_layout=True) axes[0].plot(coord, frame.depth[vi, ui]*1000, '.-', label='observed 1mm depth', ms=3) axes[0].plot(coord, truth['depth'][vi, ui]*1000, label='analytic GT face, evaluation only', lw=1) axes[0].set_ylabel('Depth (mm)'); axes[0].legend(fontsize=8) for c, label in enumerate(('nx', 'ny', 'nz')): axes[1].plot(coord, np.where(good, f.normals[vi, ui, c], np.nan), label=label) axes[1].set_ylabel('CV unit normal'); axes[1].legend(fontsize=8, ncol=3) axes[2].plot(coord, np.where(good, np.rad2deg(f.normal_variation_rad[vi, ui]), np.nan), label='variation') axis_name, fixed_name = ('v', 'u') if along_v else ('u', 'v') axes[2].axhline(20, color='r', ls=':', lw=1) axes[2].set(ylabel='Variation (deg)', xlabel=f'Source {axis_name}') fig.suptitle(f'Frame {frame.source_frame}, {fixed_name}={fixed}, GT signed face {face}: verified planar pixels only') fig.savefig(path, dpi=140); plt.close(fig) return dict(varying_axis=axis_name, fixed_axis=fixed_name, fixed_index=fixed, signed_face=int(face), axis_min=lo, axis_max=hi, valid_planar_coordinates=coord[good].tolist())
def evaluate(episode_path, masks_path, *, output_root, camera='base_camera', selected=(0, 15, 45, 80, 120)): episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() # Check source identity before producing a new evaluation run. tracking_path = masks_path.with_name('tracking.json') if tracking_path.exists(): tracking = json.loads(tracking_path.read_text()) if tracking.get('camera') not in (None, camera): raise ValueError('camera differs from tracking.json') original = Path(tracking.get('input') or episode_path) if original.is_file() and original.resolve() != episode_path and digests(original)[1] != digests(episode_path)[1]: raise ValueError('episode differs from tracking.json') with np.load(episode_path, allow_pickle=False) as archive: required = [f'{camera}/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed'] missing = set(required)-set(archive.files) if missing: raise ValueError(f'evaluation GT missing: {sorted(missing)}') gt = {k: archive[k] for k in required} with np.load(masks_path, allow_pickle=False) as archive: sources = archive['source_frame'] if sources.ndim != 1 or not len(sources) or len(np.unique(sources)) != len(sources): raise ValueError('source_frame must be unique and nonempty') if set(selected)-set(sources.tolist()): raise ValueError('selected sources absent from tracking archive') iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) first = next(iterator) from itertools import chain config = dict(task='02-A', input=str(episode_path), masks=str(masks_path), camera=camera, input_sha256=digests(episode_path)[1], masks_sha256=digests(masks_path)[1], baseline_geometry_sha256=digests(REPO/'visual/runtime/geometry.py')[1], selected_sources=list(selected), intrinsic=first.intrinsic.tolist(), parameters=vars(GeometryParameters()), device='cpu', gpu_executed=False, python=platform.python_version(), numpy=np.__version__, platform=platform.platform(), scipy=importlib.metadata.version('scipy'), matplotlib=matplotlib.__version__, roi_depth_residual_m=.0015, roi_metric_edge_margin_m=.004, roi_raster_erosion_px=3, rim_metric_radius_m=.004, rim_raster_radius_px=2, high_variation_degrees=[5, 10, 20, 30], actual_feature_inputs='recorded depth, intrinsic and original tracker masks only', gt_use='evaluation regions, oriented angular truth, analytic depth residuals only') config['diagnostic_source_sha256'] = {str(p.relative_to(REPO)): digests(p)[1] for p in (Path(__file__), Path(__file__).with_name('normal_diagnostics.py'), Path(__file__).with_name('test_normal_diagnostics.py'))} with ExperimentLogger(team='visual', config=config, seed=int(gt['seed']), model='task02a_unchanged_organized_geometry', job_type='evaluate') as logger: output = Path(output_root).resolve()/logger.run_id output.mkdir(parents=True, exist_ok=False) print(f'Output: {output}', flush=True) synthetic = synthetic_experiment(output, first.intrinsic) records, pooled, pooled_errors = [], {}, {} for frame in chain((first,), iterator): s = frame.source_frame result = process_geometry(frame) # Actual feature computation: no GT. half = gt['peg_half_sizes'] box_rotation = pose_rotation(gt['box_pose'][s]) hole_centre = ((gt['box_hole_pose'][s, :3]-gt['box_pose'][s, :3]) @ box_rotation)[1:] boxes = box_primitives(float(half[0]), float(gt['box_hole_radii']), hole_centre) truths = dict(peg=oracle(frame, gt['peg_pose'][s], [(np.zeros(3), half)]), box=oracle(frame, gt['box_pose'][s], boxes)) record = dict(source_frame=s, frame_idx=frame.frame_idx, timestamp=frame.timestamp, overlap_pixels=int(result.geometry.overlap_mask.sum()), objects={}) selected_regions, maps, plane_base = {}, {}, None for name, object_id in OBJECTS.items(): f = result.objects[object_id] seg = gt[f'{camera}/seg'][s] == int(gt[f'{name}_id']) regions, base, boundary_maps = real_regions(frame, result, seg, truths[name], object_id, half=half if name == 'peg' else None) if name == 'peg': plane_base = base if name == 'box': rim, projected = rim_region(frame, truths[name], regions['gt_visible'], gt['box_pose'][s], float(half[0]), float(gt['box_hole_radii']), hole_centre) regions['hole_rim'] = rim regions['hole_rim_normal_valid'] = rim & f.normal_valid regions['hole_rim_normal_invalid'] = rim & ~f.normal_valid boundary_maps['rim_projection'] = projected selected_regions[name], maps[name] = regions, boundary_maps rows = {k: metrics(f, m, truths[name]['normals'] if k.startswith('plane_') else None) for k, m in regions.items()} visible = regions['gt_visible'] residual = (frame.depth-truths[name]['depth'])*1000 observed_z, analytic_z = frame.depth[visible], truths[name]['depth'][visible] expected_floor = (np.floor(truths[name]['depth']*1000)/1000).astype(np.float32) floor_agree_map = visible & (frame.depth == expected_floor) floor_agree = floor_agree_map[visible] row = dict(mask_pixels=int(f.object_mask.sum()), gt_pixels=int(seg.sum()), analytic_hit_gt_fraction=float(np.mean(np.isfinite(truths[name]['depth'][seg]))) if seg.any() else None, depth_consistent_gt_fraction=float(visible.sum()/seg.sum()) if seg.any() else None, depth_residual_mm=stats(residual[visible]), mm_grid_residual_m=stats(np.abs(observed_z-np.rint(observed_z.astype(float)*1000)/1000)), analytic_floor_match_fraction=float(floor_agree.mean()) if visible.any() else None, analytic_floor_match_count=int(floor_agree.sum()), regions=rows, blockers=normal_blockers(result, object_id)) if name == 'peg': plane = regions['plane_interior'] # Derivative geometry: 1-pixel lateral spacing at the same z. row['plane_depth_m'] = stats(frame.depth[plane]) row['plane_lateral_pixel_spacing_mm'] = stats(frame.depth[plane]/frame.intrinsic[0, 0]*1000) row['q_over_2pixel_lateral_span'] = stats(.001/(2*frame.depth[plane]/frame.intrinsic[0, 0])) vv = plane & f.normal_variation_valid matched = vv & erode(floor_agree_map, 2) high = vv & (np.rad2deg(f.normal_variation_rad) > 20) row['plane_floor_dependency_match'] = dict( variation_valid=int(vv.sum()), matched=int(matched.sum()), fraction=float(matched.sum()/vv.sum()) if vv.any() else None, high20=int(high.sum()), high20_matched=int((high & matched).sum()), high20_matched_fraction=float((high & matched).sum()/high.sum()) if high.any() else None) # Same-plane mask cuts and occlusions are evaluated separately. record['objects'][name] = row for region_name, roi in regions.items(): key = f'{name}/{region_name}' vv = roi & f.normal_variation_valid & f.valid_points pooled.setdefault(key, []).append(np.rad2deg(f.normal_variation_rad[vv])) if region_name.startswith('plane_'): nv = roi & f.normal_valid & f.valid_points pooled_errors.setdefault(key, []).append(angular_error(f.normals[nv], truths[name]['normals'][nv])) if s in selected: record['scale_probe'] = scale_probe(frame, result.objects[PEG], PEG, plane_base, truths['peg']['normals']) record['profile'] = profile_plot(output/f'f{s:04d}_profile.png', frame, result, selected_regions['peg'], truths['peg']) real_plot(output/f'f{s:04d}.png', frame, result, selected_regions, maps, truths) boundary_plot(output/f'f{s:04d}_boundaries.png', frame, result, selected_regions) arrays = dict(source_frame=np.array(s), depth_m=frame.depth, intrinsic=frame.intrinsic) for name, object_id in OBJECTS.items(): f = result.objects[object_id] arrays.update({f'{name}/{field.name}': getattr(f, field.name) for field in fields(f)}) arrays.update({f'evaluation/{name}/{k}': v for k, v in selected_regions[name].items()}) arrays[f'evaluation/{name}/analytic_depth_m'] = truths[name]['depth'] arrays[f'evaluation/{name}/face_id'] = truths[name]['face'] np.savez_compressed(output/f'f{s:04d}.npz', **arrays) records.append(record) if len(records) == 1 or len(records) % 20 == 0: print(f'Real frames: {len(records)}/{len(sources)}', flush=True) summary = {} for key, values in pooled.items(): name, region = key.split('/') summary[key] = summarize_rows([r['objects'][name]['regions'][region] for r in records], values, pooled_errors.get(key)) data = dict(run_id=logger.run_id, config=config, git_commit=logger.metadata['git_commit'], git_dirty=logger.metadata['git_dirty'], synthetic=synthetic, evaluated_frames=len(records), selected_source_frames=list(selected), summary=summary, frames=records) save_json(output/'diagnostics.json', data) distribution_plot(output/'distributions.png', data) scale_plot(output/'scale_probe.png', data) write_html(output/'diagnostics.html', data) for path in sorted(output.iterdir()): logger.link_output(path, kind='metrics' if path.suffix == '.json' else None) logger.log(summary, prefix='eval/task02a') logger.record(dataset_sha256=config['input_sha256'], masks_sha256=config['masks_sha256'], evaluation_device='cpu', evaluated_frames=len(records), gpu_executed=False) return output
def distribution_plot(path, data): fig, axes = plt.subplots(2, 2, figsize=(13, 9), constrained_layout=True) xs = np.arange(2.5, 180, 5) for name, ax in zip(('peg', 'box'), axes[0]): keys = ['all', 'plane_interior', 'contamination', 'face_seam_2px', 'occlusion_2px', 'hole_rim'] for key in keys: r = data['summary'].get(f'{name}/{key}') if r and r['variation_valid']: ax.plot(xs, np.array(r['variation_hist_5deg'])/r['variation_valid'], label=f'{key} (n={r["variation_valid"]})') ax.set(xlim=(0, 90), xlabel='Normal variation (deg)', ylabel='Fraction per 5 deg bin', title=f'{name}: pooled 121 frames') ax.legend(fontsize=7) sources = [r['source_frame'] for r in data['frames']] for key in ('all', 'plane_interior', 'contamination', 'face_seam_2px', 'occlusion_2px'): ys = [r['objects']['peg']['regions'][key]['high_20_fraction_of_valid'] for r in data['frames']] axes[1, 0].plot(sources, [np.nan if v is None else v for v in ys], label=key, lw=1) axes[1, 0].set(xlabel='Source frame', ylabel='Fraction >20 deg / valid variation', title='Peg: time distribution') axes[1, 0].legend(fontsize=7) for name, key in [('peg', 'all'), ('box', 'all'), ('box', 'hole_rim')]: ys = [r['objects'][name]['regions'][key]['normal_valid_fraction'] for r in data['frames']] axes[1, 1].plot(sources, [np.nan if v is None else v for v in ys], label=f'{name}/{key}') axes[1, 1].set(xlabel='Source frame', ylabel='Normals / observed points', title='Coverage (missing remains missing)', ylim=(-.05, 1.05)) axes[1, 1].legend(fontsize=8) fig.savefig(path, dpi=140); plt.close(fig)
def scale_plot(path, data): fig, axes = plt.subplots(1, 3, figsize=(15, 5), constrained_layout=True) for r in data['frames']: if 'scale_probe' not in r: continue rows = r['scale_probe'] x = [v['stride_px'] for v in rows] for ax, key in zip(axes[:2], ('angular_error_deg', 'variation_deg')): y = [v['larger_spacing'][key]['p95'] for v in rows] ax.plot(x, y, 'o-', label=f'f{r["source_frame"]}') axes[0].set(ylabel='p95 normal error (deg)', xlabel='Neighbour spacing (px)', title='Verified flat Peg ROI, shared safe region') axes[1].set(ylabel='p95 variation (deg)', xlabel='Neighbour spacing (px)', title='No averaging; same baseline extractor') for s in (1, 2, 4): rows = data['synthetic']['scale_sweep'] axes[2].plot([r['z0_m'] for r in rows], [next(v for v in r['rows'] if v['stride_px']==s)['larger_spacing']['variation_deg']['p95'] for r in rows], 'o-', label=f'synthetic stride={s}') axes[2].set(xlabel='Central depth (m)', ylabel='p95 variation (deg)', title='Tilted plane, fixed K and 1mm quantization') for ax in axes: ax.legend(fontsize=8); ax.grid(alpha=.2) fig.savefig(path, dpi=140); plt.close(fig)
def write_html(path, data): images = ['synthetic.png', 'distributions.png', 'scale_probe.png'] images += [f'f{s:04d}{suffix}.png' for s in data['selected_source_frames'] for suffix in ('', '_boundaries', '_profile')] body = ''.join(f'<p><a href="{p}"><img src="{p}" alt="{p}"></a></p>' for p in images if (path.parent/p).exists()) path.write_text(f'''<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task 02-A</title><style>body{{font:15px system-ui;max-width:1600px;margin:24px auto;padding:16px}}img{{width:100%}}pre{{white-space:pre-wrap}}</style><h1>Task 02-A — normal reliability and depth quantization</h1><p>Run {data['run_id']}; all {data['evaluated_frames']} saved frames; unchanged CPU NumPy extractor.<a href="diagnostics.json">Full numeric metrics, counts, histograms and parameters</a>.</p><p>Actual feature inputs are recorded depth, intrinsic and tracker masks only. GT defines evaluation regionsand oriented normal truth. Plane ROI: visible cuboid face, depth residual ≤1.5mm, 4mm from other faces,then 3px erosion independently per signed face. No selection by measured normal or variation.Hole rim requires analytic physical line proximity (4mm, 2px), not just a segmentation contour.</p><p>20° is a diagnostic threshold, not an edge class. All 5/10/20/30° rates and missing support are reported.Boundary ROIs can overlap; counts are not additive. Pooled values are pixel-frame weighted.Subsampling probes preserve pixel centres and compare baseline values on the same centres; they changeboth stencil span and normal-comparison separation. Only verified planar regions are compared.</p><p>GT annotations and analytic depth in NPZ are under evaluation/. They never replace observed depth.No smoothing, PCL, new production estimator, structural classification, sampling or Graph changes.</p>{body}<details><summary>Configuration</summary><pre>{html.escape(json.dumps(data['config'], indent=2))}</pre></details></html>''', encoding='utf-8')
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, default=REPO/'visual/data/step2/ep000.npz') parser.add_argument('--masks', type=Path, default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') parser.add_argument('--camera', default='base_camera') parser.add_argument('--out', type=Path, default=REPO/'visual/results/normal_diagnostics') args = parser.parse_args() print(evaluate(args.input, args.masks, output_root=args.out, camera=args.camera))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""Fused CUDA patch-local PCA5. Imported only for an explicit CUDA backend.
One warp per observed centre: exact 25-bit connectivity, float64 covariance,closed-form symmetric eigensystem, and a guarded Torch/LAPACK fallback."""import torchimport tritonimport triton.language as tlfrom triton.language.extra.cuda import libdevice
@triton.jitdef _pca5(XYZ, SUPPORT, CENTRES, NORMALS, VALID, COV, FALLBACK, H:tl.constexpr, W:tl.constexpr, ABS:tl.constexpr, REL:tl.constexpr): pid=tl.program_id(0) cv=tl.load(CENTRES+pid*2);cu=tl.load(CENTRES+pid*2+1) k=tl.arange(0,32);r=k//5;c=k%5 v=cv+r-2;u=cu+c-2 inside=(k<25)&(v>=0)&(v<H)&(u>=0)&(u<W) index=v*W+u available=tl.load(SUPPORT+index,inside,other=0) x=tl.load(XYZ+index*3,inside,other=0).to(tl.float64) y=tl.load(XYZ+index*3+1,inside,other=0).to(tl.float64) z=tl.load(XYZ+index*3+2,inside,other=0).to(tl.float64) right_inside=inside&(c<4)&(u+1<W) down_inside=inside&(r<4)&(v+1<H) rs=tl.load(SUPPORT+index+1,right_inside,other=0) ds=tl.load(SUPPORT+index+W,down_inside,other=0) rz=tl.load(XYZ+(index+1)*3+2,right_inside,other=0).to(tl.float64) dz=tl.load(XYZ+(index+W)*3+2,down_inside,other=0).to(tl.float64) right_ok=available&rs&right_inside&(tl.abs(z-rz)<=ABS+REL*tl.minimum(z,rz)) down_ok=available&ds&down_inside&(tl.abs(z-dz)<=ABS+REL*tl.minimum(z,dz)) bits=1<<k right=tl.sum(tl.where(right_ok,bits,0),0) down=tl.sum(tl.where(down_ok,bits,0),0) reached=1<<12 for _ in range(24): reached=reached|((reached&right)<<1)|((reached>>1)&right)|((reached&down)<<5)|((reached>>5)&down) component=(k<25)&((reached&bits)!=0) count=tl.sum(component.to(tl.int32),0) cx=tl.load(XYZ+(cv*W+cu)*3).to(tl.float64) cy=tl.load(XYZ+(cv*W+cu)*3+1).to(tl.float64) cz=tl.load(XYZ+(cv*W+cu)*3+2).to(tl.float64) dx=tl.where(component,x-cx,0);dy=tl.where(component,y-cy,0);ddz=tl.where(component,z-cz,0) den=tl.maximum(count,1).to(tl.float64) mx=tl.sum(dx,0)/den;my=tl.sum(dy,0)/den;mz=tl.sum(ddz,0)/den xx=tl.sum(dx*dx,0)/den-mx*mx;yy=tl.sum(dy*dy,0)/den-my*my;zz=tl.sum(ddz*ddz,0)/den-mz*mz xy=tl.sum(dx*dy,0)/den-mx*my;xz=tl.sum(dx*ddz,0)/den-mx*mz;yz=tl.sum(dy*ddz,0)/den-my*mz for j in tl.static_range(9): value=tl.where(j==0,xx,tl.where(j==1,xy,tl.where(j==2,xz,tl.where(j==3,xy,tl.where(j==4,yy,tl.where(j==5,yz,tl.where(j==6,xz,tl.where(j==7,yz,zz)))))))) tl.store(COV+pid*9+j,value) scale=tl.maximum(tl.maximum(tl.maximum(tl.abs(xx),tl.abs(yy)),tl.maximum(tl.abs(zz),tl.abs(xy))),tl.maximum(tl.abs(xz),tl.abs(yz))) s=tl.where(scale>0,scale,1.) a=xx/s;b=yy/s;d=zz/s;e=xy/s;f=xz/s;g=yz/s q=(a+b+d)/3. aa=a-q;bb=b-q;dd=d-q p=libdevice.sqrt((aa*aa+bb*bb+dd*dd+2*(e*e+f*f+g*g))/6.) pp=tl.where(p>0,p,1.) ca=aa/pp;cb=bb/pp;cd=dd/pp;ce=e/pp;cf=f/pp;cg=g/pp determinant=ca*(cb*cd-cg*cg)-ce*(ce*cd-cg*cf)+cf*(ce*cg-cb*cf) phi=libdevice.acos(tl.minimum(1.,tl.maximum(-1.,determinant/2.)))/3. largest=q+2*p*libdevice.cos(phi) smallest=q+2*p*libdevice.cos(phi+2.0943951023931953) middle=3*q-smallest-largest ra=a-smallest;rb=b-smallest;rd=d-smallest x1=e*g-f*rb;y1=f*e-ra*g;z1=ra*rb-e*e x2=e*rd-f*g;y2=f*f-ra*rd;z2=ra*g-e*f x3=rb*rd-g*g;y3=g*f-e*rd;z3=e*g-rb*f n1=x1*x1+y1*y1+z1*z1;n2=x2*x2+y2*y2+z2*z2;n3=x3*x3+y3*y3+z3*z3 use1=(n1>=n2)&(n1>=n3);use2=n2>=n3 nx=tl.where(use1,x1,tl.where(use2,x2,x3));ny=tl.where(use1,y1,tl.where(use2,y2,y3));nz=tl.where(use1,z1,tl.where(use2,z2,z3)) length=libdevice.sqrt(nx*nx+ny*ny+nz*nz) safe_length=tl.where(length>0,length,1.) nx=nx/safe_length;ny=ny/safe_length;nz=nz/safe_length rx=a*nx+e*ny+f*nz-smallest*nx ry=e*nx+b*ny+g*nz-smallest*ny rz=f*nx+g*ny+d*nz-smallest*nz residual=libdevice.sqrt(rx*rx+ry*ry+rz*rz) threshold=tl.maximum(1e-16,largest*scale*1e-8) rank=(middle*scale>threshold)&((middle-smallest)*scale>threshold) delicate=(middle*scale<=100*threshold)|((middle-smallest)*scale<=100*threshold) fallback=(count>=6)&((length<1e-10)|(residual>1e-10)|delicate|(residual!=residual)) good=(count>=6)&rank&~fallback flip=nx*cx+ny*cy+nz*cz>0 sign=tl.where(flip,-1.,1.) tl.store(NORMALS+(cv*W+cu)*3,nx*sign,good) tl.store(NORMALS+(cv*W+cu)*3+1,ny*sign,good) tl.store(NORMALS+(cv*W+cu)*3+2,nz*sign,good) tl.store(VALID+cv*W+cu,good) tl.store(FALLBACK+pid,fallback)
def fused_normals(xyz,support,parameters): h,w=support.shape normals=torch.full_like(xyz,float('nan'));valid=torch.zeros_like(support) # torch.nonzero commonly returns column-major strides (1,N); the kernel # explicitly consumes adjacent (v,u) pairs. centres=support.nonzero().contiguous() if not len(centres):return normals,valid covariance=torch.empty((len(centres),3,3),dtype=torch.float64,device=xyz.device) fallback=torch.empty((len(centres),),dtype=torch.bool,device=xyz.device) _pca5[(len(centres),)](xyz,support,centres,normals,valid,covariance,fallback,h,w, parameters.depth_jump_abs_m,parameters.depth_jump_rel,num_warps=1,enable_fp_fusion=False) idx=fallback.nonzero().flatten() if len(idx): values,basis=torch.linalg.eigh(covariance[idx]) threshold=torch.maximum(torch.full_like(values[:,2],1e-16),values[:,2]*1e-8) good=(values[:,1]>threshold)&(values[:,1]-values[:,0]>threshold)&torch.isfinite(values).all(1) vu=centres[idx[good]];vectors=basis[good,:,0] vectors/=torch.linalg.vector_norm(vectors,dim=1)[:,None] flip=(vectors*xyz[vu[:,0],vu[:,1]]).sum(1)>0 vectors=torch.where(flip[:,None],-vectors,vectors) normals[vu[:,0],vu[:,1]]=vectors.to(torch.float32);valid[vu[:,0],vu[:,1]]=True return normals,valid
@triton.jitdef _features(XYZ,VD,MASK,SUPPORT,NORMALS,NV,JM,PV,DISC,MB,VB,IB,VAR,VV,COUNT, H:tl.constexpr,W:tl.constexpr,ABS:tl.constexpr,REL:tl.constexpr,B:tl.constexpr): i=tl.program_id(0)*B+tl.arange(0,B);inside=i<H*W v=i//W;u=i%W vd=tl.load(VD+i,inside,other=0);mask=tl.load(MASK+i,inside,other=0) support=tl.load(SUPPORT+i,inside,other=0);nv=tl.load(NV+i,inside,other=0) z=tl.where(vd,tl.load(XYZ+i*3+2,inside,other=0),0.) nx=tl.where(nv,tl.load(NORMALS+i*3,inside,other=0),0.) ny=tl.where(nv,tl.load(NORMALS+i*3+1,inside,other=0),0.) nz=tl.where(nv,tl.load(NORMALS+i*3+2,inside,other=0),0.) jump_m=tl.full((B,),0.,tl.float32);variation=tl.full((B,),0.,tl.float32) pair_valid=tl.full((B,),False,tl.int1);disc=pair_valid;mb=pair_valid;vb=pair_valid count=tl.full((B,),0,tl.int32) for direction in tl.static_range(4): offset=tl.where(direction==0,-1,tl.where(direction==1,1,tl.where(direction==2,-W,W))) available=inside&tl.where(direction==0,u>0,tl.where(direction==1,u+1<W,tl.where(direction==2,v>0,v+1<H))) q=i+offset qvd=tl.load(VD+q,available,other=0);qm=tl.load(MASK+q,available,other=0) qnv=tl.load(NV+q,available,other=0) qz=tl.where(qvd,tl.load(XYZ+q*3+2,available,other=0),0.) dz=tl.abs(z-qz);both_depth=available&vd&qvd pv=support&both_depth pair_valid=pair_valid|pv jump_m=tl.maximum(jump_m,tl.where(pv,dz,0.)) threshold=tl.full((),ABS,tl.float32)+tl.full((),REL,tl.float32)*tl.minimum(z,qz) disc=disc|(support&both_depth&(dz>threshold)) mb=mb|(available&mask&~qm);vb=vb|(available&support&~qvd) qx=tl.where(qnv,tl.load(NORMALS+q*3,available,other=0),0.) qy=tl.where(qnv,tl.load(NORMALS+q*3+1,available,other=0),0.) qnz=tl.where(qnv,tl.load(NORMALS+q*3+2,available,other=0),0.) cx=ny*qnz-nz*qy;cy=nz*qx-nx*qnz;cz=nx*qy-ny*qx length=libdevice.sqrt(cx*cx+cy*cy+cz*cz) dot=nx*qx+ny*qy+nz*qnz both=available&nv&qnv angle=tl.where(both,libdevice.atan2(length,dot),0.) variation=tl.maximum(variation,angle);count=count+both.to(tl.int32) vv=nv&(count>0) image_boundary=mask&((v==0)|(v==H-1)|(u==0)|(u==W-1)) tl.store(JM+i,tl.where(pair_valid,jump_m,float('nan')),inside) tl.store(PV+i,pair_valid,inside);tl.store(DISC+i,disc,inside) tl.store(MB+i,mb,inside);tl.store(VB+i,vb,inside);tl.store(IB+i,image_boundary,inside) tl.store(VAR+i,tl.where(vv,variation,float('nan')),inside);tl.store(VV+i,vv,inside);tl.store(COUNT+i,count,inside)
def fused_features(xyz,valid_depth,mask,support,normals,normal_valid,parameters): shape=mask.shape result=dict(object_mask=mask,valid_points=support,normals=normals,normal_valid=normal_valid) names=['depth_jump_m','depth_pair_valid','depth_discontinuity','mask_boundary','depth_validity_boundary', 'image_boundary','normal_variation_rad','normal_variation_valid','normal_neighbor_count'] for name in names: dtype=torch.float32 if name in ('depth_jump_m','normal_variation_rad') else torch.uint8 if name=='normal_neighbor_count' else torch.bool result[name]=torch.empty(shape,dtype=dtype,device=xyz.device) _features[(triton.cdiv(mask.numel(),256),)](xyz,valid_depth,mask,support,normals,normal_valid, *[result[name] for name in names],*shape,parameters.depth_jump_abs_m,parameters.depth_jump_rel,256, num_warps=4,enable_fp_fusion=False) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""Phase3 contracts. All FPS calls here use synthetic points, never Task03 data."""import copyfrom types import SimpleNamespaceimport unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.rgbd import PEG, BOXfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_priority_fps_seed_control as controlfrom visual.runtime.test.sampling_evaluation import CoverageMatcher
class Archive(dict): @property def files(self): return list(self)
def synthetic_candidates(): # Common source pixels always point at exactly the same source XYZ. def method(flat): xyz = np.column_stack((np.sin(flat*.3), np.cos(flat*.2), flat*.01)).astype(np.float32) return dict(flat=flat, points=xyz) return dict(S2=method(np.arange(100, 148)), S3=method(np.arange(108, 156)))
def saved_fixture(): """Synthetic 256-row archives with the real shape/quota/field contracts.""" shape = (512, 512) flat = np.arange(np.prod(shape)) xyz = np.column_stack((flat*.001, flat*.002, np.ones(len(flat)))).astype(np.float32).reshape(*shape, 3) geometry = SimpleNamespace(xyz=xyz, observed_mask=lambda oid: (flat < 90000 if oid == PEG else flat >= 90000).reshape(shape)) frame = SimpleNamespace(source_frame=0, depth=np.ones(shape, np.float32)) archive = Archive(source_frame=np.array(0), shape=np.array(shape)) config, metrics, phase2 = dict(conditions={}), {}, dict(methods={}) field_names = ['object_mask', 'valid_points', 'normals', 'normal_valid', 'depth_jump_m', 'depth_pair_valid', 'depth_discontinuity', 'mask_boundary', 'depth_validity_boundary', 'image_boundary', 'normal_variation_rad', 'normal_variation_valid', 'normal_neighbor_count', 'orientation_evidence', 'depth_evidence', 'occluding_evidence', 'occluded_evidence', 'invalid_evidence', 'mask_evidence', 'orientation_score_deg', 'orientation_candidate', 'depth_only_candidate', 'structural_candidate'] for method, (estimator, _, count, _, _) in control.METHODS.items(): candidates = np.sort(np.r_[np.arange(90000, 90000+count-3), control.FIRST[method]]) archive[f'evidence/{estimator}/1/20/orientation_flat'] = candidates phase2['methods'][method] = dict(candidate_flat_indices=candidates.tolist()) for seed in (0, 1, 2): key = f'{method}_n256_r0.25_t20_s{seed}' config['conditions'][key] = dict(method=method, num_points=256, structural_ratio=.25, orientation_threshold_deg=20, seed=seed) first = control.FIRST[method][seed] selected = np.r_[np.arange(129), first, candidates[candidates != first][:126]] box = np.arange(256) >= 129 archive[key+'/flat_index'] = selected archive[key+'/points'] = xyz.reshape(-1, 3)[selected] archive[key+'/pixels_vu'] = np.column_stack(np.unravel_index(selected, shape)) archive[key+'/object_id'] = box.astype(np.int64) archive[key+'/priority_selected'] = np.r_[np.arange(129) < 32, np.arange(127) < 32] archive[key+'/depth_priority_selected'] = np.zeros(256, bool) for name in field_names: value = np.zeros((256, 3), np.float32) if name == 'normals' else np.zeros(256, bool) if name in ('object_mask', 'valid_points'): value[:] = True if name in ('orientation_candidate', 'structural_candidate'): value[box] = True archive[key+'/metadata/'+name] = value objects = {} for name, budget in [('peg', 129), ('box', 127)]: objects[name] = dict(counts=dict(budget=budget, selected=budget, priority=32, orientation_priority=32, depth_priority=0, surface_fps=budget-32)) n = control.FINAL[method][seed] objects['box']['structural'] = dict(tolerance={'2px_3mm': dict(gt_visible=103, sampled=n, gt_coverage=n/103)}) metrics[key] = dict(objects=objects) return archive, config, metrics, frame, geometry, phase2
class SharedInitialTests(unittest.TestCase): def select(self, candidates=None): return control.select_control(synthetic_candidates() if candidates is None else candidates, expected_shared=40, expected_initial=128)
def test_initial_included_total_32_exact_local_global_no_rng(self): candidates = synthetic_candidates() before = copy.deepcopy(candidates) with patch.object(control, 'fps_indices', wraps=fps_indices) as calls: orders, info = self.select(candidates) self.assertEqual(calls.call_count, 2) self.assertEqual(info['candidate_local_index'], {'S2': 28, 'S3': 20}) self.assertEqual(info['initial_rng_draws'], 0) for method, row in orders.items(): self.assertEqual(len(row['flat']), 32) self.assertEqual(len(set(row['flat'])), 32) self.assertEqual(row['flat'][0], 128) np.testing.assert_array_equal(candidates[method]['flat'][row['local']], row['flat']) np.testing.assert_array_equal(candidates[method]['points'][row['local']], row['xyz']) for field in ('flat', 'points'): np.testing.assert_array_equal(candidates[method][field], before[method][field]) np.testing.assert_array_equal(orders['S2']['xyz'][0], orders['S3']['xyz'][0])
def test_initial_path_never_constructs_rng_even_when_seed_changes(self): points = synthetic_candidates()['S2']['points'] with patch('visual.runtime.sampling.np.random.default_rng', side_effect=AssertionError('RNG draw')): a = fps_indices(points, 32, seed=0, initial=[28]) b = fps_indices(points, 32, seed=98765, initial=[28]) np.testing.assert_array_equal(a, b) self.assertEqual(a[0], 28)
def test_intersection_and_initial_mismatch_stop_before_fps(self): for kwargs in (dict(expected_shared=39, expected_initial=128), dict(expected_shared=40, expected_initial=127)): with patch.object(control, 'fps_indices', side_effect=AssertionError('must stop before FPS')): with self.assertRaises(ValueError): control.select_control(synthetic_candidates(), **kwargs)
def test_order_xyz_and_short_count_mismatch_stop_before_fps(self): for mutation in ('order', 'xyz', 'count'): c = synthetic_candidates() if mutation == 'order': c['S2']['flat'] = c['S2']['flat'][::-1] elif mutation == 'xyz': c['S3']['points'][20, 0] += .001 else: c['S2'] = {k: v[:31] for k, v in c['S2'].items()} with patch.object(control, 'fps_indices', side_effect=RuntimeError('must stop before FPS')): with self.assertRaises((ValueError, AssertionError)): self.select(c)
def test_invalid_fps_order_is_rejected(self): for order in (np.zeros(32, np.int64), np.arange(31), np.r_[28, np.arange(30), 999]): with patch.object(control, 'fps_indices', return_value=order): with self.assertRaises(ValueError): self.select() with patch.object(control, 'fps_indices', return_value=np.arange(32)): with self.assertRaisesRegex(ValueError, 'initial included'): self.select()
def test_gt_annotation_change_cannot_change_control_selection(self): candidates = synthetic_candidates() orders_a, _ = self.select(candidates) xyz = np.zeros((1, 200, 3), np.float32) geometry = SimpleNamespace(valid_depth=np.ones((1, 200), bool), xyz=xyz, observed_mask=lambda oid: np.ones((1, 200), bool)) frame = SimpleNamespace(depth=np.ones((1, 200), np.float32)) annotations = [((np.array([[128., 0.]]), np.zeros((1, 3))), np.zeros((1, 200), bool)), ((np.array([[999., 999.]]), np.ones((1, 3))*100), np.ones((1, 200), bool))] scores = [] for refs, negative in annotations: matcher = CoverageMatcher(geometry, BOX, refs) scores.append(control.score_control(orders_a, matcher, frame, {'negative': negative})) orders_b, _ = self.select(candidates) # synthetic repeat only for method in control.METHODS: np.testing.assert_array_equal(orders_a[method]['flat'], orders_b[method]['flat']) self.assertNotEqual(scores[0][method]['negative_roi'], scores[1][method]['negative_roi']) with self.assertRaises(TypeError): control.select_control(candidates, gt={})
class SavedAnalysisTests(unittest.TestCase): def test_source_feature_role_alignment_without_fps(self): fixture = saved_fixture() with control.forbid_sampling(): candidates, selected, checks = control.load_saved(*fixture) self.assertEqual(len(checks), 6) for method in control.METHODS: self.assertEqual(len(candidates[method]['flat']), control.METHODS[method][2]) for seed in (0, 1, 2): self.assertEqual(selected[method][seed]['flat'][0], control.FIRST[method][seed]) self.assertTrue(all(c['feature_and_role_alignment'] for c in checks.values()))
def test_corrupt_source_feature_role_or_order_fails(self): key = 'S2_n256_r0.25_t20_s1' for field in ('points', 'metadata/normals', 'metadata/orientation_candidate', 'priority_selected', 'pixels_vu'): fixture = saved_fixture() array = fixture[0][key+'/'+field] fixture[0][key+'/'+field] = array.copy() array = fixture[0][key+'/'+field] if field == 'metadata/normals': array[0, 0] = 1 # same source pixel, inconsistent saved feature elif field == 'priority_selected': array[129] = False elif field == 'metadata/orientation_candidate': array[129] = False else: array[0, 0] += 1 with control.forbid_sampling(), self.assertRaises((ValueError, AssertionError)): control.load_saved(*fixture)
def test_seed0_reused_and_only_seed1_2_matched_without_fps(self): flat = np.arange(32, dtype=np.int64) xyz = np.zeros((32, 3), np.float32) frame = SimpleNamespace(depth=np.ones((1, 32), np.float32)) negatives = dict(negative=np.zeros((1, 32), bool)) rows = {m: {s: dict(flat=flat, xyz=xyz, final=dict(sampled=10, gt_coverage=10/103)) for s in (0, 1, 2)} for m in control.METHODS} trace = [dict(xyz_m=p.tolist(), flat_index=int(f), depth_m=1., rim_reference_matched=i == 1, matched_rim_reference_ids=[2, 3] if i == 1 else [], selected_negative_roi=dict(negative=False, known_negative_union=False)) for i, (p, f) in enumerate(zip(xyz, flat))] phase2 = dict(methods={m: dict(stored_priority_flat_indices=flat.tolist(), trace=trace, priority_reference_ids=[2, 3], priority_reference_count=2) for m in control.METHODS}) phase1 = dict(frames=[dict(conditions={m: dict(reference_ids=dict(P=[2, 3])) for m in control.METHODS})]) calls = [] def match(selected, **kwargs): calls.append(selected.copy()) self.assertEqual(kwargs, dict(px=2., m=.003)) return np.array([2, 3]), selected[1:2] with control.forbid_sampling(): result = control.summarize_saved(rows, phase1, phase2, SimpleNamespace(reference_hits=match), frame, negatives) self.assertEqual(len(calls), 4) for method in control.METHODS: self.assertEqual(result[method]['0']['priority_reference_ids'], [2, 3]) self.assertEqual(result[method]['0']['rim_matching_node_count'], 1) self.assertEqual(result[method]['0']['final_sampling']['numerator'], 10) phase2['methods']['S2']['priority_reference_ids'] = [2, 4] with control.forbid_sampling(), self.assertRaisesRegex(ValueError, 'Phase1/2 IDs'): control.summarize_saved(rows, phase1, phase2, SimpleNamespace(reference_hits=match), frame, negatives)
def test_joint_same_pair_and_reference_dedup(self): shape = (1, 10) xyz = np.zeros((*shape, 3), np.float32) xyz[0, 3] = [.1, 0, 0] geometry = SimpleNamespace(valid_depth=np.ones(shape, bool), xyz=xyz, observed_mask=lambda oid: np.ones(shape, bool)) # Selected nodes: 0 is near ref 0 only in 2D, 3 only in XYZ. refs = (np.array([[0., 0.], [7., 0.]]), np.array([[.1, 0, 0], [0, 0, 0]])) matcher = CoverageMatcher(geometry, BOX, refs) ids, hits = matcher.reference_hits(np.array([0, 3], np.int64)) self.assertEqual(ids.tolist(), []) self.assertEqual(hits.tolist(), []) ids, hits = matcher.reference_hits(np.array([6, 7, 8], np.int64)) self.assertEqual(ids.tolist(), [1]) self.assertEqual(len(hits), 3) frame = SimpleNamespace(depth=np.ones(shape, np.float32)) a = np.zeros(shape, bool); b = a.copy(); a[0, [6, 7]] = True; b[0, [7, 8]] = True summary = control.point_summary(np.array([6, 7, 8]), frame, dict(a=a, b=b), ids, hits, xyz[0, [6, 7, 8]]) self.assertEqual(summary['negative_roi']['known_negative_union']['count'], 3) self.assertEqual(summary['priority_reference_count'], 1) with self.assertRaisesRegex(ValueError, 'deduplicated'): control.point_summary(np.array([6, 7, 8]), frame, dict(a=a), [1, 1], hits, xyz[0, [6, 7, 8]])
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Device-resident Torch PCA5 comparison, independent of the NumPy adapter.
Depth and tracker masks stay on the selected device. Float64 PCA preserves thereference policy; CUDA measurements require an actual CUDA host. CPU Torch isused for executable numerical contract tests, not claimed as a fast backend."""from __future__ import annotations
import numpy as npimport torch
from visual.runtime.geometry import GeometryParametersfrom visual.runtime.rgbd import PEG, BOX
class TorchPCA5: def __init__(self, intrinsic, shape, *, device='cuda', parameters=GeometryParameters(), backend='eigh'): k = np.asarray(intrinsic, float) if (k.shape != (3, 3) or not np.isfinite(k).all() or min(k[0, 0], k[1, 1]) <= 0 or not np.allclose(k[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1])): raise ValueError('invalid zero-skew intrinsic') self.device = torch.device(device) if self.device.type == 'cuda' and self.device.index is None: self.device = torch.device('cuda', torch.cuda.current_device()) if self.device.type == 'mps': raise ValueError('MPS cannot preserve the float64 PCA contract; use CPU or CUDA') self.shape, self.parameters = tuple(shape), parameters if backend not in ('eigh', 'triton', 'triton_fused'): raise ValueError('unknown Torch PCA backend') if backend.startswith('triton') and self.device.type!='cuda': raise ValueError('Triton backend requires CUDA') self.backend=backend h, w = self.shape if h < 1 or w < 1: raise ValueError('shape must be positive') self.ux = (torch.arange(w, dtype=torch.float64, device=self.device)+.5-k[0, 2])[None] self.vy = (torch.arange(h, dtype=torch.float64, device=self.device)+.5-k[1, 2])[:, None] self.fx, self.fy = float(k[0, 0]), float(k[1, 1]) dv, du = torch.meshgrid(torch.arange(-2, 3, device=self.device), torch.arange(-2, 3, device=self.device), indexing='ij') self.dv, self.du = dv, du self.bits = (torch.ones(25, dtype=torch.int64, device=self.device) << torch.arange(25, device=self.device)).reshape(5, 5)
def _jump(self, a, b): return (a-b).abs() > self.parameters.depth_jump_abs_m+self.parameters.depth_jump_rel*torch.minimum(a, b)
def _normals(self, xyz, support): if self.backend.startswith('triton'): from visual.runtime.test.pca_triton import fused_normals return fused_normals(xyz,support,self.parameters) h, w = self.shape normals = torch.full_like(xyz, float('nan')) valid = torch.zeros_like(support) centres = support.nonzero() if not len(centres): return normals, valid v = centres[:, 0, None, None]+self.dv u = centres[:, 1, None, None]+self.du inside = (v >= 0) & (v < h) & (u >= 0) & (u < w) v, u = v.clamp(0, h-1), u.clamp(0, w-1) available = inside & support[v, u] points = xyz[v, u].to(torch.float64) z = torch.where(available, points[..., 2], 0) right_links = available[:, :, :-1] & available[:, :, 1:] & ~self._jump(z[:, :, :-1], z[:, :, 1:]) down_links = available[:, :-1] & available[:, 1:] & ~self._jump(z[:, :-1], z[:, 1:]) right = (right_links*self.bits[:, :-1]).sum((1, 2)) down = (down_links*self.bits[:-1]).sum((1, 2)) reached = torch.full((len(centres),), 1 << 12, dtype=torch.int64, device=self.device) # A simple path in a 25-vertex patch has <=24 edges. Fixed iterations # avoid a host .item()/synchronization at every flood-fill iteration. for _ in range(24): reached = reached | ((reached & right) << 1) | ((reached >> 1) & right) | ((reached & down) << 5) | ((reached >> 5) & down) component = (reached[:, None, None] & self.bits) != 0 count = component.sum((1, 2)) idx = (count >= 6).nonzero().flatten() centres, points, component, count = centres[idx], points[idx], component[idx], count[idx] delta = torch.where(component[..., None], points-xyz[centres[:, 0], centres[:, 1]][:, None, None], 0) mean = delta.sum((1, 2))/count[:, None] flat = delta.flatten(1, 2) covariance = flat.transpose(1, 2).bmm(flat)/count[:, None, None]-mean[:, :, None]*mean[:, None, :] values, basis = torch.linalg.eigh(covariance) threshold = torch.maximum(torch.full_like(values[:, 2], 1e-16), values[:, 2]*1e-8) good = (values[:, 1] > threshold) & (values[:, 1]-values[:, 0] > threshold) & torch.isfinite(values).all(1) centres, vectors = centres[good], basis[good, :, 0] vectors = vectors/torch.linalg.vector_norm(vectors, dim=1)[:, None] camera_dot = (vectors*xyz[centres[:, 0], centres[:, 1]]).sum(1) vectors = torch.where((camera_dot > 0)[:, None], -vectors, vectors) normals[centres[:, 0], centres[:, 1]] = vectors.to(torch.float32) valid[centres[:, 0], centres[:, 1]] = True return normals, valid
def _features(self, xyz, valid_depth, mask, support, normals, normal_valid): shape, dev = self.shape, self.device z = torch.where(valid_depth, xyz[..., 2], 0) jump_m = torch.zeros(shape, dtype=torch.float32, device=dev) pair_valid = torch.zeros_like(support); discontinuity = torch.zeros_like(support) mask_boundary = torch.zeros_like(support); validity_boundary = torch.zeros_like(support) variation = torch.zeros_like(jump_m) count = torch.zeros(shape, dtype=torch.uint8, device=dev) safe_normals = torch.nan_to_num(normals) pairs = [((slice(None), slice(None, -1)), (slice(None), slice(1, None))), ((slice(None, -1), slice(None)), (slice(1, None), slice(None)))] for a, b in pairs: both_depth = valid_depth[a] & valid_depth[b] dz = (z[a]-z[b]).abs() jumps = both_depth & self._jump(z[a], z[b]) both_normals = normal_valid[a] & normal_valid[b] n1, n2 = safe_normals[a], safe_normals[b] angle = torch.atan2(torch.linalg.vector_norm(torch.linalg.cross(n1, n2), dim=-1), (n1*n2).sum(-1)) angle = torch.where(both_normals, angle, 0) for p, q in ((a, b), (b, a)): available = support[p] & both_depth pair_valid[p] |= available jump_m[p] = torch.maximum(jump_m[p], torch.where(available, dz, 0)) discontinuity[p] |= support[p] & jumps mask_boundary[p] |= mask[p] & ~mask[q] validity_boundary[p] |= support[p] & ~valid_depth[q] variation[p] = torch.maximum(variation[p], angle) count[p] += both_normals.to(torch.uint8) variation_valid = normal_valid & (count > 0) image_boundary = torch.zeros_like(support) image_boundary[[0, -1], :] = mask[[0, -1], :] image_boundary[:, [0, -1]] = mask[:, [0, -1]] return dict(object_mask=mask, valid_points=support, normals=normals, normal_valid=normal_valid, depth_jump_m=torch.where(pair_valid, jump_m, float('nan')), depth_pair_valid=pair_valid, depth_discontinuity=discontinuity, mask_boundary=mask_boundary, depth_validity_boundary=validity_boundary, image_boundary=image_boundary, normal_variation_rad=torch.where(variation_valid, variation, float('nan')), normal_variation_valid=variation_valid, normal_neighbor_count=count)
@torch.inference_mode() def __call__(self, depth_m, masks): if depth_m.shape != self.shape or depth_m.device != self.device or not depth_m.is_floating_point(): raise ValueError('depth must be floating (H,W) on the configured device') if set(masks)-{PEG, BOX}: raise ValueError('unknown object ID') masks = {i: masks.get(i, torch.zeros(self.shape, dtype=torch.bool, device=self.device)) for i in (PEG, BOX)} if any(m.dtype != torch.bool or m.shape != self.shape or m.device != self.device for m in masks.values()): raise ValueError('masks must be bool (H,W) on the configured device') depth_m=depth_m.contiguous() masks={i:m.contiguous() for i,m in masks.items()} valid_depth = torch.isfinite(depth_m) & (depth_m > 0) z = torch.where(valid_depth, depth_m, 0).to(torch.float64) xyz = torch.stack((self.ux*z/self.fx, self.vy*z/self.fy, z), dim=-1).to(torch.float32) xyz = torch.where(valid_depth[..., None], xyz, float('nan')) overlap = masks[PEG] & masks[BOX] objects = {} for oid, mask in masks.items(): support = mask & valid_depth & ~overlap normals, normal_valid = self._normals(xyz, support) if self.backend=='triton_fused': from visual.runtime.test.pca_triton import fused_features objects[oid]=fused_features(xyz,valid_depth,mask,support,normals,normal_valid,self.parameters) else: objects[oid] = self._features(xyz, valid_depth, mask, support, normals, normal_valid) return dict(xyz=xyz, valid_depth=valid_depth, overlap_mask=overlap, objects=objects)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993"""Task03-G: one offline Frame0 feasibility rule, never a production sampler.
WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_geometry_aware_sampling --original-state DIRNo normal/candidate extraction, baseline FPS replay, sweep or synthetic performance run."""from __future__ import annotations
import argparsefrom dataclasses import fieldsimport htmlfrom html.parser import HTMLParserimport jsonimport osfrom pathlib import Pathimport platformimport reimport shutilimport subprocessimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport numpy as npfrom scipy.sparse import coo_matrixfrom scipy.sparse.csgraph import connected_components
from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digests, register_existing_outputfrom visual.runtime.edge_evidence import PairEvidencefrom visual.runtime.geometry import GeometryParametersfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_local_structural_sampling as previousfrom visual.runtime.test import run_priority_fps_metric_control as priorfrom visual.runtime.test.run_rim_bottleneck import require_equal, write_json, validate_saved_selection
REPO = prior.REPOSTEM = 'geometry_aware_sampling'REPORT = REPO/'docs/visual-graph-integration/03g_geometry_aware_sampling.md'UV_RUN = '1f7ad262dd2e4b2fb0ac805a4eda5278'UV_DIR = REPO/'experiments'/UV_RUNTESTS = ['visual.runtime.test.'+s for s in ( 'test_geometry_aware_sampling', 'test_local_structural_sampling', 'test_priority_fps_metric_control', 'test_sampling', 'test_sampling_geometry', 'test_sampling_evaluation', 'test_priority_fps_trace', 'test_priority_fps_seed_control')]RULES = dict(threshold_deg=20., priority=32, total=256, structural_ratio=.25, patch='X components: same-object support at both ends, no overlap, no depth jump, finite angle <=20 deg', ordering='patch minimum flat ascending; candidate rows flat ascending', weight='Euclidean diagonal of candidate XYZ axis-aligned bbox; zero for empty/singleton/coincident', quota='reserve whole-C seeded anchor; remaining 31 capacity-capped largest remainder; ties patch order', saturation='floor capped by residual capacity, then fractional remainder once per eligible patch; repeat', zero_weight='no minimum quota, no merge, no relaxed gate; leftover goes to global fallback', priority_metric='original XYZ 3D Euclidean within patches; same object seed for each patch', anchor='anchor patch first, initial anchor; remaining patches minimum flat ascending', fallback='current C global lambda=0 FPS order (camera Z zeroed), skip already selected; optional verified saved prefix', surface='original whole X 3D FPS initialized with all P', gt='evaluation only after selection_before_gt.npz; same-pair 2px AND 3mm', comparison='grouping, span allocation, per-patch initialization and distance metric change together', synthetic='seven existing performance fixtures N/A: dense X and PairEvidence absent', adoption='Frame0 feasibility only; no policy adoption or generalization claim')
def ordered_source(flat, shape): previous.uv_from_flat(flat, shape) if len(flat) and not np.all(flat[:-1] < flat[1:]): raise ValueError('source rows must be ascending')
def patch_labels(support_flat, pair): """Temporary observation components only; retain isolated and C-free X rows.""" support_flat = np.asarray(support_flat) ordered_source(support_flat, pair.shape) pixels = np.asarray(pair.pixels) if pixels.ndim != 2 or pixels.shape[1] != 2: raise ValueError('pair pixels require [N,2]') if ((pixels < 0) | (pixels >= np.prod(pair.shape))).any(): raise ValueError('pair outside raster') delta = pixels[:, 1]-pixels[:, 0] right = (delta == 1) & (pixels[:, 0]//pair.shape[1] == pixels[:, 1]//pair.shape[1]) down = delta == pair.shape[1] if not (right | down).all() or len(np.unique(pixels, axis=0)) != len(pixels): raise ValueError('unique right/down pair contract required') expected = np.isin(pixels, support_flat) np.testing.assert_array_equal(pair.supported, expected) gate = (pair.supported.all(1) & ~pair.overlap.any(1) & ~pair.depth_jump & np.isfinite(pair.normal_angle_deg) & (pair.normal_angle_deg <= RULES['threshold_deg'])) rows = np.searchsorted(support_flat, pixels[gate]) graph = coo_matrix((np.ones(len(rows), bool), (rows[:, 0], rows[:, 1])), shape=(len(support_flat), len(support_flat))).tocsr() count, labels = connected_components(graph, directed=False) # scipy normally discovers in row order; explicitly impose minimum source order. minima = np.full(count, np.iinfo(np.int64).max, np.int64) np.minimum.at(minima, labels, support_flat) order = np.argsort(minima, kind='stable') relabel = np.empty(count, np.int64); relabel[order] = np.arange(count) return relabel[labels], gate
def allocate_span(capacity, weights, count): """No zero-span minimum. Returns quota plus unallocated fallback slots.""" cap, w = np.asarray(capacity), np.asarray(weights, float) if cap.ndim != 1 or cap.dtype.kind not in 'iu' or w.shape != cap.shape: raise ValueError('integer capacities and aligned weights required') if (cap < 0).any() or not np.isfinite(w).all() or (w < 0).any() or count < 0: raise ValueError('nonnegative finite allocation inputs required') out = np.zeros(len(cap), np.int64); left = int(count) while left: active = (out < cap) & (w > 0) if not active.any(): break scaled = np.where(active, w/w[active].max(), 0.) real = left*scaled/scaled.sum() take = np.minimum(cap-out, np.floor(real).astype(np.int64)) out += take; left -= int(take.sum()) for g in np.argsort(-(real-np.floor(real)), kind='stable'): if left and active[g] and out[g] < cap[g]: out[g] += 1; left -= 1 return out, left
def prepare(case, pair): """Freeze fragmentation, bbox extrema, weight, capacity and quota before FPS.""" c, x = case['candidate_flat'], case['support_flat'] ordered_source(c, pair.shape); ordered_source(x, pair.shape) cr = np.searchsorted(x, c) if (cr >= len(x)).any() or not np.array_equal(x[cr], c): raise ValueError('C outside X') np.testing.assert_array_equal(case['support_xyz'][cr], case['candidate_xyz']) if not np.isfinite(case['support_xyz']).all(): raise ValueError('finite XYZ required') labels, gate = patch_labels(x, pair) cm = labels[cr]; ng = int(labels.max())+1 if len(labels) else 0 cap = np.bincount(cm, minlength=ng); xn = np.bincount(labels, minlength=ng) spans = np.zeros(ng); rows = [] for g in range(ng): xr, rr = np.flatnonzero(labels == g), np.flatnonzero(cm == g) xx, cc = case['support_xyz'][xr], case['candidate_xyz'][rr] bbox = lambda a: dict(min_xyz_m=a.min(0).tolist(), max_xyz_m=a.max(0).tolist(), span_m=float(np.linalg.norm(a.max(0)-a.min(0)))) if len(a) else None cb = bbox(cc); spans[g] = cb['span_m'] if cb else 0. extreme = np.unique(np.r_[cc.argmin(0), cc.argmax(0)]) if len(cc) else np.empty(0, int) # Sensitivity diagnostic only: never changes weights or selection. loo = [] for i in extreme: remaining = np.delete(cc, i, axis=0) span = float(np.linalg.norm(remaining.max(0)-remaining.min(0))) if len(remaining) else 0. loo.append(dict(source=int(c[rr[i]]), span_without_point_m=span, span_reduction_m=float(spans[g]-span))) rows.append(dict(patch=g, min_flat=int(x[xr[0]]), X=int(xn[g]), C=int(cap[g]), X_bbox=bbox(xx), C_bbox=cb, extrema_leave_one_out=loo)) target = min(RULES['priority'], len(c)) quota = np.zeros(ng, np.int64); ag = None if target: ar = np.flatnonzero(c == case['first']) if len(ar) != 1: raise ValueError('anchor must be in C exactly once') require_equal(int(c[np.random.default_rng(case['seed']).integers(len(c))]), int(case['first']), 'whole-C anchor') ag = int(cm[ar[0]]); quota[ag] = 1 additional, left = allocate_span(cap-quota, spans, target-int(quota.sum())) quota += additional for g, row in enumerate(rows): row.update(weight=float(spans[g]), capacity=int(cap[g]), residual_capacity_after_anchor=int(cap[g]-(g == ag)), anchor_reserved=int(g == ag), additional_allocation=int(additional[g]), quota=int(quota[g])) zero = (cap > 0) & (spans == 0) singleton = xn == 1 return dict(support_patch=labels, candidate_patch=cm, connection_gate=gate, patches=rows, weight=spans, capacity=cap, quota=quota, anchor_patch=ag, fallback_slots=left, diagnostics=dict(X_patches=ng, candidate_patches=int((cap > 0).sum()), X_singleton_patches=int(singleton.sum()), X_singleton_candidates=int(cap[singleton].sum()), candidate_singleton_patches=int((cap == 1).sum()), zero_span_candidate_patches=int(zero.sum()), zero_span_candidates=int(cap[zero].sum()), zero_span_candidate_fraction=float(cap[zero].sum()/len(c)) if len(c) else None, singleton_or_zero_span_patches=int((singleton | zero).sum()), singleton_or_zero_span_candidates=int(cap[singleton | zero].sum()), singleton_or_zero_span_candidate_fraction=float(cap[singleton | zero].sum()/len(c)) if len(c) else None, zero_quota_candidate_patches=int(((cap > 0) & (quota == 0)).sum()), zero_quota_candidates=int(cap[quota == 0].sum()), anchor_patch=ag, anchor_quota=int(quota[ag]) if ag is not None else 0, planned_fallback=left, quota_sum=int(quota.sum())))
def fallback_rows(flat, xyz, seed, anchor, selected, needed, saved_order=None): """Generic current-C global lambda=0 FPS fallback, with optional cached prefix.
A verified prefix is sufficient when it has `needed` unselected rows. Otherwise generate current-C order up to selected+needed; no Task03 artifact is required. """ if not needed: return np.empty(0, np.int64), 'unused' flat = np.asarray(flat); selected = np.asarray(selected, np.int64) if saved_order is not None: order = np.asarray(saved_order) if len(np.unique(order)) != len(order) or not np.isin(order, flat).all() or order[0] != anchor: raise ValueError('invalid verified cached fallback prefix') available = order[~np.isin(order, flat[selected])] if len(available) >= needed: return np.searchsorted(flat, available[:needed]), 'verified_saved_global_prefix' ar = np.flatnonzero(flat == anchor) metric = prior.metric_coordinates(xyz, 0.) order = fps_indices(metric, min(len(flat), len(selected)+needed), seed=seed, initial=ar) available = order[~np.isin(order, selected)] if len(available) < needed: raise ValueError('fallback capacity exhausted') return available[:needed], 'generated_current_C_global_order'
def select_geometry(case, prepared, saved_order=None): """Annotation-free selection. No object names, poses, ROI, scores or references.""" c, xyz = case['candidate_flat'], case['candidate_xyz'] cm, q = prepared['candidate_patch'], prepared['quota'] ag = prepared['anchor_patch'] order = ([ag] if ag is not None else [])+[g for g in range(len(q)) if g != ag and q[g]] selected = []; initial_source = np.full(len(q), -1, np.int64) for g in order: rows = np.flatnonzero(cm == g) initial = np.flatnonzero(c[rows] == case['first']) if g == ag else () local = fps_indices(xyz[rows], int(q[g]), seed=case['seed'], initial=initial) selected.extend(rows[local].tolist()); initial_source[g] = c[rows[local[0]]] before_fallback = np.asarray(selected, np.int64) extra, mode = fallback_rows(c, xyz, case['seed'], case['first'], before_fallback, prepared['fallback_slots'], saved_order) rows = np.r_[before_fallback, extra].astype(np.int64) p = c[rows] initial = np.searchsorted(case['support_flat'], p) frows = fps_indices(case['support_xyz'], case['budget'], seed=case['seed'], initial=initial) f = case['support_flat'][frows] return dict(P=p, S=f[len(p):], F=f, xyz=case['support_xyz'][frows], priority_rows=rows, patch_priority_count=np.bincount(cm[before_fallback], minlength=len(q)), actual_priority_count=np.bincount(cm[rows], minlength=len(q)), fallback_patch_count=np.bincount(cm[extra], minlength=len(q)), fallback_source=c[extra], fallback_mode=mode, patch_initial_source=initial_source)
def selection_input(case): return {k: case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz','seed','first','budget')}
def compatibility(frame, geometry, samples, cases, config, edges, normal): """Validate saved contracts only; never estimate normals or extract candidates.""" parameters = GeometryParameters() for path in (prior.TASK01/'geometry.json', prior.EDGES.parent/'comparison.json', prior.NORMAL.parent/'comparison.json'): cfg = json.loads(path.read_text())['config'] for key in ('input_sha256','masks_sha256','camera'): require_equal(cfg[key], config[key], 'evidence source '+key) if 'parameters' in cfg: require_equal(cfg['parameters'], dict(depth_jump_abs_m=.01, depth_jump_rel=.02), 'depth config') if 'depth_gate_abs_m' in cfg: require_equal((cfg['depth_gate_abs_m'], cfg['depth_gate_rel']), (.01,.02), 'pair depth config') with np.load(prior.TASK01/'f0000.npz', allow_pickle=False) as dense: require_equal(int(dense['source_frame']), 0, 'dense frame') require_equal(str(dense['camera']), config['camera'], 'dense camera') np.testing.assert_array_equal(dense['valid_depth'], np.isfinite(frame.depth) & (frame.depth > 0)) np.testing.assert_array_equal(dense['overlap_mask'], frame.masks[prior.OBJECTS['peg']] & frame.masks[prior.OBJECTS['box']]) for name, oid in prior.OBJECTS.items(): np.testing.assert_array_equal(dense[name+'/valid_points'], geometry.observed_mask(oid)) validate_saved_selection(samples, 'S3_n256_r0.25_t20_s0', frame, geometry) for archive in (edges, normal): require_equal(int(archive['source_frame']), 0, 'pair/normal frame') np.testing.assert_array_equal(archive['intrinsic'], frame.intrinsic) np.testing.assert_array_equal(archive['depth_m'], frame.depth) np.testing.assert_array_equal(edges['shape'], frame.depth.shape) pairs, checks = {}, {} h, w = frame.depth.shape indices = np.arange(h*w, dtype=np.int32).reshape(h, w) for name, case in cases.items(): oid = case['oid']; prefix = 'pca5/'+name+'/' pair = PairEvidence(**{f.name: tuple(edges[prefix+f.name]) if f.name == 'shape' else edges[prefix+f.name].copy() for f in fields(PairEvidence)}) require_equal(pair.shape, frame.depth.shape, 'pair shape') mask = geometry.object_masks[oid] right = mask[:, :-1] | mask[:, 1:]; down = mask[:-1] | mask[1:] expected = np.concatenate((np.column_stack((indices[:, :-1][right], indices[:, 1:][right])), np.column_stack((indices[:-1][down], indices[1:][down])))) np.testing.assert_array_equal(pair.pixels, expected) p = pair.pixels; valid = geometry.valid_depth.ravel()[p]; both = valid.all(1) np.testing.assert_array_equal(pair.supported, geometry.observed_mask(oid).ravel()[p]) np.testing.assert_array_equal(pair.overlap, geometry.overlap_mask.ravel()[p]) np.testing.assert_array_equal(pair.mask_boundary, mask.ravel()[p[:,0]] ^ mask.ravel()[p[:,1]]) np.testing.assert_array_equal(pair.invalid_depth_boundary, valid[:,0] ^ valid[:,1]) z = geometry.xyz[...,2].ravel()[p] delta = np.full(len(p), np.nan, np.float32); delta[both] = z[both,1]-z[both,0] np.testing.assert_array_equal(pair.signed_depth_delta_m, delta) jump = np.zeros(len(p), bool) jump[both] = np.abs(delta[both]) > parameters.depth_jump_abs_m+parameters.depth_jump_rel*z[both].min(1) np.testing.assert_array_equal(pair.depth_jump, jump) near = np.full(len(p), -1, np.int8); near[jump] = z[jump].argmin(1) np.testing.assert_array_equal(pair.near_endpoint, near) np.testing.assert_array_equal(pair.far_endpoint, np.where(jump, 1-near, -1)) for field, value in (('object_mask',mask), ('valid_points',geometry.observed_mask(oid))): np.testing.assert_array_equal(normal[prefix+field], value) nv = normal[prefix+'normal_valid'].ravel()[p].all(1) np.testing.assert_array_equal(np.isfinite(pair.normal_angle_deg), nv) # Recompute pair angles from SAVED reference normals only; no estimator. n = normal[prefix+'normals'].reshape(-1,3)[p[nv]] angle = np.rad2deg(np.arctan2(np.linalg.norm(np.cross(n[:,0],n[:,1]),axis=1), np.einsum('ij,ij->i',n[:,0],n[:,1]))) np.testing.assert_array_equal(pair.normal_angle_deg[nv], angle) endpoint = np.zeros(h*w, bool) high = pair.normal_angle_deg > 20. for k in (0,1): endpoint[p[high & pair.supported[:,k],k]] = True np.testing.assert_array_equal(endpoint.reshape(h,w), edges[prefix+'candidate20/orientation']) np.testing.assert_array_equal(np.flatnonzero(endpoint), case['candidate_flat']) normal_members = normal[prefix+'valid_points'] & (np.rad2deg(normal[prefix+'normal_variation_rad']) > 20.) np.testing.assert_array_equal(np.flatnonzero(normal_members), case['candidate_flat']) for field in ('normal_valid','valid_points','orientation_candidate'): saved = case['saved_features'][field] expected_feature = (endpoint if field == 'orientation_candidate' else normal[prefix+field].ravel())[case['saved_flat']] np.testing.assert_array_equal(saved, expected_feature) pairs[name] = pair checks[name] = dict(status='PASS',pairs=len(p),right=int(right.sum()),down=int(down.sum()), source_object_support_pixel_exact=True, depth_jump_strict_gt=True, reference_angles_exact_from_saved_reference_normals=True, candidate_threshold_membership_exact=True, saved_row_validity_membership_exact=True, optimized_pair_numeric_identity='N/A: full optimized PCA5 pair angles not stored', optimized_connection_gate_identity='N/A: endpoint candidate equality does not prove low-angle pair gate equality') return pairs, checks
def check_selection(case, chosen): c,x = case['candidate_flat'],case['support_flat'] require_equal((len(chosen['P']),len(chosen['F'])), (32,case['budget']), 'fixed budget') require_equal(int(chosen['P'][0]),case['first'],'anchor first') np.testing.assert_array_equal(chosen['F'],np.r_[chosen['P'],chosen['S']]) if not np.isin(chosen['P'],c).all() or not np.isin(c,x).all() or not np.isin(chosen['F'],x).all(): raise ValueError('P subset C subset X / F subset X') require_equal(len(np.unique(chosen['F'])),case['budget'],'unique P/S/F') np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(x,chosen['F'])])
def preserved(original): actual = prior.hashes([REPO/p for p in original]) require_equal(actual,original,'original source/input/artifact hashes') return dict(status='PASS',files=len(original),all_sha256_unchanged=True)
def serial(value): if isinstance(value,np.ndarray):return value.tolist() if isinstance(value,np.generic):return value.item() if isinstance(value,dict):return {k:serial(v) for k,v in value.items()} if isinstance(value,(tuple,list)):return [serial(v) for v in value] return value
def read_reference_selections(cases, baselines): """Read saved lambda=1 / UV controls. No reference selection is rerun.""" selections={} with np.load(UV_DIR/(previous.STEM+'.npz'),allow_pickle=False) as uv: for name,case in cases.items(): one={k:case['saved_flat'][sl].copy() for k,sl in ( ('P',slice(0,32)),('S',slice(32,None)),('F',slice(None)))} one['xyz']=case['support_xyz'][np.searchsorted(case['support_flat'],one['F'])] local={k:uv[f'{name}/local/{k}/flat_index'].copy() for k in ('P','S','F')} local['xyz']=uv[f'{name}/local/F/xyz'].copy() for k in ('P','S','F'): np.testing.assert_array_equal(uv[f'{name}/global/{k}/flat_index'],baselines[name][k]) selections[name]=dict(global0=baselines[name],global1=one,uv=local) for chosen in selections[name].values():check_selection(case,chosen) return selections
def evaluate(frame,geometry,samples,cases,selections,arrays,old,uv_old,input_config): # This function is called ONLY after selection_before_gt exists and is hashed. with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal: contexts=prior.evaluation_inputs(frame,geometry,samples,edges,normal) peg_labels,peg_members=prior.peg_labels(normal['evaluation/peg/face'],normal['evaluation/peg/gt_visible'], normal['evaluation/peg/seam_endpoints'],contexts['peg']['reference'][0]) with np.load(input_config['input'],allow_pickle=False) as episode: box_labels,box_specs,box_transform=prior.rim_labels(contexts['box']['reference'][1],frame.cam2world, episode['box_pose'][0],episode['box_hole_pose'][0],float(episode['box_hole_radii'])) actual={} for name,case in cases.items(): context=contexts[name];labels=peg_labels if name=='peg' else box_labels previous.add_arrays(arrays,'evaluation/'+name,dict(reference_uv=context['reference'][0], reference_xyz=context['reference'][1],observable=context['observable'],GT_reference_segment=labels)) row={} for method,chosen in selections[name].items(): pxyz=case['support_xyz'][np.searchsorted(case['support_flat'],chosen['P'])] spatial,raw=previous.spatial_metrics(case['candidate_flat'],case['candidate_xyz'],chosen['P'],pxyz, case['support_flat'],case['support_xyz'],frame.depth.shape) gt,data=prior.score_case(case,chosen,context,frame,labels, {} if name=='peg' else box_specs,None if name=='peg' else box_transform) previous.add_arrays(arrays,f'{name}/{method}/spatial',raw) previous.add_arrays(arrays,f'evaluation/{name}/{method}',data) row[method]=dict(spatial=spatial,gt=gt) reference = (old['cases']['S3/'+name]['conditions']['0.0'] if method=='global0' else uv_old['actual'][name]['local']['gt'] if method=='uv' else None) if reference is not None: for field in ('coverage','stages','surface_distance_mm','occupancy','feature_availability'): require_equal(gt[field],reference[field],name+'/'+method+' saved metric '+field) base,new=row['global0'],row['geometry'] row['delta_geometry_minus_global0']=dict( C_to_P_mm={k:new['spatial']['mm']['raw'][k]-base['spatial']['mm']['raw'][k] for k in ('mean','p50','p95','max')}, X_to_F_mm={k:new['gt']['surface_distance_mm'][k]-base['gt']['surface_distance_mm'][k] for k in ('mean','p95','max')}, unique_references={s:new['gt']['stages'][s]['unique_reference_count']-base['gt']['stages'][s]['unique_reference_count'] for s in ('C','P','S','F')}, negative_union={s:new['gt']['occupancy']['negative_roi']['known_negative_union'][s]['count']- base['gt']['occupancy']['negative_roi']['known_negative_union'][s]['count'] for s in ('P','S','F')}) actual[name]=row return actual,peg_members
def make_plots(output,frame,cases,prepared,selections,result,arrays): plt.rcParams.update({'font.size':9}) fig,axes=plt.subplots(2,3,figsize=(17,10),constrained_layout=True) for i,(name,case) in enumerate(cases.items()): a=prepared[name];xuv=previous.uv_from_flat(case['support_flat'],frame.depth.shape) cuv=previous.uv_from_flat(case['candidate_flat'],frame.depth.shape) axes[i,0].scatter(*xuv.T,c=a['support_patch']%20,cmap='tab20',s=2,alpha=.6) axes[i,0].scatter(*cuv.T,facecolors='none',edgecolors='black',s=11,lw=.35,label='C on X patches') zero=a['quota'][a['candidate_patch']]==0 axes[i,0].scatter(*cuv[zero].T,c='red',marker='x',s=15,label='C in quota=0 patch') axes[i,0].set_title(f'{name}: observation X patches (colours repeat)') for j,method in enumerate(('global0','geometry'),1): ax=axes[i,j];ax.scatter(*cuv.T,c='gray',s=5,alpha=.5) for stage,color,marker in [('S','#25a8b5','.'),('P','#ed7b24','o')]: uv=previous.uv_from_flat(selections[name][method][stage],frame.depth.shape) ax.scatter(*uv.T,c=color,marker=marker,s=14 if stage=='P' else 9,label=stage) worst=result['actual'][name][method]['spatial']['mm']['worst']['uv'] ax.scatter(*worst,c='red',marker='x',s=80,label='max 3D C->P source') ax.set_title(f'{name}: {method} P / S') for ax in axes[i]:ax.invert_yaxis();ax.set(xlabel='u (px)',ylabel='v (px)');ax.legend(fontsize=7) fig.savefig(output/'patch_and_selection.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(14,10),constrained_layout=True) for i,name in enumerate(cases): for method in ('global0','geometry','global1','uv'): d=arrays[f'{name}/{method}/spatial/ecdf_mm'] axes[i,0].plot(d,np.arange(1,len(d)+1)/len(d),label=method) axes[i,1].plot(d,np.arange(1,len(d)+1)/len(d),label=method) axes[i,0].set(title=f'{name}: all C->P original 3D',xlabel='mm',ylabel='ECDF') axes[i,1].set(title=f'{name}: distance tail',xlabel='mm',ylabel='ECDF',ylim=(.9,1.002)) for ax in axes[i]:ax.legend() fig.savefig(output/'candidate_3d_ecdf_tail.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(15,10),constrained_layout=True) for i,name in enumerate(cases): for j,kind in enumerate(('uv','xyz')): for method,off in [('global0',-.18),('geometry',.18)]: cells=result['actual'][name][method]['spatial']['grids'][kind]['cells'] vals=[c['distance_mm']['p95'] if c['distance_mm']['p95'] is not None else np.nan for c in cells] axes[i,j].bar(np.arange(len(cells))+off,vals,.34,label=method) axes[i,j].set(title=f'{name}: fixed independent {kind} regions',xlabel='region ID',ylabel='C->P p95 mm') axes[i,j].legend() fig.savefig(output/'independent_regions.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(16,10),constrained_layout=True) for i,name in enumerate(cases): rows=[r for r in prepared[name]['patches'] if r['C']] ids=[r['patch'] for r in rows];x=np.arange(len(ids)) axes[i,0].bar(x,[r['C'] for r in rows],label='candidate capacity',color='#b2b9c3') axes[i,0].bar(x,[r['quota'] for r in rows],label='quota',color='#ef7b22') axes[i,0].set(title=f'{name}: candidate patches incl. quota 0',ylabel='count',xticks=x,xticklabels=ids,xlabel='observation patch ID') axes[i,1].bar(x,[r['weight']*1000 for r in rows],color='#327fb7',label='C bbox span') axes[i,1].set(title=f'{name}: allocation weights (not structural length)',ylabel='span mm',xticks=x,xticklabels=ids,xlabel='observation patch ID') for ax in axes[i]:ax.legend();ax.tick_params(axis='x',labelrotation=90) fig.savefig(output/'patch_quota.png',dpi=140);plt.close(fig)
for name in cases: fig,axes=plt.subplots(2,2,figsize=(14,11),constrained_layout=True) refs=arrays[f'evaluation/{name}/reference_uv'] for i,method in enumerate(('global0','geometry')): for j,stage in enumerate(('P','F')): ax=axes[i,j];ax.imshow(frame.rgb) prefix=f'evaluation/{name}/{method}/{stage}' hit=arrays[prefix+'/covered'];matched=arrays[prefix+'/matched_node'] uv=arrays[prefix+'/pixels_vu'][:,::-1] ax.scatter(*refs[~hit].T,c='#d92e76',marker='x',s=18,label='missing GT reference') ax.scatter(*refs[hit].T,c='#1cb58c',s=16,label='covered GT reference') ax.scatter(*uv.T,facecolors='none',edgecolors='#eda420',s=28,label='selected node') ax.scatter(*uv[matched].T,facecolors='none',edgecolors='#2873dc',s=85,label='joint matching node') ax.set(xlim=(refs[:,0].min()-12,refs[:,0].max()+12),ylim=(refs[:,1].max()+12,refs[:,1].min()-12), title=f'{name} {method} {stage}: {matched.sum()} nodes / {hit.sum()} refs') ax.legend(fontsize=7) fig.suptitle('GT auxiliary evaluation labels; separate from observation patch IDs') fig.savefig(output/f'{name}_GT_auxiliary.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,3,figsize=(18,10),constrained_layout=True) for i,(name,case) in enumerate(cases.items()): for j,method in enumerate(('global0','geometry')): x=case['support_xyz'];ax=axes[i,j] ax.scatter(x[:,0]*1000,x[:,2]*1000,c='gray',s=.5,alpha=.3) for stage,color in [('P','#ed7b24'),('S','#20a6b7')]: xyz=x[np.searchsorted(case['support_flat'],selections[name][method][stage])] ax.scatter(xyz[:,0]*1000,xyz[:,2]*1000,c=color,s=15,label=stage) ax.set(title=f'{name} {method}: unfiltered X',xlabel='camera X mm',ylabel='camera Z mm');ax.legend() for method in ('global0','geometry'): d=np.sort(arrays[f'evaluation/{name}/{method}/surface_support_to_final_mm']) axes[i,2].plot(d,np.arange(1,len(d)+1)/len(d),label=method) axes[i,2].set(title=f'{name}: X->F Surface ECDF',xlabel='mm',ylabel='ECDF');axes[i,2].legend() fig.savefig(output/'surface_depth_tradeoff.png',dpi=140);plt.close(fig)
fig,axes=plt.subplots(2,2,figsize=(14,10),constrained_layout=True) for i,(name,case) in enumerate(cases.items()): xyz=case['candidate_xyz']*1000 for j,method in enumerate(('global0','geometry')): ax=axes[i,j];d=arrays[f'{name}/{method}/spatial/distance_mm'] sc=ax.scatter(xyz[:,0],xyz[:,2],c=d,cmap='magma',s=14,vmin=0, vmax=max(result['actual'][name][m]['spatial']['mm']['raw']['max'] for m in ('global0','geometry'))) pxyz=case['support_xyz'][np.searchsorted(case['support_flat'],selections[name][method]['P'])]*1000 ax.scatter(pxyz[:,0],pxyz[:,2],facecolors='none',edgecolors='cyan',s=35,label='P') worst=result['actual'][name][method]['spatial']['mm']['worst']['xyz_m'] ax.scatter(worst[0]*1000,worst[2]*1000,c='lime',marker='x',s=80,label='worst source') ax.set(title=f'{name} {method}: original C XZ / distance mm',xlabel='camera X mm',ylabel='camera Z mm') ax.legend();fig.colorbar(sc,ax=ax) fig.savefig(output/'candidate_XZ_coverage.png',dpi=140);plt.close(fig)
def documents(output,result,tests): """Create both documents from the same exact tables and interpretation.""" md=['# Task03-G — Geometry-Aware Structural Sampling, Phase 1 Feasibility',''] page=['<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task03-G Frame0 feasibility</title>', '<style>body{font:16px/1.65 system-ui,sans-serif;max-width:1500px;margin:36px auto;padding:0 24px;color:#203047} ' 'table{border-collapse:collapse;font-size:13px;margin:18px 0;display:block;overflow:auto}th,td{border:1px solid #cbd5e1;padding:6px 9px;white-space:nowrap} ' 'th{background:#eaf1f8}img{width:100%;height:auto}pre{white-space:pre-wrap}a{color:#125caa}</style>', '<h1>Task03-G — Geometry-Aware Structural Sampling</h1>'] def section(title,text=''): md.extend(['## '+title,'',text,'']);page.extend(['<h2>'+html.escape(title)+'</h2>','<p>'+html.escape(text)+'</p>']) def paragraph(text):md.extend([text,'']);page.append('<p>'+html.escape(text)+'</p>') def fmt(v): if v is None:return 'N/A' if isinstance(v,float):return f'{v:.6g}' return str(v) def table(head,rows): rows=[[fmt(v) for v in r] for r in rows] md.extend(['| '+' | '.join(head)+' |','| '+' | '.join(['---']*len(head))+' |']) md.extend('| '+' | '.join(v.replace('|','/') for v in row)+' |' for row in rows);md.append('') page.append('<table><thead><tr>'+''.join('<th>'+html.escape(h)+'</th>' for h in head)+'</tr></thead><tbody>') page.extend('<tr>'+''.join('<td>'+html.escape(v)+'</td>' for v in row)+'</tr>' for row in rows);page.append('</tbody></table>') def plot(filename,caption): md.extend([f'','']) page.append(f'<figure><img src="{filename}" alt="{html.escape(caption)}"><figcaption>{html.escape(caption)}</figcaption></figure>') paragraph('Frame0 결과: Peg C→P p95는 6.662→5.664mm로 개선됐고 Box는 29.779→30.710mm로 악화됐다. ' 'X→F Surface mean/p95는 두 물체에서 소폭 개선됐지만 Final GT reference는 Peg 160→149, Box 12→9로 줄었다. ' 'Fallback은 양쪽 0점이며, 관측 patch의 유용성은 제한적이다. 일반화 성공이나 정책 채택을 주장하지 않는다.') if result.get('report_recovery'): paragraph(f"수치 선택 UUID는 {result['report_recovery']['selection_run_id']}다. 해당 실행은 수치·문서 생성 후 최종 artifact 등록에서 " '종료 후 전용 API를 실행 중 호출해 failed로 남았다. 이번 보고 UUID는 저장 수치 NPZ와 pre-GT 선택을 byte-identical 복사한 문서 후처리이며 ' '새 FPS/평가 실행은 0회다. 실패 실행과 모든 원본 산출물은 보존했다.') section('결과 범위와 재현 정보', f"새 ExperimentLogger UUID: {result['run_id']}. ep000 Frame 0 / base_camera / S3(PCA5), N=256, structural_ratio=.25, threshold=20°, seed=0. " 'Peg P/F=32/129, Box P/F=32/127. CPU NumPy/SciPy offline 실행만 수행했다. 일반화 알고리즘 채택 근거가 아닌 관측 patch 단위의 첫 feasibility 실험이다.') paragraph('주 비교는 Task03-E 7f657cf88baf4f1f89e594252e243e1c 저장 Global λ=0이다. Task03 2551448b0fae4c6bbce3caf48774275f Global λ=1과 ' 'Task03-F 1f7ad262dd2e4b2fb0ac805a4eda5278 UV는 참고 비교다. F 최종 UUID는 기존 수치 실행의 문서 후처리이며 독립 반복 실험으로 세지 않는다.') paragraph('선택 규칙은 same-object X의 right/down pair를 기존 4-neighbour 무방향 연결로 복원하고, 양 끝 support·overlap 없음·depth_jump=False·finite angle≤20°로 고정했다. ' 'C의 각 source는 정확히 하나의 X patch에 귀속한다. C-free patch도 X와 Surface에서 보존한다. Weight는 C bbox의 3D 대각선이다. ' '전체 C의 seeded anchor 1점을 보존한 뒤 남은 31점을 capacity-capped largest remainder로 배분하고, patch 내부 원본 3D FPS와 전체 X의 Surface FPS를 사용한다.') section('Evidence compatibility 관문', 'Task01 dense XYZ·validity·mask·overlap·camera·intrinsic·cam2world와 E의 C/X, Task02-C pair source/index/support를 대조했다. ' 'Right pair는 같은 행의 +1, down은 +width이며 각 pair는 한 번만 저장된다. Depth jump는 두 depth가 유효할 때 ' '|z₂−z₁| > .01 + .02×min(z₁,z₂)이다. Equality는 jump가 아니다. Normal orientation 후보는 >20°, patch 연결은 finite ≤20°다. ' 'NaN angle은 연결하지 않는다. Normal-invalid X는 삭제하지 않는다.') table(['object','pairs','right','down','candidate/support/threshold','optimized pair identity'],[ [n,r['pairs'],r['right'],r['down'],'PASS','N/A'] for n,r in result['compatibility'].items()]) paragraph('Reference PCA5 pair angle은 저장 Task02-B normal에서 직접 재계산해 exact equality를 확인했다. 저장 orientation endpoint 및 normal variation의 >20° membership은 ' 'Task03 optimized PCA5의 저장 C와 일치했고, 저장 선택 행의 validity/candidate membership도 일치했다. ' '하지만 optimized PCA5 전체 pair angle은 저장되지 않았다. Candidate endpoint 집합의 일치가 low-angle pair별 연결 gate의 일치를 보장하지 않는다. ' '따라서 이번 patch는 Task02-C reference PCA5 evidence에서 구성했고 optimized PCA5와 bit-exact라고 주장하지 않는다. Normal estimator/candidate detector는 재실행하지 않았다.') section('선택 전 patch 분절과 allocation', '아래 patch ID는 GT-free 관측상 매끄럽게 연결된 표면 성분이다. Structural edge, physical component, 평가용 seam/rim label 또는 최종 graph edge를 뜻하지 않는다. ' 'Weight=0인 후보 patch에는 anchor 외 minimum quota가 없다. 실패를 보정하기 위한 병합·gate 변경·후보 삭제는 하지 않았다.') table(['object','X patches','C patches','X singleton','0-span C patches','0-span candidates / C','quota=0 C patches','quota=0 candidates','anchor patch/quota','fallback'],[ [n,d['X_patches'],d['candidate_patches'],d['X_singleton_patches'],d['zero_span_candidate_patches'], f"{d['zero_span_candidates']} / {result['counts'][n]['C']} ({d['zero_span_candidate_fraction']*100:.3f}%)", d['zero_quota_candidate_patches'],d['zero_quota_candidates'],f"{d['anchor_patch']} / {d['anchor_quota']}",d['actual_fallback']] for n,d in result['patch_diagnostics'].items()]) for n,d in result['patch_diagnostics'].items(): paragraph(f"{n}: singleton 또는 candidate 0-span patch {d['singleton_or_zero_span_patches']}개, 그 안의 후보 {d['singleton_or_zero_span_candidates']}개 " f"({d['singleton_or_zero_span_candidate_fraction']*100:.3f}%). Candidate가 1개인 patch {d['candidate_singleton_patches']}개, " f"X singleton에 속한 후보 {d['X_singleton_candidates']}개. 실제 fallback={d['actual_fallback']}점.") for name,rows in result['patches'].items(): paragraph(name+' 전체 X patch (C=0 포함): span은 bbox proxy이며 구조 길이가 아니다. Capacity는 전체 C 수, additional은 anchor 제외 배분이다.') table(['patch','min source','X','C/capacity','X span m','C span/weight m','anchor','additional','quota','actual P','fallback P'],[ [r['patch'],r['min_flat'],r['X'],r['C'],r['X_bbox']['span_m'],r['weight'],r['anchor_reserved'], r['additional_allocation'],r['quota'],r['actual_priority'],r['fallback_priority']] for r in rows]) plot('patch_and_selection.png','GT-free X patches, candidate attribution and Global/new P/S') plot('patch_quota.png','Candidate capacity, span weight, quota and zero quota patches') section('Primary — 원본 3D candidate·surface 보존', '모든 거리는 변환하지 않은 CV-camera XYZ의 Euclidean 최근접 거리(mm)다. P의 patch 내부 선택 metric과 독립적으로 평가했다. ' 'Grouping·span allocation·patch별 초기화·patch 내부 3D와 Global λ=0 metric 차이가 묶여 있다. 아래 차이는 선택 규칙 전체의 차이이며 개별 요소의 인과 효과가 아니다.') table(['object','method','C→P mean','p50','p95','max','X→F mean','p95','max'],[ [n,m,*[r[m]['spatial']['mm']['raw'][k] for k in ('mean','p50','p95','max')], *[r[m]['gt']['surface_distance_mm'][k] for k in ('mean','p95','max')]] for n,r in result['actual'].items() for m in ('global0','geometry','global1','uv')]) table(['object','Δ mean','Δ p50','Δ p95','Δ max','Δ Surface mean','Δ Surface p95'],[ [n,*[r['delta_geometry_minus_global0']['C_to_P_mm'][k] for k in ('mean','p50','p95','max')], *[r['delta_geometry_minus_global0']['X_to_F_mm'][k] for k in ('mean','p95')]] for n,r in result['actual'].items()]) table(['object','method','worst source','UV','XYZ m'],[ [n,m,r[m]['spatial']['mm']['worst']['flat_index'],r[m]['spatial']['mm']['worst']['uv'], r[m]['spatial']['mm']['worst']['xyz_m']] for n,r in result['actual'].items() for m in ('global0','geometry')]) plot('candidate_3d_ecdf_tail.png','C→P original 3D ECDF including tail; references are saved controls') plot('candidate_XZ_coverage.png','Candidate XYZ positions, distance tail and worst uncovered source') section('독립 평가 구역과 후보 밀도', 'Task03-F의 X bbox 기반 UV 4×4 및 XYZ 최대 2×2×2 경계와 helper를 그대로 사용했다. Candidate count, 선택률과 거리 분포를 함께 본다. ' 'Box X의 30.726m depth outlier 때문에 XYZ grid의 후보가 한 구역에 들어가는 한계를 보정하지 않았다. ' '전체 분위수는 후보 밀도의 영향을 받으며 구역 동등 가중 p95도 함께 기록한다. XYZ 공간 밀도의 공통 helper 값은 N/A이며 UV 밀도는 px²당 후보 수다.') table(['object','method','grid','C occupied','P=0 regions','equal-region mean p95 mm'],[ [n,m,k,r[m]['spatial']['grids'][k]['candidate_occupied_regions'],r[m]['spatial']['grids'][k]['empty_priority_region_ids'], r[m]['spatial']['grids'][k]['equal_region_mean_p95_mm']] for n,r in result['actual'].items() for m in ('global0','geometry') for k in ('uv','xyz')]) for n,r in result['actual'].items(): for kind in ('uv','xyz'): paragraph(n+' / '+kind+' independent regions:') table(['method','region','C','P','C density/px²','P/C','C→P mean mm','p95','max'],[ [m,c['id'],c['candidate_count'],c['priority_count'],c['candidate_density_per_px2'],c['selection_rate'], *[c['distance_mm'][k] for k in ('mean','p95','max')]] for m in ('global0','geometry') for c in r[m]['spatial']['grids'][kind]['cells']]) plot('independent_regions.png','Independent fixed UV/XYZ regions; empty candidate regions are blank') section('Secondary — GT 기반 보조 진단', '선택 및 selection_before_gt.npz 저장·hash 후 GT reference/pose/ROI를 평가에만 적용했다. ' '동일 point/reference pair가 2px AND 3mm를 만족해야 한다. Peg GT-visible 464개 중 관측 가능 462개, Box 103개 중 103개가 분모다. ' 'Matching node 수와 unique reference 수는 서로 다른 수량이다. 특정 Box rim 선분 개선은 성공 조건이 아니다.') table(['object','method','stage','nodes','matching nodes','unique refs'],[ [n,m,s,gt['gt']['stages'][s]['node_count'],gt['gt']['stages'][s]['structural_matching_nodes'], gt['gt']['stages'][s]['unique_reference_count']] for n,r in result['actual'].items() for m,gt in [(m,r[m]) for m in ('global0','geometry','global1','uv')] for s in ('C','P','S','F')]) table(['object','method','P refs','S refs','F refs','S added refs','P/S overlap refs'],[ [n,m,*[r[m]['gt']['stages'][s]['unique_reference_count'] for s in ('P','S','F')], len(set(r[m]['gt']['stages']['S']['covered_reference_ids'])-set(r[m]['gt']['stages']['P']['covered_reference_ids'])), len(set(r[m]['gt']['stages']['S']['covered_reference_ids'])&set(r[m]['gt']['stages']['P']['covered_reference_ids']))] for n,r in result['actual'].items() for m in ('global0','geometry')]) table(['object','method','stage','GT face-pair/rim segment','observed refs','covered refs','matching nodes'],[ [n,m,s,label,seg['observed_references'],seg['coverage_count'],seg['matching_node_count']] for n,r in result['actual'].items() for m in ('global0','geometry') for s in ('C','P','S','F') for label,seg in r[m]['gt']['stages'][s]['segments'].items()]) paragraph('Box의 verified line projection 간격과 missing-reference run은 JSON/NPZ에 기존 helper 정의로 저장했다. ' 'Peg face-pair 및 ambiguous reference의 물리적 선분 순서는 N/A다. Array 순서를 곡선 길이나 실제 연속 미보존 길이로 해석하지 않는다.') plot('peg_GT_auxiliary.png','Peg GT seam evaluation, separate from GT-free observation patches') plot('box_GT_auxiliary.png','Box GT rim evaluation, separate from GT-free observation patches') section('일반 Surface·negative ROI·depth·outlier trade-off', '일반 Surface는 전체 X→F로 평가한다. S만 따로 평가하거나 far point를 제거하지 않았다. ' 'Known-negative ROI union은 평가용이며 평면 Surface 점유를 자동 오선택이라고 분류하지 않는다. 원본 outlier·depth tail은 그대로 남긴다.') table(['object','method','negative P / 32','negative S','negative F','F exact feature rows','unavailable rows'],[ [n,m,*[r[m]['gt']['occupancy']['negative_roi']['known_negative_union'][s]['count'] for s in ('P','S','F')], r[m]['gt']['feature_availability']['exact_available_rows'],r[m]['gt']['feature_availability']['unavailable_rows']] for n,r in result['actual'].items() for m in ('global0','geometry')]) table(['object','method','stage','depth min m','median','p95','max'],[ [n,m,s,*[r[m]['gt']['occupancy']['depth_m'][s][k] for k in ('min','median','p95','max')]] for n,r in result['actual'].items() for m in ('global0','geometry') for s in ('X','C','P','S','F')]) paragraph('Feature는 같은 S3 조건에서 저장된 23개 field의 exact available 행만 compact gather하고 availability mask/positions를 저장했다. ' 'Missing feature는 근사 복원하지 않았다. 완전한 production Vision Tensor 검증을 주장하지 않는다.') for name,rows in result['patches'].items(): sensitive=sorted([(e['span_reduction_m'],r,e) for r in rows for e in r['extrema_leave_one_out']],key=lambda x:-x[0])[:3] table(['object','patch','extreme source','original C span m','span without one point m','drop m','quota'],[ [name,r['patch'],e['source'],r['weight'],e['span_without_point_m'],drop,r['quota']] for drop,r,e in sensitive]) paragraph('각 patch의 C/X bbox min/max XYZ와 C extrema source별 leave-one-out span을 저장했다. 위 표는 한 극단점에 민감한 상위 사례다. ' '한 점 제거 span은 진단일 뿐 선택에 적용하지 않았다. Bbox span은 실제 구조 길이가 아니며 camera 축과 outlier에 민감하다.') plot('surface_depth_tradeoff.png','Unfiltered depth and whole X→F Surface trade-off') section('Synthetic 경계와 fallback 계약', '기존 Task03-F 7개 fixture에는 dense X 및 PairEvidence가 없어 새 full-rule performance는 전부 N/A다. ' '구조 label로 patch를 만들거나 새 detector/normal/fixture를 생성하지 않았다. 기존 Global/UV 결과를 새 방법의 검증 결과로 표시하지 않는다.') table(['existing fixture','new full-rule performance','reason'],[[n,'N/A',v['reason']] for n,v in result['synthetic'].items()]) paragraph('일반 fallback은 현재 C만으로 기존 fps_indices()의 Global λ=0 순서를 만들고 이미 선택된 point를 제외해 부족분을 채운다. ' '이번 고정 입력에서는 E의 기존 검증과 저장 순서를 재사용할 수 있으며 NPZ는 fallback 규칙의 필수 입력이 아니다. ' '두 실제 물체의 fallback은 0점이어서 새 결과가 fallback으로 Global FPS를 복제한 경우는 아니다. ' '작은 synthetic 계약 테스트는 입력 C만으로 fallback을 재현하고 depth/normal veto·분리·0-span·capacity·anchor·정렬·결정성·GT 독립성을 확인한다. ' '이 테스트는 실제 형상 또는 sensor noise에 대한 일반화 성능 검증이 아니다.') section('완료 판단 — 여섯 질문', '') for text in result['interpretation_ko']:paragraph(text) section('검증과 미실행 범위',tests) paragraph('Source/input/artifact hash 불변, 모든 C의 단일 patch 귀속, quota/capacity, P=32, F=129/127, ' 'P⊆C⊆X·F⊆X, pixel/XYZ/object/role 정렬, P/S 중복 없음, NPZ exact readback, saved baseline 평가 exact equality를 확인했다. ' 'GT annotation 변경에 따른 전체 선택 불변은 annotation-free 입력/함수 및 작은 full-rule 계약 테스트로 확인하고 실제 선택 전후 archive hash도 유지했다. ' '실제 Frame0 선택을 GT 변경 후 다시 실행하지 않았다. Optimized pair-level 동일성은 N/A다.') paragraph('공통 ExperimentLogger와 experiment_artifacts의 digests/register_existing_output 및 link_output 로컬 API를 재사용했다. ' '실행 소스 snapshot, 시작 dirty diff, 입력 hash, 구현 diff와 tests.log를 새 UUID에 보존했다. ' 'Simulator/renderer·GPU/CUDA/MPS/PCL·추가 frame/episode·normal/candidate 재계산·sweep·production·Graph/GNN/BC·외부 업로드·dependency 설치·commit은 실행하지 않았다. ' 'Adaptive Budget 결합, Task-Relevance, 다른 grouping과 다음 단계는 시작하지 않고 여기서 종료한다.') paragraph('재현 명령: WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_geometry_aware_sampling ' '--original-state STATE_DIR. STATE_DIR에는 사전 파일 hash mapping인 hashes.json과 git_start.diff, git_status.txt를 둔다. ' '선택 규칙·입력 경로/hash는 preregistered_config.json, 실행 소스는 source_snapshot 또는 selection_source_snapshot에 있다. ' '보고서가 이미 존재하면 덮어쓰기를 거부하므로 별도 checkout/복제 경로에서 재현한다. 현재 결과의 문서만 재생성하려면 ' '--render-saved SELECTION_RUN_DIR을 추가한다. 원본을 수정하지 않고 새로운 보고 UUID를 생성한다.') section('산출물과 원본 링크','') files=[STEM+'.html',STEM+'.json',STEM+'.npz','selection_before_gt.npz','patch_diagnostics_before_selection.json', 'verification.json','tests.log','source_hashes.json','original_hashes.json','preregistered_config.json','implementation.patch'] for filename in files: md.extend([f'[{filename}](../../experiments/{result["run_id"]}/{filename})','']) page.append(f'<p><a href="{filename}">{filename}</a></p>') for p,label in [(previous.BASELINE/(prior.STEM+'.html'),'Task03-E saved baseline'), (UV_DIR/(previous.STEM+'.html'),'Task03-F reference / existing synthetic evidence'), (REPO/'docs/visual-graph-integration/03g_geometry_aware_sampling_plan.md','approved plan')]: md.extend([f'[{label}]({os.path.relpath(p,REPORT.parent)})','']) page.append(f'<p><a href="{os.path.relpath(p,output)}">{label}</a></p>') page.append('<p><a href="../../docs/visual-graph-integration/03g_geometry_aware_sampling.md">Markdown report</a></p></html>') REPORT.write_text('\n'.join(md),encoding='utf-8') (output/'report.md').write_text('\n'.join(md),encoding='utf-8') (output/(STEM+'.html')).write_text('\n'.join(page),encoding='utf-8')
def interpretation(result): d=result['patch_diagnostics']; a=result['actual']; patches=result['patches'] lines=[f"1. 실제 C의 분리: Peg는 X patch {d['peg']['X_patches']}개 중 C patch {d['peg']['candidate_patches']}개, " f"Box는 {d['box']['X_patches']}개 중 {d['box']['candidate_patches']}개다. " '이는 관측 normal/depth gate로 연결된 표면이지 실제 구조의 독립 분해가 아니다.'] allocation=[] for name,rows in patches.items(): allocation.append(name+': '+', '.join(f"patch {r['patch']}={r['quota']}" for r in rows if r['quota'])) lines.append('2. 3D span quota: '+'; '.join(allocation)+'. Peg의 대부분 C는 하나의 큰 surface patch에 연결되어 독립 구조별 예산을 만들지 못했다. ' 'Box는 여러 patch에 배분되었지만 넓은 bbox를 가진 patch에 예산이 집중된다.') primary=[];secondary=[] for n,row in a.items(): b,z=row['global0'],row['geometry'];bg,zg=b['gt'],z['gt'] primary.append(f"{n} C→P mean/p95/max {b['spatial']['mm']['raw']['mean']:.3f}/{b['spatial']['mm']['raw']['p95']:.3f}/{b['spatial']['mm']['raw']['max']:.3f}" f"→{z['spatial']['mm']['raw']['mean']:.3f}/{z['spatial']['mm']['raw']['p95']:.3f}/{z['spatial']['mm']['raw']['max']:.3f}mm; " f"X→F mean/p95 {bg['surface_distance_mm']['mean']:.3f}/{bg['surface_distance_mm']['p95']:.3f}" f"→{zg['surface_distance_mm']['mean']:.3f}/{zg['surface_distance_mm']['p95']:.3f}mm") secondary.append(f"{n} P/F refs {bg['stages']['P']['unique_reference_count']}/{bg['stages']['F']['unique_reference_count']}" f"→{zg['stages']['P']['unique_reference_count']}/{zg['stages']['F']['unique_reference_count']}; " f"negative P/F {bg['occupancy']['negative_roi']['known_negative_union']['P']['count']}/{bg['occupancy']['negative_roi']['known_negative_union']['F']['count']}" f"→{zg['occupancy']['negative_roi']['known_negative_union']['P']['count']}/{zg['occupancy']['negative_roi']['known_negative_union']['F']['count']}") lines.append('3. Global λ=0 대비 3D 보존: '+'; '.join(primary)+'. 손익은 지표별로 해석하며 GT 보존으로 primary 손실을 상쇄하지 않는다.') lines.append('4. 국소 구조·negative ROI: '+'; '.join(secondary)+'. Face-pair/rim 전체 구간과 Surface 추가분·overlap은 위 표에 제시했다. ' '구간별 개선·손실을 합쳐 특정 Box 선분을 성공 기준으로 삼지 않았다.') lines.append(f"5. 제한 요인: Peg/Box의 0-span 후보 {d['peg']['zero_span_candidates']}/{d['box']['zero_span_candidates']}개는 " f"span quota를 받지 못하며 quota=0 후보 patch는 {d['peg']['zero_quota_candidate_patches']}/{d['box']['zero_quota_candidate_patches']}개다. " 'Normal 불연속 주변 후보가 작은 patch로 분절되면 중요한 구조라도 quota에서 사라질 수 있는 설계 취약성이다. ' '실제 fallback은 양쪽 0점이다. Bbox 극단점 민감도와 depth outlier는 제거하지 않았고 span을 구조 길이로 해석하지 않는다.') lines.append('6. 추가 검증 판단: Frame0에서 관측 patch가 어떻게 분리·배분되는지는 재현 가능하게 설명했지만, ' 'Peg의 단일 큰 patch, Box의 fragmentation/zero-quota, reference와 optimized PCA5 pair 차이의 미확인, ' '7개 full-rule synthetic N/A가 남는다. 현재 결과만으로 일반 geometry preservation 후보의 유용성·안정성을 확립하거나 production 채택을 정당화하지 않는다. ' '관측 patch의 유용성에는 제한된 ���거만 있으며, 독립 관측·형상·camera에서 같은 고정 규칙의 별도 evidence가 필요하다. 이번에는 추가 검증을 시작하지 않는다.') return lines
def verify_documents(output): class Links(HTMLParser): def __init__(self):super().__init__();self.links=[] def handle_starttag(self,tag,attrs): self.links.extend(v for k,v in attrs if k in ('href','src')) parser=Links();content=(output/(STEM+'.html')).read_text();parser.feed(content) if re.search(r'<script|https?://',content):raise ValueError('HTML must be static and local') for target in parser.links: if not (output/target).is_file():raise ValueError('missing HTML link '+target) targets=re.findall(r'\]\(([^)]+)\)',REPORT.read_text()) for target in targets: if not (REPORT.parent/target).is_file():raise ValueError('missing Markdown link '+target) decoded={} for path in output.glob('*.png'): a=plt.imread(path) if a.ndim != 3 or min(a.shape[:2]) < 400 or a.std()<.01:raise ValueError('invalid PNG '+path.name) decoded[path.name]=list(a.shape) return dict(status='PASS',html_links=len(parser.links),markdown_links=len(targets),png_decoded=decoded)
def run(state_directory): if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required') if REPORT.exists():raise FileExistsError('refuse to overwrite existing report') state_directory=Path(state_directory) original=json.loads((state_directory/'hashes.json').read_text());preserved(original) sources=list((REPO/'visual/runtime').rglob('*.py'))+[REPO/'utils/experiment_logger.py',REPO/'utils/experiment_artifacts.py'] source_hashes=prior.hashes(sources) old=json.loads((previous.BASELINE/(prior.STEM+'.json')).read_text()) uv_old=json.loads((UV_DIR/(previous.STEM+'.json')).read_text()) require_equal(uv_old['run_id'],UV_RUN,'UV reference identity') for p,digest in old['config']['input_sha256'].items():require_equal(digests(REPO/p)[1],digest,'E saved input '+p) require_equal(json.loads((previous.BASELINE/'verification.json').read_text())['status'],'PASS','E baseline verified') input_paths=[REPO/p for p in old['config']['input_sha256']]+[ previous.BASELINE/(prior.STEM+'.npz'),previous.BASELINE/(prior.STEM+'.json'),previous.BASELINE/'verification.json', UV_DIR/(previous.STEM+'.npz'),UV_DIR/(previous.STEM+'.json'),UV_DIR/'verification.json', prior.EDGES.parent/'comparison.json',prior.NORMAL.parent/'comparison.json'] input_hashes=prior.hashes(input_paths) config=dict(task='03-G Phase1 Frame0 feasibility',rules=RULES,episode='ep000',frame=0, method='S3(PCA5)',seed=0,threshold_deg=20,structural_ratio=.25,num_points=256,priority_count=32,budgets=prior.BUDGET, source_run_id=previous.BASELINE_ID,task03=prior.SOURCE_RUN,task03f=UV_RUN, source_sha256=source_hashes,input_sha256=input_hashes,python=platform.python_version(),numpy=np.__version__, device='cpu',simulator_executed=False,gpu_executed=False,production_policy_adopted=False, baseline_FPS_replayed=False,synthetic_performance='N/A',parameters_swept=False) with ExperimentLogger(team='visual',config=config,seed=0,model='task03g_observation_patch_feasibility',job_type='evaluate') as logger: output=logger.directory try: write_json(output/'original_hashes.json',original) write_json(output/'preregistered_config.json',config);frozen_hash=digests(output/'preregistered_config.json')[1] for name in ('git_start.diff','git_status.txt'):shutil.copyfile(state_directory/name,output/name) for source in sources: dest=output/'source_snapshot'/source.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,dest) frame,geometry,samples,cases,baselines,loaded_old,input_config,contracts=previous.load_actual() require_equal(loaded_old,old,'baseline payload') with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal: pairs,gate=compatibility(frame,geometry,samples,cases,input_config,edges,normal) write_json(output/'compatibility.json',gate) selections=read_reference_selections(cases,baselines) prepared={name:prepare(selection_input(case),pairs[name]) for name,case in cases.items()} write_json(output/'patch_diagnostics_before_selection.json',serial(prepared)) print('Evidence compatibility PASS. Patch/weight/quota frozen before FPS.',flush=True) with (output/'tests.log').open('w') as log: tests=subprocess.run([sys.executable,'-m','unittest',*TESTS,'-v'],cwd=REPO,stdout=log,stderr=subprocess.STDOUT) if tests.returncode:raise RuntimeError('contract tests failed before actual selection') test_text=(output/'tests.log').read_text() test_summary=next(l for l in test_text.splitlines() if l.startswith('Ran '))+'; '+test_text.splitlines()[-1] print(test_summary,flush=True) arrays={};patches={};diagnostics={};counts={} for name,case in cases.items(): a=prepared[name] chosen=select_geometry(selection_input(case),a,baselines[name]['P']) check_selection(case,chosen) np.testing.assert_array_equal(chosen['patch_priority_count'],a['quota']) if (a['quota']>a['capacity']).any():raise ValueError('quota exceeds capacity') require_equal(int(a['quota'].sum())+len(chosen['fallback_source']),32,'quota plus fallback') selections[name]['geometry']=chosen counts[name]=dict(X=len(case['support_flat']),C=len(case['candidate_flat']),P=32,F=case['budget']) diagnostics[name]=dict(a['diagnostics'],actual_fallback=len(chosen['fallback_source']),fallback_mode=chosen['fallback_mode']) patches[name]=[dict(r,actual_priority=int(chosen['actual_priority_count'][i]), patch_FPS_priority=int(chosen['patch_priority_count'][i]),fallback_priority=int(chosen['fallback_patch_count'][i]), patch_initial_source=int(chosen['patch_initial_source'][i])) for i,r in enumerate(a['patches'])] previous.add_arrays(arrays,name,{k:case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz')}) previous.add_arrays(arrays,name+'/observation_patch',{k:a[k] for k in ( 'support_patch','candidate_patch','connection_gate','weight','capacity','quota')}) for f in fields(PairEvidence):arrays[f'{name}/observation_pair/{f.name}']=np.asarray(getattr(pairs[name],f.name)) previous.add_arrays(arrays,name+'/geometry/provenance',{k:chosen[k] for k in ( 'priority_rows','patch_priority_count','actual_priority_count','fallback_patch_count','fallback_source','patch_initial_source')}) for method,s in selections[name].items(): check_selection(case,s) for stage in ('P','S','F'): flat=s[stage] previous.add_arrays(arrays,f'{name}/{method}/{stage}',dict(flat_index=flat, pixels_vu=previous.uv_from_flat(flat,frame.depth.shape)[:,::-1], xyz=case['support_xyz'][np.searchsorted(case['support_flat'],flat)], object_id=np.full(len(flat),case['oid']), selection_role=np.full(len(flat),'Priority' if stage=='P' else 'Surface') if stage!='F' else np.where(np.arange(len(flat))<32,'Priority','Surface'))) available,positions,features=prior.feature_rows(case,s['F']) previous.add_arrays(arrays,f'{name}/{method}/F',dict(feature_available=available,feature_available_positions=positions)) previous.add_arrays(arrays,f'{name}/{method}/F/available_features',features) for method in ('global0','geometry','global1','uv'): f=np.concatenate([selections[n][method]['F'] for n in cases]) require_equal((len(f),len(np.unique(f))),(256,256),'cross-object unique budget') arrays['selection_input_hashes_json']=np.array(json.dumps(input_hashes,sort_keys=True)) np.savez_compressed(output/'selection_before_gt.npz',**arrays) before_gt_hash=digests(output/'selection_before_gt.npz')[1] print('Geometry selection fixed and saved before GT. No Global baseline FPS replay.',flush=True) actual,members=evaluate(frame,geometry,samples,cases,selections,arrays,old,uv_old,input_config) result=dict(run_id=logger.run_id,config=config,input_config=input_config,counts=counts, compatibility=gate,source_contract=contracts,patches=patches,patch_diagnostics=diagnostics, actual=actual,peg_memberships=members,selection_before_gt_sha256=before_gt_hash, synthetic={n:dict(status='N/A',reason='existing sparse C has no dense X or PairEvidence') for n in previous.FIXTURES['names']}, performance_success_required=False,contract_status='PASS',production_policy_adopted=False) result['interpretation_ko']=interpretation(result) write_json(output/(STEM+'.json'),serial(result));np.savez_compressed(output/(STEM+'.npz'),**arrays) with np.load(output/(STEM+'.npz'),allow_pickle=False) as saved: require_equal(set(saved.files),set(arrays),'NPZ key set') for k,v in arrays.items():np.testing.assert_array_equal(saved[k],v,err_msg=k) require_equal(digests(output/'selection_before_gt.npz')[1],before_gt_hash,'pre-GT archive unchanged') make_plots(output,frame,cases,prepared,selections,result,arrays) require_equal(prior.hashes(sources),source_hashes,'executed sources unchanged') require_equal(prior.hashes(input_paths),input_hashes,'input hashes unchanged') require_equal(digests(output/'preregistered_config.json')[1],frozen_hash,'frozen config') preservation=preserved(original) write_json(output/'source_hashes.json',dict(sources_before=source_hashes,sources_after=prior.hashes(sources), inputs_before=input_hashes,inputs_after=prior.hashes(input_paths),original_preservation=preservation, historical_task03e_sources=old['config']['source_sha256'])) verification=dict(status='PASS',compatibility=gate,original_preservation=preservation, required_tests=dict(summary=test_summary,modules=TESTS,failed=0), all_C_exactly_one_patch=True,quota_capacity_and_sum=True,fixed_P_F_budgets=True, P_subset_C_subset_X_F_subset_X=True,source_pixel_xyz_object_role_alignment=True, P_S_no_overlap=True,npz_exact_readback=True,pre_GT_archive_sha256_unchanged=True, GT_independence='full-rule synthetic annotation perturbation + annotation-free actual helpers; actual selection rerun=0', joint_matching_and_reference_denominators=True,baseline_and_UV_saved_metric_exact=True, optimized_pair_identity='N/A',synthetic_performance='N/A',source_input_hashes_unchanged=True, feature_unavailable_explicit=True,preregistered_config_sha256=frozen_hash, actual_fps_calls=dict(global_baseline=0,priority_patch=sum(int((p['quota']>0).sum()) for p in prepared.values()), global_fallback=sum(s['geometry']['fallback_mode']=='generated_current_C_global_order' for s in selections.values()),surface=2), no_generalization_or_adoption_claim=True, skipped=['simulator','renderer','GPU/CUDA/MPS/PCL','normal/candidate extraction','sweep','other frames/episodes', 'full-rule synthetic performance','feature reconstruction','production','external upload','install','commit']) write_json(output/'verification.json',verification) # Only this new run owns these targets; originals are never replaced. (output/'implementation.patch').touch() documents(output,result,test_summary) diff=b'' for path in (Path(__file__),Path(__file__).with_name('test_geometry_aware_sampling.py'),REPORT): proc=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,stdout=subprocess.PIPE) if proc.returncode!=1:raise ValueError('implementation diff capture failed') diff+=proc.stdout (output/'implementation.patch').write_bytes(diff) verification['document_checks']=verify_documents(output) write_json(output/'verification.json',verification) for path in sorted(output.rglob('*')): if path.is_file() and not path.name.endswith('.tracking.json') and path.name not in ('metadata.json','manifest.json','config.yaml','metrics.json'): logger.link_output(path,kind='reports') logger.link_output(REPORT,kind='reports') logger.record(source_run_id=previous.BASELINE_ID,task03_source_run_id=prior.SOURCE_RUN, task03f_source_run_id=UV_RUN,selection_before_gt_sha256=before_gt_hash, simulator_executed=False,gpu_executed=False,production_policy_adopted=False) logger.log({n:dict(candidate_mean_mm=r['geometry']['spatial']['mm']['raw']['mean'], candidate_p95_mm=r['geometry']['spatial']['mm']['raw']['p95'], surface_mean_mm=r['geometry']['gt']['surface_distance_mm']['mean'], final_refs=r['geometry']['gt']['stages']['F']['unique_reference_count']) for n,r in actual.items()},step=0,prefix='eval/task03g') print(output,flush=True) except Exception as exc: write_json(output/'attempt_failure.json',dict(status='FAIL',exception_type=type(exc).__name__,reason=str(exc), no_automatic_reselection=True,existing_attempt_preserved=True)) print('Failed attempt preserved at '+str(output),flush=True) raise register_existing_output(output,output/(STEM+'.html'),kind='reports') return output
def render_saved(previous_run,state_directory): """Reporting recovery from a complete numeric attempt, with zero FPS/evaluation.
Preserve the failed execution byte-for-byte, freeze selector/evaluator ASTs, and replace only our own just-created Markdown after checking its exact copy. """ import ast if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required') previous_run=Path(previous_run).resolve() original=json.loads((Path(state_directory)/'hashes.json').read_text());preserved(original) data=json.loads((previous_run/(STEM+'.json')).read_text()) if REPORT.exists() and REPORT.read_bytes() != (previous_run/'report.md').read_bytes(): raise FileExistsError('refuse to replace unrelated existing report') if not REPORT.exists():raise FileNotFoundError('recovery expects its exact own generated report') old_tree=ast.parse((previous_run/'source_snapshot'/Path(__file__).relative_to(REPO)).read_text()) new_tree=ast.parse(Path(__file__).read_text()) frozen=['ordered_source','patch_labels','allocate_span','prepare','fallback_rows','select_geometry', 'selection_input','compatibility','check_selection','read_reference_selections','evaluate','make_plots'] for name in frozen: old_node=next(n for n in old_tree.body if isinstance(n,ast.FunctionDef) and n.name==name) new_node=next(n for n in new_tree.body if isinstance(n,ast.FunctionDef) and n.name==name) require_equal(ast.dump(old_node),ast.dump(new_node),'unchanged numeric AST '+name) require_equal(data['config']['rules'],RULES,'unchanged rule constants') prior_hashes=prior.hashes([p for p in previous_run.rglob('*') if p.is_file()]) config=dict(task='03-G report recovery',source_run_id=previous.BASELINE_ID,selection_run_id=data['run_id'], numeric_npz_sha256=digests(previous_run/(STEM+'.npz'))[1],actual_FPS_calls=0,evaluation_calls=0, source_sha256=prior.hashes([Path(__file__),Path(__file__).with_name('test_geometry_aware_sampling.py')])) with ExperimentLogger(team='visual',config=config,seed=0,model='task03g_report_recovery',job_type='evaluate') as logger: output=logger.directory excluded={STEM+'.json',STEM+'.html','report.md','implementation.patch','verification.json','source_hashes.json', 'config.yaml','metadata.json','manifest.json','metrics.json','attempt_failure.json'} for path in previous_run.iterdir(): if path.is_file() and path.name not in excluded and not path.name.endswith('.tracking.json'): shutil.copyfile(path,output/path.name) shutil.copytree(previous_run/'source_snapshot',output/'selection_source_snapshot', ignore=shutil.ignore_patterns('*.tracking.json')) for path in (Path(__file__),Path(__file__).with_name('test_geometry_aware_sampling.py')): dest=output/'source_snapshot'/path.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,dest) for filename in ('source_hashes.json','verification.json','attempt_failure.json','report.md','implementation.patch'): shutil.copyfile(previous_run/filename,output/('selection_'+filename)) recovery=dict(selection_run_id=data['run_id'],reason='post-run artifact registration called while logger running; reporting only', this_execution_FPS_calls=0,this_execution_evaluation_calls=0,numeric_npz_byte_identical=True, selection_before_GT_byte_identical=True,frozen_numeric_AST=frozen) result=dict(data,run_id=logger.run_id,report_recovery=recovery) write_json(output/(STEM+'.json'),result) verification=json.loads((previous_run/'verification.json').read_text()) verification.update(report_recovery=recovery,selection_run_status='failed after numeric/document completion', original_preservation=preserved(original),this_execution_FPS_calls=0,this_execution_evaluation_calls=0, visual_QA=dict(status='PASS',inspected=['patch_and_selection.png','candidate_XZ_coverage.png','patch_quota.png'])) require_equal(digests(output/(STEM+'.npz'))[1],digests(previous_run/(STEM+'.npz'))[1],'numeric NPZ byte identical') require_equal(digests(output/'selection_before_gt.npz')[1],digests(previous_run/'selection_before_gt.npz')[1],'pre-GT NPZ byte identical') with (output/'tests_report_recovery.log').open('w') as log: proc=subprocess.run([sys.executable,'-m','unittest','visual.runtime.test.test_geometry_aware_sampling','-v'],cwd=REPO, stdout=log,stderr=subprocess.STDOUT) if proc.returncode:raise RuntimeError('recovery source tests failed') verification['report_recovery_tests']=dict(status='PASS',count=13,log='tests_report_recovery.log') write_json(output/'verification.json',verification) write_json(output/'source_hashes.json',dict(selection_source_hashes=json.loads((previous_run/'source_hashes.json').read_text()), reporting_source_sha256=config['source_sha256'],previous_run_files_before=prior_hashes)) (output/'implementation.patch').touch() documents(output,result,verification['required_tests']['summary']) diff=b'' for path in (Path(__file__),Path(__file__).with_name('test_geometry_aware_sampling.py'),REPORT): proc=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,stdout=subprocess.PIPE) if proc.returncode!=1:raise ValueError('implementation diff capture failed') diff+=proc.stdout (output/'implementation.patch').write_bytes(diff) verification['document_checks']=verify_documents(output) require_equal(prior.hashes([REPO/p for p in prior_hashes]),prior_hashes,'failed numeric execution unchanged') require_equal(prior.hashes([REPO/p for p in config['source_sha256']]),config['source_sha256'],'reporting sources unchanged') verification['failed_numeric_execution_preserved']=True verification['original_preservation']=preserved(original) write_json(output/'verification.json',verification) for path in sorted(output.rglob('*')): if path.is_file() and not path.name.endswith('.tracking.json') and path.name not in ('metadata.json','manifest.json','config.yaml','metrics.json'): logger.link_output(path,kind='reports') logger.link_output(REPORT,kind='reports') logger.record(source_run_id=previous.BASELINE_ID,selection_run_id=data['run_id'],report_only=True, numeric_npz_byte_identical=True,this_execution_FPS_calls=0,this_execution_evaluation_calls=0) logger.log({n:dict(candidate_p95_mm=r['geometry']['spatial']['mm']['raw']['p95'], final_refs=r['geometry']['gt']['stages']['F']['unique_reference_count']) for n,r in result['actual'].items()}, step=0,prefix='eval/task03g_saved_selection') print(output,flush=True) register_existing_output(output,output/(STEM+'.html'),kind='reports') return output
def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--original-state',type=Path,required=True,help='pre-implementation hashes.json and git_start.diff directory') parser.add_argument('--render-saved',type=Path,help='report-only recovery from complete numeric execution; no FPS/evaluation') args=parser.parse_args() if args.render_saved:render_saved(args.render_saved,args.original_state) else:run(args.original_state)
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""Small local-first scalar logger; W&B is an optional transport.
JSON is used for config.yaml (JSON is a YAML 1.2 subset). No model, dataset,checkpoint format, random state, or training schedule is owned by this module."""import importlibimport jsonimport mathimport osfrom pathlib import Pathimport reimport subprocessfrom datetime import datetime, timezonefrom uuid import uuid4import warnings
REPO = Path(__file__).resolve().parents[1]DEFAULT_PROJECT = 'graph-recurrent-vla'DEFAULT_ENV_FILE = Path('/root/.secrets/wandb.env')GROUPS = {'Graph-Recurrent-VLA-controller': 'controller', 'Graph-Recurrent-VLA-vision': 'vision', 'Graph-Recurrent-VLA-graph': 'graph'}SECRET = re.compile(r'api.?key|token|password|secret|credential', re.I)
def load_env_file(path): """Load optional local credentials without replacing existing environment.""" env_path = Path(path).expanduser() if not env_path.is_file(): return False try: from dotenv import load_dotenv except ImportError: return False try: return load_dotenv(dotenv_path=env_path, override=False, verbose=False) except (OSError, UnicodeError): return False
def load_wandb_env(path=None): return load_env_file(path or os.getenv('WANDB_ENV_FILE') or DEFAULT_ENV_FILE)
def project_name(config=None): config = config or {} return os.getenv('WANDB_PROJECT') or config.get('wandb_project') or DEFAULT_PROJECT
def has_wandb_api_key(): """Return whether an API key exists in the merged process environment.""" return bool(os.environ.get('WANDB_API_KEY', '').strip())
def clean(value): """Persist explicit config only; redact credential fields recursively.""" if isinstance(value, dict): return {str(k): '[REDACTED]' if SECRET.search(str(k)) else clean(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [clean(v) for v in value] if isinstance(value, Path): return str(value.resolve()) if value is None or isinstance(value, (str, bool, int)): return value if isinstance(value, float): return value if math.isfinite(value) else None raise TypeError(f'Expected JSON configuration or scalar, got {type(value).__name__}')
def write(path, data): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + '.' + uuid4().hex + '.tmp') temporary.write_text(json.dumps(clean(data), indent=2, allow_nan=False) + '\n') temporary.replace(path)
def git_info(): def git(*args): try: return subprocess.check_output(['git', *args], cwd=REPO, stderr=subprocess.DEVNULL, timeout=3).decode().strip() except (OSError, subprocess.SubprocessError): return None return dict(git_commit=git('rev-parse', 'HEAD'), git_dirty=bool(git('status', '--porcelain')))
def scalars(values, prefix=''): """Flatten dictionaries only; lists/tensors/videos are deliberately excluded.""" result = {} for key, value in values.items(): name = f'{prefix}/{key}' if prefix else str(key) if SECRET.search(str(key)): continue if isinstance(value, dict): result.update(scalars(value, name)) elif isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value): result[name] = value return result
class ExperimentLogger: def __init__(self, *, team, config=None, seed=None, model=None, group=None, job_type='train', root=None): if team not in ('visual', 'graph', 'recurrent', 'integration'): raise ValueError('unknown team') load_wandb_env() self.run_id = uuid4().hex self.directory = Path(root or os.getenv('EXPERIMENTS_DIR', REPO / 'experiments')) / self.run_id self.directory.mkdir(parents=True, exist_ok=False) self.config = clean(config or {}) workspace = os.getenv('VESSL_WORKSPACE_NAME', '') self.group = (group or os.getenv('WANDB_RUN_GROUP') or self.config.get('wandb_group') or self.config.get('group') or GROUPS.get(workspace) or {'visual': 'vision', 'recurrent': 'controller'}.get(team, team)) self.metadata = dict(run_id=self.run_id, team=team, group=self.group, model=model, seed=seed, job_type=job_type, project=project_name(self.config), entity=os.getenv('WANDB_ENTITY') or self.config.get('wandb_entity'), started_at=datetime.now(timezone.utc).isoformat(), status='running', outputs=[], **git_info()) self.run = None self.closed = False self._metrics = (self.directory / 'metrics.json').open('w') # An incrementally valid JSON array; flush each event for error preservation. self._metrics.write('[]\n'); self._metrics.flush() self._first = True write(self.directory / 'config.yaml', self.config) self._save() requested = os.getenv('WANDB_MODE', 'online').lower() mode = requested if requested in ('offline', 'disabled') else ( 'online' if has_wandb_api_key() and self.metadata['entity'] else 'offline') self.metadata['wandb_mode'] = mode if mode != 'disabled': try: wandb = importlib.import_module('wandb') self.run = wandb.init(project=self.metadata['project'], entity=self.metadata['entity'], id=self.run_id, group=self.group, job_type=job_type, config=dict(parameters=self.config, experiment=self.metadata.copy()), dir=str(self.directory), mode=mode, resume='never', settings=wandb.Settings(init_timeout=10, save_code=False, disable_git=True, console='off')) self.metadata['wandb_directory'] = self.run.dir self.metadata['wandb_url'] = self.run.url if mode == 'online' else None except Exception as exc: self._failure('init', exc) self._save()
def _save(self): write(self.directory / 'metadata.json', self.metadata) from .experiment_artifacts import save_manifest save_manifest(self.directory, self.metadata)
def _failure(self, operation, exc): # Exception text can contain authentication details; record type only. self.metadata.setdefault('tracking_errors', []).append(dict(operation=operation, type=type(exc).__name__)) warnings.warn(f'Experiment tracking {operation} failed ({type(exc).__name__}); local metrics retained.', RuntimeWarning)
def log(self, metrics, *, step=None, prefix=''): if self.closed: raise RuntimeError('experiment already finished') values = scalars(metrics, prefix) event = dict(run_id=self.run_id, step=step, metrics=values) self._metrics.seek(self._metrics.tell() - 2) self._metrics.write(('' if self._first else ',\n') + json.dumps(event, allow_nan=False) + ']\n') self._metrics.flush() self._first = False if self.run is not None: try: # Let W&B assign transport steps; epoch/evaluation coordinates are data. self.run.log(dict(values, **({'epoch': step} if step is not None else {}))) except Exception as exc: self._failure('log', exc) self._save()
def log_epoch(self, row): values = scalars(row) values.update(scalars(row.get('train_metrics', {}), 'train')) values.update(scalars(row.get('validation_metrics', {}), 'val')) if 'train_mse' in row: values['train/loss'] = row['train_mse'] if 'val_mse' in row: values['val/loss'] = row['val_mse'] self.log(values, step=row.get('epoch'))
def record(self, **metadata): self.metadata.update(clean(metadata)) self._save() if self.run is not None: try: self.run.config.update({'experiment': clean(self.metadata)}, allow_val_change=True) except Exception as exc: self._failure('config', exc) self._save()
def link_output(self, path, *, checkpoint=False, kind=None): """A sidecar associates unchanged existing artifacts with this run.""" if kind not in (None, 'checkpoint', 'rollouts', 'episode_metadata', 'trajectory', 'metrics', 'reports'): raise ValueError('unknown artifact kind') path = Path(path).resolve() if kind is not None: self.metadata.setdefault('artifact_kinds', {})[str(path)] = kind if str(path) not in self.metadata['outputs']: self.metadata['outputs'].append(str(path)) self._save() sidecar = path.with_name(path.name + '.tracking.json') if checkpoint: if sidecar.exists(): try: previous = json.loads(sidecar.read_text()) self.record(source_run_id=previous.get('run_id')) except (OSError, ValueError, AttributeError) as exc: self._failure('artifact', exc) self._save() return write(sidecar, dict(run_id=self.run_id, experiment_directory=str(self.directory.resolve()), artifact=str(path)))
def finish(self, failed=False): if self.closed: return self.closed = True self.metadata.update(status='failed' if failed else 'finished', finished_at=datetime.now(timezone.utc).isoformat()) self._metrics.close() try: if self.run is not None: self.run.finish(exit_code=1 if failed else 0) except Exception as exc: self._failure('finish', exc) finally: self._save()
def __enter__(self): return self
def __exit__(self, exc_type, exc, traceback): if exc_type is not None: self.metadata['exception_type'] = exc_type.__name__ self.finish(failed=exc_type is not None) return False123version https://git-lfs.github.com/spec/v1oid sha256:7978ecae2395dee91aa7ab70c193fee4149cfeb16f08bf9b505259d8276efc59size 591206123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258"""Independent PCA5 implementation optimizations; Task 01/02-B stay unchanged.
Same observed 5x5 patch-local connected component, minimum six points, cameraorientation and rank gates. Complete patches use reusable box moments; partialpatches retain explicit connectivity. Float64 is retained throughout PCA."""from __future__ import annotations
from time import perf_counterfrom concurrent.futures import ThreadPoolExecutorfrom functools import lru_cacheimport numpy as npfrom scipy.ndimage import minimum_filter, uniform_filter
from visual.runtime.geometry import ( GeometricFeatures, GeometryFrame, GeometryParameters, OrganizedGeometry, compute_geometric_features,)from visual.runtime.rgbd import BOX, PEGfrom visual.runtime.normal_estimators import _assign, _empty, _jump
def build_geometry(frame): """Dense broadcasting of the original backprojection, same operation order.""" depth = np.asarray(frame.depth) k = np.asarray(frame.intrinsic, dtype=np.float64) if depth.ndim != 2 or not min(depth.shape) or not np.issubdtype(depth.dtype, np.floating): raise ValueError('depth must be a nonempty floating point (H,W) array') if (k.shape != (3, 3) or not np.isfinite(k).all() or k[0, 0] <= 0 or k[1, 1] <= 0 or not np.allclose(k[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1])): raise ValueError('invalid zero-skew CV intrinsic') if set(frame.masks)-{PEG, BOX}: raise ValueError('unknown object ID') masks = {} for oid in (PEG, BOX): mask = np.asarray(frame.masks.get(oid, np.zeros(depth.shape, bool))) if mask.shape != depth.shape or mask.dtype != np.bool_: raise ValueError('object masks must be boolean (H,W)') masks[oid] = mask.copy() valid = np.isfinite(depth) & (depth > 0) z = np.where(valid, depth, 0) xyz = np.empty((*depth.shape, 3), np.float32) xyz[..., 0] = (np.arange(depth.shape[1])[None, :]+.5-k[0, 2])*z/k[0, 0] xyz[..., 1] = (np.arange(depth.shape[0])[:, None]+.5-k[1, 2])*z/k[1, 1] xyz[..., 2] = z if not np.isfinite(xyz).all(): raise ValueError('depth/intrinsic must yield representable float32 XYZ') xyz[~valid] = np.nan return OrganizedGeometry(xyz, valid, masks, masks[PEG] & masks[BOX])
def _bounds(mask, halo): v, u = np.nonzero(mask) if not len(v): return None return (slice(max(0, v.min()-halo), min(mask.shape[0], v.max()+halo+1)), slice(max(0, u.min()-halo), min(mask.shape[1], u.max()+halo+1)))
def covariance_patches(xyz, support, centres, parameters, *, batch_size=4096): """Original partial-patch covariance, using globally precomputed unit links.""" n = len(centres) covariance = np.zeros((n, 3, 3), float) enough = np.zeros(n, bool) if not n: return covariance, enough h, w = support.shape z = np.where(support, xyz[..., 2], 0) horizontal = support[:, :-1] & support[:, 1:] & ~_jump(z[:, :-1], z[:, 1:], parameters) vertical = support[:-1] & support[1:] & ~_jump(z[:-1], z[1:], parameters) horizontal = np.pad(horizontal, ((0, 0), (0, 1))) vertical = np.pad(vertical, ((0, 1), (0, 0))) dv, du = np.meshgrid(np.arange(-2, 3), np.arange(-2, 3), indexing='ij') for start in range(0, n, batch_size): vu = centres[start:start+batch_size] v, u = vu[:, 0, None, None]+dv, vu[:, 1, None, None]+du inside = (v >= 0) & (v < h) & (u >= 0) & (u < w) v, u = np.clip(v, 0, h-1), np.clip(u, 0, w-1) available = inside & support[v, u] hl = horizontal[v[:, :, :-1], u[:, :, :-1]] & available[:, :, :-1] & available[:, :, 1:] vl = vertical[v[:, :-1], u[:, :-1]] & available[:, :-1] & available[:, 1:] # 25 patch vertices fit in one uint32. Links encode their source bit; # no horizontal wrap because a row's last source bit is always zero. bit = np.left_shift(np.uint32(1), np.arange(25, dtype=np.uint32)).reshape(5, 5) right = np.sum(hl.astype(np.uint32)*bit[:, :-1], axis=(1, 2), dtype=np.uint32) down = np.sum(vl.astype(np.uint32)*bit[:-1], axis=(1, 2), dtype=np.uint32) reached_bits = np.full(len(vu), np.uint32(1 << 12)) for _ in range(24): nxt = (reached_bits | ((reached_bits & right) << np.uint32(1)) | ((reached_bits >> np.uint32(1)) & right) | ((reached_bits & down) << np.uint32(5)) | ((reached_bits >> np.uint32(5)) & down)) if np.array_equal(nxt, reached_bits): break reached_bits = nxt reached = ((reached_bits[:, None, None] & bit) != 0) count = reached.sum((1, 2)) good = count >= 6 enough[start:start+len(vu)] = good chosen = np.flatnonzero(good) if not len(chosen): continue delta = np.where(reached[good, ..., None], xyz[v[good], u[good]]-xyz[vu[good, 0], vu[good, 1]][:, None, None], 0) mean = delta.sum((1, 2))/count[good, None] c = np.einsum('nijk,nijl->nkl', delta, delta)/count[good, None, None] c -= mean[:, :, None]*mean[:, None, :] covariance[start+chosen] = c return covariance, enough
def smallest_eigenvector(covariance): """Closed-form symmetric 3x3 eigensystem with residual/degeneracy fallback.
Solves the same eigenproblem, not z=f(x,y) regression. Near a repeated eigenvalue or an inaccurate residual, use the original LAPACK eigensolver. """ n = len(covariance) if not n: return np.empty((0, 3)), np.empty((0, 3)), 0 scale = np.max(np.abs(covariance), axis=(1, 2)) a = covariance/np.where(scale > 0, scale, 1)[:, None, None] q = np.trace(a, axis1=1, axis2=2)/3 b = a-q[:, None, None]*np.eye(3) p = np.sqrt(np.sum(b*b, axis=(1, 2))/6) c = b/np.where(p > 0, p, 1)[:, None, None] determinant = (c[:, 0, 0]*(c[:, 1, 1]*c[:, 2, 2]-c[:, 1, 2]**2) -c[:, 0, 1]*(c[:, 0, 1]*c[:, 2, 2]-c[:, 1, 2]*c[:, 0, 2]) +c[:, 0, 2]*(c[:, 0, 1]*c[:, 1, 2]-c[:, 1, 1]*c[:, 0, 2])) phi = np.arccos(np.clip(determinant/2, -1, 1))/3 largest = q+2*p*np.cos(phi) smallest = q+2*p*np.cos(phi+2*np.pi/3) middle = 3*q-smallest-largest eigenvalues = np.column_stack((smallest, middle, largest))*scale[:, None] rows = a-smallest[:, None, None]*np.eye(3) crosses = np.stack((np.cross(rows[:, 0], rows[:, 1]), np.cross(rows[:, 0], rows[:, 2]), np.cross(rows[:, 1], rows[:, 2])), axis=1) norms = np.sum(crosses*crosses, axis=2) vectors = crosses[np.arange(n), norms.argmax(1)] lengths = np.linalg.norm(vectors, axis=1) vectors /= np.where(lengths > 0, lengths, 1)[:, None] residual = np.linalg.norm(np.einsum('nij,nj->ni', a, vectors)-smallest[:, None]*vectors, axis=1) threshold = np.maximum(1e-16, eigenvalues[:, 2]*1e-8) # Preserve delicate original rank decisions with LAPACK, too. delicate = ((eigenvalues[:, 1] <= threshold*100) | (eigenvalues[:, 1]-eigenvalues[:, 0] <= threshold*100)) fallback = (lengths < 1e-10) | (residual > 1e-10) | delicate | ~np.isfinite(residual) if fallback.any(): values, basis = np.linalg.eigh(covariance[fallback]) eigenvalues[fallback], vectors[fallback] = values, basis[:, :, 0] return eigenvalues, vectors, int(fallback.sum())
def local_plane_optimized(geometry, object_id, parameters=GeometryParameters(), *, solver='eigh', profile=None): if solver not in ('eigh', 'analytic'): raise ValueError('solver must be eigh or analytic') t0 = perf_counter() normals, valid = _empty(geometry) support_full = geometry.observed_mask(object_id) bounds = _bounds(support_full, 2) if bounds is None: if profile is not None: profile.update(points=0, fast_points=0, partial_points=0) return normals, valid support = support_full[bounds] xyz = geometry.xyz[bounds].astype(float) v, u = np.nonzero(support); vu = np.column_stack((v, u)) z = np.where(support, xyz[..., 2], 0) hl = np.zeros_like(support); vl = np.zeros_like(support) hl[:, :-1] = support[:, :-1] & support[:, 1:] & ~_jump(z[:, :-1], z[:, 1:], parameters) vl[:-1] = support[:-1] & support[1:] & ~_jump(z[:-1], z[1:], parameters) fast_map = (minimum_filter(support, size=5, mode='constant', cval=0) & minimum_filter(hl, size=(5, 4), mode='constant', cval=0) & minimum_filter(vl, size=(4, 5), mode='constant', cval=0)) fast = fast_map[v, u] t1 = perf_counter() covariance = np.zeros((len(v), 3, 3), float) enough = fast.copy() if fast.any(): # A constant translation limits cancellation in second-moment sums. shifted = np.where(support[..., None], xyz-xyz[v[0], u[0]], 0) means = [uniform_filter(shifted[..., axis], size=5, mode='constant')[v[fast], u[fast]] for axis in range(3)] for i in range(3): for j in range(i, 3): value = uniform_filter(shifted[..., i]*shifted[..., j], size=5, mode='constant')[v[fast], u[fast]]-means[i]*means[j] covariance[fast, i, j] = value; covariance[fast, j, i] = value t2 = perf_counter() slow = ~fast if slow.any(): c, ok = covariance_patches(xyz, support, vu[slow], parameters) covariance[slow], enough[slow] = c, ok t3 = perf_counter() idx = np.flatnonzero(enough) fallback = 0 if solver == 'eigh': values, vectors = np.linalg.eigh(covariance[idx]); vectors = vectors[:, :, 0] else: values, vectors, fallback = smallest_eigenvector(covariance[idx]) rank2 = values[:, 1] > np.maximum(1e-16, values[:, 2]*1e-8) unique = values[:, 1]-values[:, 0] > np.maximum(1e-16, values[:, 2]*1e-8) good = rank2 & unique & np.isfinite(values).all(1) global_vu = vu[idx[good]]+np.array([bounds[0].start, bounds[1].start]) _assign(geometry, global_vu, vectors[good], normals, valid) t4 = perf_counter() if profile is not None: profile.update(points=len(v), fast_points=int(fast.sum()), partial_points=int(slow.sum()), eigen_fallback=fallback, prepare_ms=(t1-t0)*1000, box_moments_ms=(t2-t1)*1000, partial_connectivity_covariance_ms=(t3-t2)*1000, eigensystem_scatter_ms=(t4-t3)*1000) return normals, valid
def cropped_features(geometry, oid, normals, normal_valid, parameters=GeometryParameters()): """Same feature operator on all raw mask pixels + one neighbour halo.
This is computational cropping, never an evaluation ROI or point sampling. Outputs remain full-resolution and all true image boundaries are retained. """ mask = geometry.object_masks[oid] shape = mask.shape bounds = _bounds(mask, 1) arrays = dict(object_mask=mask, valid_points=geometry.observed_mask(oid), normals=normals, normal_valid=normal_valid) floating = {'depth_jump_m', 'normal_variation_rad'} for key in GeometricFeatures.__dataclass_fields__: if key in arrays: continue arrays[key] = (np.full(shape, np.nan, np.float32) if key in floating else np.zeros(shape, np.uint8 if key=='normal_neighbor_count' else bool)) if bounds is not None: cropped = OrganizedGeometry(geometry.xyz[bounds], geometry.valid_depth[bounds], {i: m[bounds] for i, m in geometry.object_masks.items()}, geometry.overlap_mask[bounds]) result = compute_geometric_features(cropped, oid, normals[bounds], normal_valid[bounds], parameters) for key in arrays: if key not in ('object_mask', 'valid_points', 'normals', 'normal_valid'): arrays[key][bounds] = getattr(result, key) return GeometricFeatures(**arrays)
@lru_cache(maxsize=1)def _two_object_executor(): return ThreadPoolExecutor(max_workers=2, thread_name_prefix='pca5-object')
def process_optimized(frame, parameters=GeometryParameters(), *, solver='eigh', profile=None, parallel=False): start = perf_counter(); geometry = build_geometry(frame); after_geometry = perf_counter() profiles = {i: {} for i in geometry.object_masks} if parallel: executor=_two_object_executor() futures={i:executor.submit(local_plane_optimized,geometry,i,parameters,solver=solver,profile=profiles[i]) for i in geometry.object_masks} normals={i:f.result() for i,f in futures.items()} else: normals = {i: local_plane_optimized(geometry, i, parameters, solver=solver, profile=profiles[i]) for i in geometry.object_masks} after_normals = perf_counter() if parallel: futures={i:executor.submit(cropped_features,geometry,i,*normals[i],parameters) for i in geometry.object_masks} objects={i:f.result() for i,f in futures.items()} else: objects = {i: cropped_features(geometry, i, *normals[i], parameters) for i in geometry.object_masks} end = perf_counter() if profile is not None: profile.update(profiles) return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, objects, dict(geometry=(after_geometry-start)*1000, normals=(after_normals-after_geometry)*1000, discontinuity_features=(end-after_normals)*1000, total=(end-start)*1000))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Task03-D Phase 1: diagnose ONLY saved frames 0/120 and S0/S2/S3.
WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_rim_bottleneck
No sampler, normal estimator, candidate extraction, FPS or simulator is called.Results go to a new ExperimentLogger UUID directory; inputs remain read-only."""from __future__ import annotations
import argparseimport astimport jsonimport osfrom pathlib import Pathimport platformimport shutilfrom types import SimpleNamespace
import numpy as np
from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import build_organized_geometryfrom visual.runtime.rgbd import BOX, PEG, attach_rgbdfrom visual.runtime.test.normal_diagnostics import endpointsfrom visual.runtime.test.sampling_evaluation import ( CoverageMatcher, count_ratio, evaluation_context, staged_reference_coverage,)
REPO = Path(__file__).resolve().parents[3]SOURCE_RUN = '2551448b0fae4c6bbce3caf48774275f'CONDITIONS = dict(S0='S0_n256_r0_t20_s0', S2='S2_n256_r0.25_t20_s0', S3='S3_n256_r0.25_t20_s0')FRAMES = (0, 120)TARGETS = {0: (103, 103, (6, 16, 3)), 120: (41, 8, (3, 0, 2))}
def write_json(path, value): path.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n', encoding='utf-8')
def require_equal(actual, expected, label): if actual != expected: raise ValueError(f'{label} mismatch: {actual!r} != {expected!r}')
def source_contract(source, config): """Fail closed on historical evaluation changes; permit additive diagnostics.
Every original top-level function and every original CoverageMatcher method must retain its AST. Evaluation imports/constants remain unchanged too. """ records = {} for relative, expected in config['source_sha256'].items(): saved, current = source/'evaluated_source'/relative, REPO/relative require_equal(digests(saved)[1], expected, f'source snapshot {relative}') saved_tree, current_tree = ast.parse(saved.read_text()), ast.parse(current.read_text()) if relative.endswith('/sampling_evaluation.py'): functions = {n.name: n for n in current_tree.body if isinstance(n, (ast.FunctionDef, ast.ClassDef))} for node in saved_tree.body: if isinstance(node, ast.ClassDef): replacement = functions[node.name] methods = {n.name: n for n in replacement.body if isinstance(n, ast.FunctionDef)} replacement = ast.ClassDef(name=node.name, bases=replacement.bases, keywords=replacement.keywords, body=[methods[n.name] if isinstance(n, ast.FunctionDef) else n for n in node.body], decorator_list=replacement.decorator_list) elif isinstance(node, ast.FunctionDef): replacement = functions[node.name] else: if ast.dump(node) not in [ast.dump(n) for n in current_tree.body]: raise ValueError(f'historical evaluation import/constant changed: {relative}') replacement = node require_equal(ast.dump(replacement), ast.dump(node), f'historical evaluation definition {relative}') status = 'original definitions unchanged; additive diagnostics only' elif relative.endswith('/test_sampling_evaluation.py'): status = 'diagnostic tests extended; not an evaluation dependency' else: require_equal(ast.dump(current_tree), ast.dump(saved_tree), f'historical source AST {relative}') status = 'byte identical' if digests(current)[1] == expected else 'AST identical (formatting only)' records[relative] = dict(original_sha256=expected, current_sha256=digests(current)[1], status=status) return records
def geometry_evidence(frame): """Only the mask/validity fields read by the unchanged evaluation_context.
endpoints(support, ~valid_depth) is the original in-image four-neighbour depth_validity_boundary rule. No normals/features/candidates are extracted. """ geometry = build_organized_geometry(frame) objects = {oid: SimpleNamespace(object_mask=geometry.object_masks[oid], depth_validity_boundary=endpoints(geometry.observed_mask(oid), ~geometry.valid_depth)) for oid in (PEG, BOX)} return SimpleNamespace(frame=SimpleNamespace(geometry=geometry, objects=objects))
def validate_saved_selection(archive, key, frame, geometry): """Exact source raster, object support and float32 XYZ equality, no epsilon.""" require_equal(int(archive['source_frame']), frame.source_frame, 'source_frame') np.testing.assert_array_equal(archive['shape'], frame.depth.shape) flat, vu = archive[key+'/flat_index'], archive[key+'/pixels_vu'] oid, points = archive[key+'/object_id'], archive[key+'/points'] priority = archive[key+'/priority_selected'] if flat.ndim != 1 or flat.dtype.kind not in 'iu' or len(np.unique(flat)) != len(flat): raise ValueError('invalid/duplicate saved source pixels') if ((flat < 0) | (flat >= frame.depth.size)).any(): raise ValueError('source pixel outside raster') np.testing.assert_array_equal(vu, np.column_stack(np.unravel_index(flat, frame.depth.shape))) np.testing.assert_array_equal(flat, vu[:, 0]*frame.depth.shape[1]+vu[:, 1]) require_equal(len(oid), len(flat), 'object ID length') if not np.isin(oid, [PEG, BOX]).all() or priority.shape != flat.shape or priority.dtype != bool: raise ValueError('invalid object IDs/selection roles') np.testing.assert_array_equal(points, geometry.xyz.reshape(-1, 3)[flat]) for object_id in (PEG, BOX): if not geometry.observed_mask(object_id).ravel()[flat[oid == object_id]].all(): raise ValueError('saved selection outside valid unambiguous object support') if archive[key+'/depth_priority_selected'].any(): raise ValueError('unexpected depth priority in S0/S2/S3') return dict(source_frame=frame.source_frame, selected_nodes=len(flat), xyz_exact=True, max_abs_xyz_error_m=0., raster_and_object_support=True)
def depth_summary(values): values = np.asarray(values) if len(values) and not (np.isfinite(values) & (values > 0)).all(): raise ValueError('nonpositive/nonfinite depth in observed support') return dict(count=len(values), min=float(values.min()) if len(values) else None, median=float(np.median(values)) if len(values) else None, p95=float(np.percentile(values, 95)) if len(values) else None, max=float(values.max()) if len(values) else None)
def occupancy(frame, node_sets, negatives): """Per-path node occupancy; overlapping ROIs and their deduplicated union.""" masks = dict(negatives) masks['known_negative_union'] = np.logical_or.reduce(list(negatives.values())) x = node_sets['X'] roi = {} for name, mask in masks.items(): observed = int(mask.ravel()[x].sum()) roi[name] = {} for stage, flat in node_sets.items(): if flat is None: roi[name][stage] = None continue count = int(mask.ravel()[flat].sum()) roi[name][stage] = dict(count=count, fraction_of_path=count_ratio(count, len(flat)), fraction_of_observed_roi=count_ratio(count, observed)) depth = {name: depth_summary(frame.depth.ravel()[flat]) if flat is not None else None for name, flat in node_sets.items()} # Observation-derived quantile bands describe depth occupancy without an # arbitrary far cutoff or reclassifying ordinary surface nodes as errors. bounds = depth['X'] bands = {} if len(x): for stage, flat in node_sets.items(): if flat is None: bands[stage] = None continue z = frame.depth.ravel()[flat] counts = (int((z <= bounds['median']).sum()), int(((z > bounds['median']) & (z <= bounds['p95'])).sum()), int((z > bounds['p95']).sum())) bands[stage] = {name: count_ratio(n, len(z)) for name, n in zip(('z_le_X_median', 'X_median_lt_z_le_X_p95', 'z_gt_X_p95'), counts)} return dict(negative_roi=roi, depth_m=depth, depth_quantile_occupancy=bands, depth_band_bounds_m=dict(median=bounds['median'], p95=bounds['p95']))
def compare_ids(first, second): first, second = set(first), set(second) return {name: dict(count=len(ids), reference_ids=sorted(ids)) for name, ids in [('intersection', first & second), ('S2_only', first-second), ('S3_only', second-first)]}
def diagnose_frame(frame, gt, robot_ids, source): evidence = geometry_evidence(frame) geometry = evidence.frame.geometry context = evaluation_context(frame, evidence, gt, frame.camera, robot_ids) metrics = json.loads((source/f'f{frame.source_frame:04d}_metrics.json').read_text()) results, alignments = {}, {} with np.load(source/f'f{frame.source_frame:04d}_samples.npz', allow_pickle=False) as archive: # Recomputed Task02 references must be bit-exact, including ID order. # Actual matching below always uses the saved arrays. for suffix, recomputed in zip(('uv', 'xyz'), context['references']['box']): np.testing.assert_array_equal(archive[f'evaluation/box/reference_{suffix}'], recomputed) reference = tuple(archive['evaluation/box/reference_'+s] for s in ('uv', 'xyz')) matcher = CoverageMatcher(geometry, BOX, reference) for method, key in CONDITIONS.items(): require_equal(metrics[key]['source_frame'], frame.source_frame, 'metric source row') alignments[method] = validate_saved_selection(archive, key, frame, geometry) choose = archive[key+'/object_id'] == BOX f = archive[key+'/flat_index'][choose] role = archive[key+'/priority_selected'][choose] p, s = f[role], f[~role] c = None if method == 'S0' else archive[f'evidence/{"fd2" if method == "S2" else "pca5"}/1/20/orientation_flat'] if method == 'S0' and len(p): raise ValueError('General FPS unexpectedly has priority nodes') row = staged_reference_coverage(matcher, c, p if c is not None else None, s, f) original = metrics[key]['objects']['box'] rescored, _ = matcher.score(f) require_equal(rescored['tolerance'], original['structural']['tolerance'], 'frame-level coverage') counts = original['counts'] for name, n in [('observed', len(matcher.flat)), ('budget', len(f)), ('priority', len(p)), ('surface_fps', len(s)), ('selected', len(f))]: require_equal(n, counts[name], 'Box '+name) if c is not None: require_equal(len(c), counts['candidates'], 'Box candidates') require_equal(int(np.isin(f, c).sum()), counts['selected_candidates'], 'selected candidate nodes') nodes = dict(X=matcher.flat, C=c, P=p if c is not None else None, S=s, F=f) row.update(occupancy(frame, nodes, context['negatives']['box'])) for name, oid in [('peg', PEG), ('box', BOX)]: obj = archive[key+'/object_id'] == oid obj_flat = archive[key+'/flat_index'][obj] obj_priority = archive[key+'/priority_selected'][obj] estimator = 'fd2' if method == 'S2' else 'pca5' obj_candidates = archive[f'evidence/{estimator}/{oid}/20/orientation_flat'] saved_counts = metrics[key]['objects'][name]['counts'] expected_counts = dict(observed=int(geometry.observed_mask(oid).sum()), budget=len(obj_flat), candidates=len(obj_candidates), priority=int(obj_priority.sum()), orientation_priority=int(obj_priority.sum()), depth_priority=0, surface_fps=int((~obj_priority).sum()), selected=len(obj_flat), selected_candidates=int(np.isin(obj_flat, obj_candidates).sum())) require_equal(saved_counts, expected_counts, name+' allocation counters') # Prove existing ROI occupancy is reproduced, not a new ROI definition. for name, saved in original['negative'].items(): actual = row['negative_roi'][name] for old, stage in [('observed', 'X'), ('selected', 'F'), ('priority', 'P')]: require_equal(actual[stage]['count'] if actual[stage] is not None else 0, saved[old], 'saved negative ROI '+name+'/'+old) row.update(condition=key, control='General FPS; C/P not applicable' if c is None else None, allocation={name: metrics[key]['objects'][name]['counts'] for name in ('box', 'peg')}, original_frame_coverage_exact=True) results[method] = row expected_v, expected_o, expected_final = TARGETS[frame.source_frame] require_equal(len(results['S0']['reference_ids']['V']), expected_v, 'target GT') require_equal(len(results['S0']['reference_ids']['O']), expected_o, 'target observed') for method, n in zip(CONDITIONS, expected_final): require_equal(results[method]['stages']['F']['unique_reference_count'], n, 'target '+method) # Allocation targets requested explicitly, separate from reference counts. box = {m: results[m]['allocation']['box'] for m in CONDITIONS} if frame.source_frame == 0: for m in CONDITIONS: require_equal((box[m]['observed'], box[m]['budget']), (11665, 127), 'frame 0 allocation') expected = {'S2': (297, 32), 'S3': (599, 32)} else: expected = {'S2': (24, 24), 'S3': (65, 49)} for m, pair in expected.items(): require_equal((box[m]['candidates'], box[m]['priority']), pair, 'candidate/priority target '+m) comparison = {stage: compare_ids(results['S2']['reference_ids'][stage], results['S3']['reference_ids'][stage]) for stage in ('C', 'P', 'F')} return dict(source_frame=frame.source_frame, conditions=results, S2_vs_S3=comparison, alignment=alignments, saved_reference_order_and_geometry_exact=True, target_coverage_exact=True, saved_negative_roi_counts_exact=True)
def diagnose(source, output_root): if os.environ.get('WANDB_MODE') != 'disabled': raise ValueError('set WANDB_MODE=disabled for this local-only diagnostic') source = Path(source).resolve() comparison_path = source/'comparison.json' original = json.loads(comparison_path.read_text()) require_equal(original['run_id'], SOURCE_RUN, 'Task03 source run') config = original['config'] source_checks = source_contract(source, config) episode, masks = Path(config['input']), Path(config['masks']) inputs = [comparison_path, episode, masks] require_equal(digests(episode)[1], config['input_sha256'], 'episode SHA256') require_equal(digests(masks)[1], config['masks_sha256'], 'tracker mask SHA256') require_equal(config['tolerances_px_m'], [[1., .002], [2., .003], [3., .005]], 'evaluation tolerances') segmap = episode.with_name('segmentation_id_map.json') require_equal(digests(segmap)[1], config['segmentation_map_sha256'], 'segmentation map SHA256') inputs.append(segmap) tracking_path = masks.with_name('tracking.json') if tracking_path.exists(): tracking = json.loads(tracking_path.read_text()) require_equal(tracking['camera'], config['camera'], 'tracker camera') require_equal(Path(tracking['input']).resolve(), episode.resolve(), 'tracker source episode') inputs.append(tracking_path) for f in FRAMES: inputs.extend(source/f'f{f:04d}_{suffix}' for suffix in ('samples.npz', 'metrics.json')) before = {str(p): digests(p)[1] for p in inputs} current_sources = {str(p.relative_to(REPO)): digests(p)[1] for p in (Path(__file__), Path(__file__).with_name('sampling_evaluation.py'), Path(__file__).with_name('test_sampling_evaluation.py'))} diagnostic_config = dict(task='03-D', phase=1, source_run_id=SOURCE_RUN, source_directory=str(source), frames=FRAMES, conditions=CONDITIONS, tolerance_px_m=[2., .003], input_sha256=before, source_sha256=current_sources, device='cpu', gpu_executed=False, gt_diagnostic_only=True, sampler_executed=False, candidate_extraction_executed=False, normal_estimation_executed=False, python=platform.python_version(), numpy=np.__version__) with ExperimentLogger(team='visual', config=diagnostic_config, seed=0, model='task03d_rim_bottleneck', job_type='evaluate', root=output_root) as logger: output = logger.directory logger.record(source_run_id=SOURCE_RUN, evaluation_device='cpu', gpu_executed=False) print('Output:', output, flush=True) with np.load(episode, allow_pickle=False) as ep, np.load(masks, allow_pickle=False) as mask: gt_keys = [f'{config["camera"]}/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii'] gt = {k: ep[k] for k in gt_keys} sources = mask['source_frame'] np.testing.assert_array_equal(sources, np.arange(len(gt[gt_keys[0]]))) peg_masks, box_masks = mask['peg'], mask['box'] selected_rows = [int(np.flatnonzero(sources == f).item()) for f in FRAMES] tracking_rows = ((i, {1: peg_masks[row], 2: box_masks[row]}) for i, row in enumerate(selected_rows)) frames = attach_rgbd(tracking_rows, ep, camera=config['camera'], source_frames=sources[selected_rows]) rows = [diagnose_frame(frame, gt, config['robot_ids'], source) for frame in frames] require_equal(tuple(r['source_frame'] for r in rows), FRAMES, 'diagnosed sources') after = {str(p): digests(p)[1] for p in inputs} require_equal(after, before, 'input preservation SHA256') result = dict(run_id=logger.run_id, source_run_id=SOURCE_RUN, config=diagnostic_config, source_contract=source_checks, inputs_unchanged=True, frames=rows, notes=['Reference IDs index saved evaluation/box/reference_uv and reference_xyz rows.', 'All coverage uses the same pair within 2px AND 3mm.', 'Overlapping set differences and ROI counts are not additive causal losses.', 'S0 saved candidate diagnostics appear only in allocation; C/P are inapplicable.', 'Depth bands are empirical X quantiles, not filtering or far/error labels.', 'No FPS trace or causal counterfactual was executed.']) write_json(output/'diagnostic.json', result) for relative in current_sources: dest = output/'diagnostic_source'/relative dest.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(REPO/relative, dest) logger.link_output(dest, kind='reports') logger.link_output(output/'diagnostic.json', kind='metrics') for row in rows: logger.log({m: r['coverage'] for m, r in row['conditions'].items()}, step=row['source_frame'], prefix='eval/task03d') logger.record(inputs_unchanged=True, evaluated_frames=len(rows), all_target_coverage_exact=True, source_contract_verified=True) return output
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--source', type=Path, default=REPO/'visual/results/sampling'/SOURCE_RUN) parser.add_argument('--out', type=Path, default=REPO/'experiments') args = parser.parse_args() print(diagnose(args.source, args.out))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236{ "status": "PASS", "compatibility": { "peg": { "status": "PASS", "pairs": 23876, "right": 11964, "down": 11912, "source_object_support_pixel_exact": true, "depth_jump_strict_gt": true, "reference_angles_exact_from_saved_reference_normals": true, "candidate_threshold_membership_exact": true, "saved_row_validity_membership_exact": true, "optimized_pair_numeric_identity": "N/A: full optimized PCA5 pair angles not stored", "optimized_connection_gate_identity": "N/A: endpoint candidate equality does not prove low-angle pair gate equality" }, "box": { "status": "PASS", "pairs": 23645, "right": 11835, "down": 11810, "source_object_support_pixel_exact": true, "depth_jump_strict_gt": true, "reference_angles_exact_from_saved_reference_normals": true, "candidate_threshold_membership_exact": true, "saved_row_validity_membership_exact": true, "optimized_pair_numeric_identity": "N/A: full optimized PCA5 pair angles not stored", "optimized_connection_gate_identity": "N/A: endpoint candidate equality does not prove low-angle pair gate equality" } }, "original_preservation": { "status": "PASS", "files": 4325, "all_sha256_unchanged": true }, "required_tests": { "summary": "Ran 93 tests in 0.704s; OK", "modules": [ "visual.runtime.test.test_geometry_aware_sampling", "visual.runtime.test.test_local_structural_sampling", "visual.runtime.test.test_priority_fps_metric_control", "visual.runtime.test.test_sampling", "visual.runtime.test.test_sampling_geometry", "visual.runtime.test.test_sampling_evaluation", "visual.runtime.test.test_priority_fps_trace", "visual.runtime.test.test_priority_fps_seed_control" ], "failed": 0 }, "all_C_exactly_one_patch": true, "quota_capacity_and_sum": true, "fixed_P_F_budgets": true, "P_subset_C_subset_X_F_subset_X": true, "source_pixel_xyz_object_role_alignment": true, "P_S_no_overlap": true, "npz_exact_readback": true, "pre_GT_archive_sha256_unchanged": true, "GT_independence": "full-rule synthetic annotation perturbation + annotation-free actual helpers; actual selection rerun=0", "joint_matching_and_reference_denominators": true, "baseline_and_UV_saved_metric_exact": true, "optimized_pair_identity": "N/A", "synthetic_performance": "N/A", "source_input_hashes_unchanged": true, "feature_unavailable_explicit": true, "preregistered_config_sha256": "ba1494d8a23de338afb4b2b8746275ce2e38b8a2c9e0a36b0c2ea9ad0b8bb2c9", "actual_fps_calls": { "global_baseline": 0, "priority_patch": 10, "global_fallback": 0, "surface": 2 }, "no_generalization_or_adoption_claim": true, "skipped": [ "simulator", "renderer", "GPU/CUDA/MPS/PCL", "normal/candidate extraction", "sweep", "other frames/episodes", "full-rule synthetic performance", "feature reconstruction", "production", "external upload", "install", "commit" ], "document_checks": { "status": "PASS", "html_links": 23, "markdown_links": 22, "png_decoded": { "patch_and_selection.png": [ 1400, 2380, 4 ], "peg_GT_auxiliary.png": [ 1540, 1960, 4 ], "candidate_3d_ecdf_tail.png": [ 1400, 1960, 4 ], "surface_depth_tradeoff.png": [ 1400, 2520, 4 ], "html_preview.png": [ 1200, 1600, 3 ], "candidate_XZ_coverage.png": [ 1400, 1960, 4 ], "patch_quota.png": [ 1400, 2240, 4 ], "independent_regions.png": [ 1400, 2100, 4 ], "box_GT_auxiliary.png": [ 1540, 1960, 4 ] } }, "report_recovery": { "selection_run_id": "2c3d733de35c4532b2b81a0a751b7ebf", "reason": "post-run artifact registration called while logger running; reporting only", "this_execution_FPS_calls": 0, "this_execution_evaluation_calls": 0, "numeric_npz_byte_identical": true, "selection_before_GT_byte_identical": true, "frozen_numeric_AST": [ "ordered_source", "patch_labels", "allocate_span", "prepare", "fallback_rows", "select_geometry", "selection_input", "compatibility", "check_selection", "read_reference_selections", "evaluate", "make_plots" ] }, "selection_run_status": "failed after numeric/document completion", "this_execution_FPS_calls": 0, "this_execution_evaluation_calls": 0, "visual_QA": { "status": "PASS", "inspected": [ "patch_and_selection.png", "candidate_XZ_coverage.png", "patch_quota.png" ], "html_preview": "html_preview.png", "browser_render_inspected": true }, "report_recovery_tests": { "status": "PASS", "count": 13, "log": "tests_report_recovery.log" }, "failed_numeric_execution_preserved": true, "browser_image_loading": { "status": "PASS", "browser": "installed Google Chrome headless", "image_count": 8, "images": [ { "src": "patch_and_selection.png", "complete": true, "width": 2380, "height": 1400 }, { "src": "patch_quota.png", "complete": true, "width": 2240, "height": 1400 }, { "src": "candidate_3d_ecdf_tail.png", "complete": true, "width": 1960, "height": 1400 }, { "src": "candidate_XZ_coverage.png", "complete": true, "width": 1960, "height": 1400 }, { "src": "independent_regions.png", "complete": true, "width": 2100, "height": 1400 }, { "src": "peg_GT_auxiliary.png", "complete": true, "width": 1960, "height": 1540 }, { "src": "box_GT_auxiliary.png", "complete": true, "width": 1960, "height": 1540 }, { "src": "surface_depth_tradeoff.png", "complete": true, "width": 2520, "height": 1400 } ], "static_local_page": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Task03 observation provenance, budgets, geometry and regression contracts."""from dataclasses import replace, fieldsimport unittestimport numpy as np
from visual.runtime.geometry import build_organized_geometry, compute_geometric_features, process_geometry, GeometryParametersfrom visual.runtime.rgbd import PEG, BOXfrom visual.runtime.sampling import (SamplingConfig, allocate_budget, fps_indices, extract_sampling_evidence, extract_candidates, sample_points)from visual.runtime.test.normal_diagnostics import synthetic_frame, synthetic_case, quantizefrom visual.runtime.test.normal_estimators import local_planefrom visual.runtime.test.structural_edges import compare
K = np.array([[256., 0, 32], [0, 256., 32], [0, 0, 1]])
class SamplingTests(unittest.TestCase): def frame(self, n=64): depth = np.full((n, n), .25, np.float32) peg = np.zeros((n, n), bool); peg[2:n//2-1, 2:-2] = True box = np.zeros_like(peg); box[n//2+1:-2, 2:-2] = True return replace(synthetic_frame(depth, K, peg), masks={PEG: peg, BOX: box})
def evidence(self, frame=None, method='pca5'): return extract_sampling_evidence(self.frame() if frame is None else frame, method)
def test_budget_ratio_observed_uniqueness_alignment_and_reproducibility(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) e = self.evidence(f) for budget in (64, 128, 256, 512): for ratio in (0., .125, .25, .5, 1.): cfg = SamplingConfig(num_points=budget, structural_ratio=ratio) a = sample_points(e, cfg); b = sample_points(e, cfg) self.assertLessEqual(len(a.points), budget) self.assertLessEqual(int(a.priority_selected.sum()), int(budget*ratio)) self.assertEqual(len(np.unique(a.flat_index)), len(a.points)) np.testing.assert_array_equal(a.flat_index, b.flat_index) v, u = a.pixels_vu.T np.testing.assert_array_equal(a.flat_index, v*f.depth.shape[1]+u) np.testing.assert_array_equal(a.points, e.frame.geometry.xyz[v, u]) c = extract_candidates(e, cfg) for oid in (PEG, BOX): chosen = a.object_id == oid rows = np.searchsorted(c[oid].flat_index, a.flat_index[chosen]) self.assertTrue(e.frame.geometry.observed_mask(oid)[v[chosen], u[chosen]].all()) for name, values in a.metadata.items(): np.testing.assert_array_equal(values[chosen], c[oid].metadata[name][rows], err_msg=name) for field in fields(a): if field.name not in ('timings_ms', 'metadata'): if isinstance(getattr(a, field.name), np.ndarray): np.testing.assert_array_equal(getattr(a, field.name), getattr(b, field.name))
def test_zero_ratio_matches_general_fps_for_every_method(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) cfg = SamplingConfig(structural_ratio=0) baseline = sample_points(self.evidence(f), cfg, method='S0') for method, est in [('S1', 'baseline'), ('S2', 'fd2'), ('S3', 'pca5'), ('S4', 'pca5')]: a = sample_points(self.evidence(f, est), cfg, method=method) np.testing.assert_array_equal(a.flat_index, baseline.flat_index) self.assertFalse(a.priority_selected.any())
def test_plane_has_no_invented_structural_and_equals_fps(self): e = self.evidence() for method in ('S3', 'S4'): a = sample_points(e, method=method); b = sample_points(e, method='S0') self.assertFalse(a.priority_selected.any()); self.assertFalse(a.metadata['structural_candidate'].any()) np.testing.assert_array_equal(a.flat_index, b.flat_index)
def test_minimums_and_configurable_observation_allocation(self): for counts in ((1000, 1000), (3, 1000), (1000, 3), (0, 1000), (1000, 0), (0, 0), (3, 4)): a = allocate_budget(64, counts, (16, 16)) self.assertEqual(int(a.sum()), min(64, sum(counts))) self.assertTrue((a <= counts).all()) self.assertTrue((a >= np.minimum(counts, [16, 16])).all()) np.testing.assert_array_equal(allocate_budget(64, (1000, 1000), (16, 16)), [32, 32]) a = allocate_budget(64, (100, 900), (8, 8)) np.testing.assert_array_equal(a, [13, 51]) e = self.evidence(); cfg = SamplingConfig(allocation='sqrt_observed_points', min_points=(8, 8)) self.assertEqual(len(sample_points(e, cfg).points), 256)
def test_one_object_empty_current_observation_no_cache(self): for absent in (PEG, BOX): f = self.frame(); masks = {i:m.copy() for i,m in f.masks.items()}; masks[absent][:] = False a = sample_points(self.evidence(replace(f, masks=masks))) self.assertEqual(a.counts[absent]['selected'], 0) self.assertEqual(a.counts[1-absent]['selected'], 256)
def test_insufficient_both_empty_and_zero_budget(self): f = self.frame(); masks = {i:np.zeros_like(m) for i,m in f.masks.items()} for empty in (True, False): if not empty: masks[PEG][4, 4] = True; masks[BOX][40, 40] = True e = self.evidence(replace(f, masks=masks)); a = sample_points(e) self.assertEqual(len(a.points), 0 if empty else 2) self.assertEqual(a.points.shape[1:], (3,)); self.assertEqual(a.pixels_vu.shape[1:], (2,)) for values in a.metadata.values(): self.assertEqual(len(values), len(a.points)) a = sample_points(self.evidence(), SamplingConfig(num_points=0, min_points=(0, 0))) self.assertEqual(len(a.points), 0)
def test_invalid_config_is_explicit(self): cases = [dict(num_points=-1), dict(num_points=1.5), dict(num_points=True), dict(num_points=16), dict(structural_ratio=-.1), dict(structural_ratio=1.1), dict(structural_ratio=np.nan), dict(depth_priority_fraction=np.inf), dict(min_points=(-1, 1)), dict(min_points=(1,)), dict(orientation_threshold_deg=-1), dict(orientation_threshold_deg=181), dict(seed=-1), dict(allocation='random'), dict(sampling='random')] for case in cases: with self.subTest(case=case), self.assertRaises(ValueError): SamplingConfig(**case) with self.assertRaises(ValueError): allocate_budget(5, [4, 4], [3, 3]) with self.assertRaises(ValueError): allocate_budget(5, [-1, 4])
def test_sparse_candidates_surface_fills_without_duplicates(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) a = sample_points(self.evidence(f), SamplingConfig(structural_ratio=1., orientation_threshold_deg=40)) self.assertEqual(len(a.points), min(256, int(f.masks[PEG].sum()))) self.assertEqual(a.counts[PEG]['priority'], a.counts[PEG]['candidates']) self.assertGreater(a.counts[PEG]['surface_fps'], 0)
def test_real_crease_priority_hits_visible_edge_and_spreads(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) e = self.evidence(f); a = sample_points(e, SamplingConfig(num_points=64, structural_ratio=.5)) self.assertGreater(a.priority_selected.sum(), 0) vu = a.pixels_vu[a.priority_selected] # Compare to the actual two-face transition in observed synthetic geometry. self.assertLessEqual(np.max(np.abs(vu[:, 1]-31.5)), 4) candidates = extract_candidates(e, SamplingConfig())[PEG] cp = candidates.points[candidates.metadata['orientation_candidate']] chosen = a.points[a.priority_selected] self.assertGreater(np.ptp(chosen[:, 1]), .8*np.ptp(cp[:, 1]))
def test_mask_cut_and_invalid_hole_not_structural_but_depth_step_separate(self): f = self.frame(); mask = f.masks[PEG].copy(); mask[10:17, 20:28] = False e = self.evidence(replace(f, masks={PEG:mask})); a = sample_points(e, method='S4') self.assertTrue(a.metadata['mask_evidence'].any()); self.assertFalse(a.priority_selected.any()) d = f.depth.copy(); d[10:17, 20:28] = 0 e = self.evidence(replace(f, depth=d)); c = extract_candidates(e, SamplingConfig(), 'S4') self.assertTrue(c[PEG].metadata['invalid_evidence'].any()) self.assertFalse(c[PEG].metadata['depth_evidence'].any()); self.assertFalse(sample_points(e, method='S4').priority_selected.any()) d = f.depth.copy(); d[:, 32:] = .5 e = self.evidence(replace(f, depth=d)); c = extract_candidates(e, SamplingConfig(), 'S4') self.assertTrue(c[PEG].metadata['depth_evidence'].any()) self.assertTrue(c[PEG].metadata['occluding_evidence'].any()); self.assertTrue(c[PEG].metadata['occluded_evidence'].any()) self.assertFalse(sample_points(e, method='S3').priority_selected.any()) a = sample_points(e, method='S4'); self.assertGreater(a.depth_priority_selected.sum(), 0) self.assertLessEqual(a.depth_priority_selected.sum(), int(256*.25*.25))
def test_all_false_candidates_still_respect_contract_and_roles(self): f, _, _ = synthetic_case('tilted', K, shape=(64, 64), phase_m=.00025) e = self.evidence(replace(f, depth=quantize(f.depth)), 'baseline') cfg = SamplingConfig(num_points=64, structural_ratio=.125, orientation_threshold_deg=0) a = sample_points(e, cfg, method='S1') self.assertLessEqual(a.priority_selected.sum(), 8) self.assertEqual(len(a.flat_index), len(np.unique(a.flat_index))) self.assertGreater(a.metadata['structural_candidate'].sum(), a.priority_selected.sum()) self.assertTrue(a.metadata['structural_candidate'][a.priority_selected].all())
def test_overlap_invalid_depth_and_input_immutability(self): f = self.frame(); d = f.depth.copy(); d[5, 5:10] = [0, -1, np.nan, np.inf, -np.inf] box = f.masks[BOX].copy(); box[4:9, 4:9] = True f = replace(f, depth=d, masks={PEG:f.masks[PEG], BOX:box}) before = d.copy(); masks = {i:m.copy() for i,m in f.masks.items()} a = sample_points(self.evidence(f)) self.assertTrue(np.isfinite(a.points).all()); v,u = a.pixels_vu.T self.assertFalse((f.masks[PEG]&f.masks[BOX])[v,u].any()) np.testing.assert_array_equal(d, before) for i in masks: np.testing.assert_array_equal(masks[i], f.masks[i])
def test_fps_seed_ties_initial_and_coincident_rows(self): points = np.zeros((20, 3)); points[:, 0] = np.arange(20) a = fps_indices(points, 10, seed=12) np.testing.assert_array_equal(a, fps_indices(points, 10, seed=12)) b = fps_indices(points, 20, initial=a) np.testing.assert_array_equal(b[:10], a); self.assertEqual(len(np.unique(b)), 20) self.assertEqual(len(np.unique(fps_indices(np.zeros((20, 3)), 20))), 20) for bad in ([1, 1], [-1], [20]): with self.assertRaises(ValueError): fps_indices(points, 5, initial=bad)
def test_normal_and_candidate_regression_against_task02_all_fields(self): for kind in ('front', 'tilted', 'crease', 'step'): f, _, _ = synthetic_case(kind, K, shape=(64, 64), phase_m=.00025) f = replace(f, depth=quantize(f.depth)); original, pairs = compare(f) for estimator in ('baseline', 'fd2', 'pca5'): actual = self.evidence(f, estimator) for oid in (PEG, BOX): ef = original[estimator].objects[oid]; af = actual.frame.objects[oid] for name in ef.__dataclass_fields__: if name in ('normals', 'normal_variation_rad'): np.testing.assert_allclose(getattr(af,name), getattr(ef,name), atol=2e-5, rtol=0) else: np.testing.assert_array_equal(getattr(af,name),getattr(ef,name)) for t in (10, 20, 30, 40): for name, arr in pairs[estimator][oid].candidates(t).items(): np.testing.assert_array_equal(actual.pairs[oid].candidates(t)[name], arr) f = self.frame(); baseline = process_geometry(f) actual = self.evidence(f, 'baseline') for oid in (PEG,BOX): for name in baseline.objects[oid].__dataclass_fields__: np.testing.assert_array_equal(getattr(baseline.objects[oid],name),getattr(actual.frame.objects[oid],name))
def test_gt_not_accepted_and_rgb_cannot_change_selection(self): f = self.frame(); a = sample_points(self.evidence(f)) altered = replace(f, rgb=255-f.rgb, cam2world=np.full((4,4),np.nan), tcp_pose=np.full(7,np.nan)) b = sample_points(self.evidence(altered)) np.testing.assert_array_equal(a.flat_index,b.flat_index) with self.assertRaises(TypeError): sample_points(self.evidence(), gt={}) with self.assertRaises(ValueError): sample_points(self.evidence(), method='S1')
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Temporary Grounding DINO visualization runner.
Run from the repository root::
.venv/bin/python visual/runtime/test/run_grounding.py --device cpu
The default input is ``visual/data/step2/ep000.npz`` when it exists; otherwisethe checked-in Step 2 contact sheet supplies six representative RGB frames.Use ``--input`` for another episode NPZ, a contact sheet, or a PNG/JPEG.Episode NPZ files must contain``base_camera/rgb`` with shape (T,H,W,3), uint8 RGB. Annotated PNGs, detections,and an MP4 when multiple frames are available are written under ``--out``.Episode videos use every recorded camera frame and derive playback fps from therecorded timestamps when available."""
from __future__ import annotations
import argparseimport jsonimport sysimport timefrom contextlib import nullcontextfrom pathlib import Path
import cv2import imageio.v2 as imageioimport numpy as np
SCRIPT_DIR = Path(__file__).resolve().parentRUNTIME_DIR = SCRIPT_DIR.parentVISUAL_ROOT = SCRIPT_DIR.parents[1]DEFAULT_EPISODE = VISUAL_ROOT / "data/step2/ep000.npz"DEFAULT_SHEET = VISUAL_ROOT / "results/step2/ep000_base_camera_frames.jpg"sys.path.insert(0, str(RUNTIME_DIR))
from grounding import GDino # noqa: E402
PROMPTS = { "peg": "red and white block", "box": "cardboard box",}COLORS = { "peg": (255, 70, 70), "box": (60, 130, 255),}
def annotate( rgb: np.ndarray, detections: dict[str, tuple[list, list]], frame_idx: int, top_k: int = 1, scale: int = 3,) -> np.ndarray: """Draw detections on an enlarged canvas so boxes and labels are readable.""" height, width = rgb.shape[:2] enlarged = cv2.resize(rgb, (width * scale, height * scale), interpolation=cv2.INTER_CUBIC) header_height = 40 image = cv2.copyMakeBorder(enlarged, header_height, 0, 0, 0, cv2.BORDER_CONSTANT, value=(24, 24, 24)) for name, (boxes, scores) in detections.items(): color = COLORS[name] for rank, (box, score) in enumerate(zip(boxes[:top_k], scores[:top_k])): x1, y1, x2, y2 = (int(round(value * scale)) for value in box) y1 += header_height y2 += header_height thickness = max(2, scale) if rank == 0 else 1 cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness) label = f"{name} {score:.2f}" if rank == 0 else f"{name} #{rank + 1} {score:.2f}" text_y = max(header_height + 20, y1 - 6) cv2.putText(image, label, (x1 + 3, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 3, cv2.LINE_AA) cv2.putText(image, label, (x1 + 3, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 1, cv2.LINE_AA)
title = f"sample {frame_idx} | Grounding DINO" cv2.putText(image, title, (10, 27), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 1, cv2.LINE_AA) return image
def load_rgb(path: Path, camera: str, parser: argparse.ArgumentParser) -> tuple[np.ndarray, str, np.ndarray | None]: """Load an episode, a Step 2 contact sheet, or one RGB image.""" if path.suffix.lower() == ".npz": with np.load(path) as archive: rgb_key = f"{camera}/rgb" if rgb_key not in archive: parser.error(f"{path} has no '{rgb_key}' array") timestamps = archive["timestamp"] if "timestamp" in archive else None return archive[rgb_key], "episode", timestamps
bgr = cv2.imread(str(path), cv2.IMREAD_COLOR) if bgr is None: parser.error(f"could not read image: {path}") rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) if path.name.endswith(f"_{camera}_frames.jpg"): height, width = rgb.shape[:2] if width % 3 or height % (width // 3): parser.error(f"unexpected Step 2 contact sheet dimensions: {rgb.shape}") tile = width // 3 frames = np.stack([rgb[y:y + tile, :tile] for y in range(0, height, tile)]) return frames, "contact_sheet", None return rgb[None], "image", None
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--input", type=Path, default=DEFAULT_EPISODE if DEFAULT_EPISODE.is_file() else DEFAULT_SHEET, help="Episode NPZ, Step 2 contact sheet, or RGB image (uses ep000 NPZ when present)", ) parser.add_argument("--out", type=Path, default=VISUAL_ROOT / "results/runtime_grounding") parser.add_argument("--camera", default="base_camera") parser.add_argument("--stride", type=int, default=1, help="Run inference on every Nth frame (default: every frame)") parser.add_argument("--max-frames", type=int, default=None, help="Optional cap on sampled frames") parser.add_argument("--fps", type=float, default=None, help="Output video fps (default: timestamps for episodes, 2 for sheets)") parser.add_argument("--display-scale", type=int, default=None, help="Visualization scale (default: 1 at 512px or larger, otherwise 3)") parser.add_argument("--top-k", type=int, default=1, help="Draw this many boxes per prompt") parser.add_argument("--device", default="cuda") parser.add_argument("--threshold", type=float, default=0.1) parser.add_argument("--peg-prompt", default=PROMPTS["peg"]) parser.add_argument("--box-prompt", default=PROMPTS["box"]) args = parser.parse_args()
if args.stride < 1: parser.error("--stride must be at least 1") if args.fps is not None and args.fps <= 0: parser.error("--fps must be positive") if args.display_scale is not None and args.display_scale < 1: parser.error("--display-scale must be at least 1") if not args.input.is_file(): parser.error(f"input file does not exist: {args.input}") args.out.mkdir(parents=True, exist_ok=True) frames_dir = args.out / "frames" frames_dir.mkdir(parents=True, exist_ok=True)
rgb, input_kind, timestamps = load_rgb(args.input, args.camera, parser)
if rgb.ndim != 4 or rgb.shape[-1] != 3: parser.error(f"expected {args.camera}/rgb with shape (T,H,W,3), got {rgb.shape}")
stride = args.stride frame_indices = list(range(0, len(rgb), stride)) if args.max_frames is not None: frame_indices = frame_indices[:max(0, args.max_frames)] if not frame_indices: parser.error("input episode contains no frames to process") if timestamps is not None and len(timestamps) != len(rgb): parser.error(f"timestamp length {len(timestamps)} differs from RGB frame count {len(rgb)}") if args.fps is not None: fps = args.fps elif timestamps is not None and len(frame_indices) > 1: gaps = np.diff(np.asarray(timestamps)[frame_indices]) positive_gaps = gaps[gaps > 0] fps = round(float(1 / np.median(positive_gaps)), 3) if len(positive_gaps) else 10.0 else: fps = 2.0 if input_kind == "contact_sheet" else 10.0 display_scale = args.display_scale or (1 if min(rgb.shape[1:3]) >= 512 else 3)
prompts = {"peg": args.peg_prompt, "box": args.box_prompt} detector = GDino(device=args.device, threshold=args.threshold) records = [] video_path = args.out / "grounding.mp4" if len(frame_indices) > 1 else None started = time.perf_counter()
video_context = imageio.get_writer(video_path, fps=fps, macro_block_size=1) if video_path else nullcontext() with video_context as writer: for frame_idx in frame_indices: image = np.asarray(rgb[frame_idx], dtype=np.uint8) detections = {} record = {"frame": int(frame_idx), "detections": {}} for name, prompt in prompts.items(): boxes, scores = detector(image, prompt) detections[name] = (boxes, scores) record["detections"][name] = { "prompt": prompt, "boxes": boxes, "scores": scores, "timing_ms": dict(detector.last_ms), }
rendered = annotate(image, detections, frame_idx, top_k=max(1, args.top_k), scale=display_scale) frame_name = f"frame_{frame_idx:05d}.png" cv2.imwrite(str(frames_dir / frame_name), cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) if writer is not None: writer.append_data(rendered) records.append(record) print(f"frame {frame_idx}: " + ", ".join( f"{name}={len(detections[name][0])}" for name in prompts ), flush=True)
result = { "input": str(args.input.resolve()), "camera": args.camera, "input_kind": input_kind, "device": args.device, "threshold": args.threshold, "stride": stride, "fps": fps, "display_scale": display_scale, "frames_processed": len(frame_indices), "elapsed_seconds": round(time.perf_counter() - started, 3), "video": str(video_path) if video_path else None, "frames_dir": str(frames_dir), "results": records, } (args.out / "detections.json").write_text(json.dumps(result, indent=2), encoding="utf-8") if video_path: print(f"saved video: {video_path}") print(f"saved images: {frames_dir}")
if __name__ == "__main__": main()visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/config/a2bdf8f682362ee9bafb36b3d1bdc03c4d3fc5b4f08b36fe8c78f565a8bacd76/config.yamlAdded+12
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/metrics/3e339b42db14cf70581d003c1cebb9ce0838d0f8f97fc19c55765000cb16ce1d/metrics.jsonAdded+12
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522/tracking.pyAdded+93
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/011fe12780cb14ed6ca52c3bffeeb19165164085c948d5c94cb8568ec02a6837/run_geometry_aware_sampling.pyAdded+891
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f/experiment_artifacts.pyAdded+470
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a/benchmark_pca_cuda.pyAdded+92
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/1ff3e91546d35ba17d82119dca0b4398b14ab558b4dbb307b6b2f07abfee071d/selection_report.mdAdded+579
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2164f666f870d868b0464ba58f6c4c4646e15ea89cacc328166e0ab35bd00817/independent_regions.pngAdded

Large File Pointer Details
- SHA256: 2164f666f870d868b0464ba58f6c4c4646e15ea89cacc328166e0ab35bd00817
- Pointer size: 130 Bytes
- Size of remote file: 86.8 kB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/24802893205b36414f5d4ce3ca662c9ed320492bec087336786f816bedbc2d3a/html_preview.pngAdded

Large File Pointer Details
- SHA256: 24802893205b36414f5d4ce3ca662c9ed320492bec087336786f816bedbc2d3a
- Pointer size: 131 Bytes
- Size of remote file: 366 kB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252/initialization.pyAdded+77
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866/test_geometry_evaluation.pyAdded+82
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3/run_tracking.pyAdded+254
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diffAdded+259
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb/benchmark_pca_streaming.pyAdded+146
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.pyAdded+81
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/2d8489eb8857c37a7c9a954d2aedf9346d473e1bd826ddd710af5f53ec829d7d/selection_attempt_failure.jsonAdded+7
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/34fffe7fbc42ba52159cb5743b92009c3e1f2a4d67278ece35414d9f7d5eaecc/patch_and_selection.pngAdded

Large File Pointer Details
- SHA256: 34fffe7fbc42ba52159cb5743b92009c3e1f2a4d67278ece35414d9f7d5eaecc
- Pointer size: 132 Bytes
- Size of remote file: 1.17 MB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.pyAdded+255
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a/run_rgbd.pyAdded+445
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692/normal_estimators.pyAdded+2
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b/grounding.pyAdded+90
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ce95cd70f328d83ff9d4d79625be38f6a2f3aa28271ec62776a981752c98a74/03g_geometry_aware_sampling.mdAdded+585
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9/run_adaptive_node_budget.pyAdded+745
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890/pca_optimized.pyAdded+2
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/3ecc0eb1b878568e30590afca24d3445840b70f1c341659b9e52dbeb350bde29/source_hashes.jsonAdded+385
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b/run_pca_optimization.pyAdded+206
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.pyAdded+266
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4b435cbe234dafea7403249306348388206d4afd5e391c613a4b4392ffb5fef5/surface_depth_tradeoff.pngAdded

Large File Pointer Details
- SHA256: 4b435cbe234dafea7403249306348388206d4afd5e391c613a4b4392ffb5fef5
- Pointer size: 131 Bytes
- Size of remote file: 286 kB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942/test_rgbd_evaluation.pyAdded+160
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f/run_local_structural_sampling.pyAdded+944
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/4fbb605112f319103364b475ad185d07fdca56cd64e81248b7da0490be0008d6/selection_verification.jsonAdded+134
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/505329aaaab54bdd976a315454e4f5b8624f7a7b68e7e2016be99886e020e2ce/geometry_aware_sampling.npzAdded+3
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/54a9b838fc7128ab7c15ed145fb7ae3ab01bacc38c0a8f476bc50c58c989d429/candidate_3d_ecdf_tail.pngAdded

Large File Pointer Details
- SHA256: 54a9b838fc7128ab7c15ed145fb7ae3ab01bacc38c0a8f476bc50c58c989d429
- Pointer size: 131 Bytes
- Size of remote file: 201 kB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a/test_priority_fps_trace.pyAdded+64
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4/test_normal_diagnostics.pyAdded+111
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.pyAdded+475
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/691ce0b1d4a587bdf3cb39cf83b9e036d8745056c1667f04c8e3d1f8f2d45c09/candidate_XZ_coverage.pngAdded

Large File Pointer Details
- SHA256: 691ce0b1d4a587bdf3cb39cf83b9e036d8745056c1667f04c8e3d1f8f2d45c09
- Pointer size: 131 Bytes
- Size of remote file: 272 kB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692/pca_triton.pyAdded+173
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645/test_priority_fps_seed_control.pyAdded+244
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482/pca_torch.pyAdded+150
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/6fcfd638a929e793ba920297942f2b85eb6b00b066058dd0133d32a358648276/run_geometry_aware_sampling.pyAdded+993
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45/experiment_logger.pyAdded+237
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/7978ecae2395dee91aa7ab70c193fee4149cfeb16f08bf9b505259d8276efc59/selection_before_gt.npzAdded+3
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.pyAdded+258
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/7b9cbf88d81131233518433afb3318958353668a6912935d05616afca8450c37/peg_GT_auxiliary.pngAdded

Large File Pointer Details
- SHA256: 7b9cbf88d81131233518433afb3318958353668a6912935d05616afca8450c37
- Pointer size: 131 Bytes
- Size of remote file: 499 kB
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/83d1edbe90ac4f24b122887bf193183acce6c8b18bb304e6cf256aaf9cf5c0aa/verification.jsonAdded+236
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.pyAdded+206
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d/run_grounding.pyAdded+223
visual/495a67210c5c4cbfab91d013239f7ce9/artifacts/reports/875b83c1132752313b12b50ae8b6957c9de11a519bee06ce92073b33bd34ade2/patch_diagnostics_before_selection.jsonAdded