Publish experiment d3f14ee494894daabb8ba2fab8e1b00c (rollouts)
Browse filesFiles changed (17)
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/config/0e7e72647775333761a724f0c55247849b01753f51df2a4089535c30867eaedd/config.yamlAdded+43
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/1d2fd5719d0b9828c07dde87543c0468afc2d6e59d3c092ff337d735d9559d9f/visualizations_verification.jsonAdded+34
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/70a7c74709bce2a757c1512e415829cb3b676714cad85267d7c1b1eb836535d6/metrics.jsonAdded+92
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/857eec6078322285809c0322622eca4059e5be4d5d088bbb62e68a7ef6714796/diagnostic.jsonAdded
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/f36e98379144581c4d26815b4530f805053b7d46aaed4979e388049a5c075dac/verification.jsonAdded+28
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/1de58f1273afcf997f91399d3bee129ab9eabcd1407f28a9d0d36808f01f6f13/implementation.patchAdded+592
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/34c14a7aba8eba48f7aafc5f2a0ca6708dd0ffa1732a1ae68e00c84be750f4e8/execution.logAdded+2
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/6f789bf37516620bdbd2e45b27a729a331ef1d14961cd97e0606533d28c4790f/visualizations_template.htmlAdded+200
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/70742cb85640c3ab9a3441dcabbcb62bbce4b887dc5858890ec0c2054a0149b1/analysis.txtAdded+217
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8663cba6a243baf6c4a12fee5be066aeaf724c25bfcf5208e35c3014cd46ba17/build_visualizations.pyAdded+135
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.pyAdded+247
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a/report-912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a.zipAdded+3
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/9850f748895cb1decc1bb5ad67a951ac61df8cd5d5aff39bc79faf06b933c0da/visualizations.htmlAdded
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.pyAdded+248
- visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/e937b9f22220beb77e4a4a7ba6f641e179b0b1832d0f89ea27e85197c26127ef/tests.logAdded+38
- visual/d3f14ee494894daabb8ba2fab8e1b00c/manifests/c90a11bf99c71db2fe8a003348a41743c9e544ff60a7f0753486b8bcb6fdf5a1/manifest.jsonAdded+124
12345678910111213141516171819202122232425262728293031323334353637383940414243{ "candidate_extraction_executed": false, "conditions": { "S0": "S0_n256_r0_t20_s0", "S2": "S2_n256_r0.25_t20_s0", "S3": "S3_n256_r0.25_t20_s0" }, "device": "cpu", "frames": [ 0, 120 ], "gpu_executed": false, "gt_diagnostic_only": true, "input_sha256": { "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/data/step2/ep000.npz": "22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/data/step2/segmentation_id_map.json": "ffd4cf9c568b4d3ef2cec161e22c9a49b78212ae0b43c43d763d1fa4bb1f0027", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/runtime_tracking/ep000/masks.npz": "6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/runtime_tracking/ep000/tracking.json": "b78ba6064a610b77d8761e4d81fcff4660f1b5120854ec224c88b1e01017f40f", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json": "a88035aa821b879f1e6b87cf5b477af13f0d5858568ca0efa7c26c364894e94c", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_metrics.json": "6df34b94fa8e513d8872c3259bfe5a3d60b5718875b80d1715e5f8b6522ebbe8", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz": "9f6d46356212bc43bd29ceb6df34c1a96ea70b3879f0bb4da2c6ccae535dd058", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0120_metrics.json": "09a44ca8b5b91979adeca89c97aca7608cad57ac34c4796c4a7e12a92bec3207", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0120_samples.npz": "45330d9089dcc0fed13f31d8f7b2c167b8de9391ac72dcb3f741075825500e76" }, "normal_estimation_executed": false, "numpy": "2.4.6", "phase": 1, "python": "3.11.13", "sampler_executed": false, "source_directory": "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f", "source_run_id": "2551448b0fae4c6bbce3caf48774275f", "source_sha256": { "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd" }, "task": "03-D", "tolerance_px_m": [ 2.0, 0.003 ]}12345678910111213141516171819202122232425262728293031323334{ "all_stage_matched_node_counts_exact": true, "all_stage_node_counts_exact": true, "display_coordinates": "source raster UV + 0.5 onto original RGB pixel centres", "external_dependencies": [], "fps_executed": false, "frames": [ 0, 120 ], "geometry_and_saved_reference_ids_exact": true, "html_bytes": 1164642, "html_sha256": "9850f748895cb1decc1bb5ad67a951ac61df8cd5d5aff39bc79faf06b933c0da", "input_sha256": { "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/d3f14ee494894daabb8ba2fab8e1b00c/analysis.txt": "70742cb85640c3ab9a3441dcabbcb62bbce4b887dc5858890ec0c2054a0149b1", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/d3f14ee494894daabb8ba2fab8e1b00c/diagnostic.json": "2a0346704763e2a5aca9ef3d52913699ced651501b031a8b1a49c57e6dcdfcff", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/d3f14ee494894daabb8ba2fab8e1b00c/verification.json": "321688fc4ef49d0d4bade2c35bbeae0bd823e11c075fe2b8a8bc0c7bd2057341", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/data/step2/ep000.npz": "22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/data/step2/segmentation_id_map.json": "ffd4cf9c568b4d3ef2cec161e22c9a49b78212ae0b43c43d763d1fa4bb1f0027", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/runtime_tracking/ep000/masks.npz": "6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/runtime_tracking/ep000/tracking.json": "b78ba6064a610b77d8761e4d81fcff4660f1b5120854ec224c88b1e01017f40f", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json": "a88035aa821b879f1e6b87cf5b477af13f0d5858568ca0efa7c26c364894e94c", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_metrics.json": "6df34b94fa8e513d8872c3259bfe5a3d60b5718875b80d1715e5f8b6522ebbe8", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz": "9f6d46356212bc43bd29ceb6df34c1a96ea70b3879f0bb4da2c6ccae535dd058", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0120_metrics.json": "09a44ca8b5b91979adeca89c97aca7608cad57ac34c4796c4a7e12a92bec3207", "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0120_samples.npz": "45330d9089dcc0fed13f31d8f7b2c167b8de9391ac72dcb3f741075825500e76" }, "normal_estimation_executed": false, "original_inputs_unchanged": true, "renderer": "build_visualizations.py", "run_id": "d3f14ee494894daabb8ba2fab8e1b00c", "sampler_executed": false, "source_run_id": "2551448b0fae4c6bbce3caf48774275f"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192[ { "metrics": { "eval/task03d/S0/final_retention/denominator": 103, "eval/task03d/S0/final_retention/numerator": 6, "eval/task03d/S0/final_retention/value": 0.05825242718446602, "eval/task03d/S0/observation/denominator": 103, "eval/task03d/S0/observation/numerator": 103, "eval/task03d/S0/observation/value": 1.0, "eval/task03d/S0/surface/denominator": 103, "eval/task03d/S0/surface/numerator": 6, "eval/task03d/S0/surface/value": 0.05825242718446602, "eval/task03d/S2/candidate/denominator": 103, "eval/task03d/S2/candidate/numerator": 57, "eval/task03d/S2/candidate/value": 0.5533980582524272, "eval/task03d/S2/final_retention/denominator": 103, "eval/task03d/S2/final_retention/numerator": 16, "eval/task03d/S2/final_retention/value": 0.1553398058252427, "eval/task03d/S2/observation/denominator": 103, "eval/task03d/S2/observation/numerator": 103, "eval/task03d/S2/observation/value": 1.0, "eval/task03d/S2/priority/denominator": 103, "eval/task03d/S2/priority/numerator": 13, "eval/task03d/S2/priority/value": 0.1262135922330097, "eval/task03d/S2/surface/denominator": 103, "eval/task03d/S2/surface/numerator": 3, "eval/task03d/S2/surface/value": 0.02912621359223301, "eval/task03d/S3/candidate/denominator": 103, "eval/task03d/S3/candidate/numerator": 91, "eval/task03d/S3/candidate/value": 0.883495145631068, "eval/task03d/S3/final_retention/denominator": 103, "eval/task03d/S3/final_retention/numerator": 3, "eval/task03d/S3/final_retention/value": 0.02912621359223301, "eval/task03d/S3/observation/denominator": 103, "eval/task03d/S3/observation/numerator": 103, "eval/task03d/S3/observation/value": 1.0, "eval/task03d/S3/priority/denominator": 103, "eval/task03d/S3/priority/numerator": 3, "eval/task03d/S3/priority/value": 0.02912621359223301, "eval/task03d/S3/surface/denominator": 103, "eval/task03d/S3/surface/numerator": 0, "eval/task03d/S3/surface/value": 0.0 }, "run_id": "d3f14ee494894daabb8ba2fab8e1b00c", "step": 0 }, { "metrics": { "eval/task03d/S0/final_retention/denominator": 8, "eval/task03d/S0/final_retention/numerator": 3, "eval/task03d/S0/final_retention/value": 0.375, "eval/task03d/S0/observation/denominator": 41, "eval/task03d/S0/observation/numerator": 8, "eval/task03d/S0/observation/value": 0.1951219512195122, "eval/task03d/S0/surface/denominator": 8, "eval/task03d/S0/surface/numerator": 3, "eval/task03d/S0/surface/value": 0.375, "eval/task03d/S2/candidate/denominator": 8, "eval/task03d/S2/candidate/numerator": 0, "eval/task03d/S2/candidate/value": 0.0, "eval/task03d/S2/final_retention/denominator": 8, "eval/task03d/S2/final_retention/numerator": 0, "eval/task03d/S2/final_retention/value": 0.0, "eval/task03d/S2/observation/denominator": 41, "eval/task03d/S2/observation/numerator": 8, "eval/task03d/S2/observation/value": 0.1951219512195122, "eval/task03d/S2/priority/denominator": 8, "eval/task03d/S2/priority/numerator": 0, "eval/task03d/S2/priority/value": 0.0, "eval/task03d/S2/surface/denominator": 8, "eval/task03d/S2/surface/numerator": 0, "eval/task03d/S2/surface/value": 0.0, "eval/task03d/S3/candidate/denominator": 8, "eval/task03d/S3/candidate/numerator": 0, "eval/task03d/S3/candidate/value": 0.0, "eval/task03d/S3/final_retention/denominator": 8, "eval/task03d/S3/final_retention/numerator": 2, "eval/task03d/S3/final_retention/value": 0.25, "eval/task03d/S3/observation/denominator": 41, "eval/task03d/S3/observation/numerator": 8, "eval/task03d/S3/observation/value": 0.1951219512195122, "eval/task03d/S3/priority/denominator": 8, "eval/task03d/S3/priority/numerator": 0, "eval/task03d/S3/priority/value": 0.0, "eval/task03d/S3/surface/denominator": 8, "eval/task03d/S3/surface/numerator": 2, "eval/task03d/S3/surface/value": 0.25 }, "run_id": "d3f14ee494894daabb8ba2fab8e1b00c", "step": 120 }]12345678910111213141516171819202122232425262728{ "commit_created": false, "cpu_only": true, "diagnostic": { "all_original_tolerances_exact": true, "command": "WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03d-mpl .venv/bin/python -m visual.runtime.test.run_rim_bottleneck", "frames": [ 0, 120 ], "negative_roi_exact": true, "status": "PASS", "target_coverage_exact": true }, "diff_check": "PASS", "external_upload": false, "inputs_unchanged": true, "metadata_status": "finished", "run_id": "d3f14ee494894daabb8ba2fab8e1b00c", "source_run_id": "2551448b0fae4c6bbce3caf48774275f", "source_snapshot_current": true, "tests": { "command": "WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03d-mpl .venv/bin/python -m unittest visual.runtime.test.test_sampling_evaluation visual.runtime.test.test_sampling visual.runtime.test.test_sampling_geometry -v", "fail_count": 0, "pass_count": 31, "skip_count": 0 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592diff --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()diff --git a/visual/runtime/test/run_rim_bottleneck.py b/visual/runtime/test/run_rim_bottleneck.pynew file mode 100644index 0000000..35b3330--- /dev/null+++ b/visual/runtime/test/run_rim_bottleneck.py@@ -0,0 +1,342 @@+"""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 argparse+import ast+import json+import os+from pathlib import Path+import platform+import shutil+from types import SimpleNamespace++import numpy as np++from utils.experiment_artifacts import digests+from utils.experiment_logger import ExperimentLogger+from visual.runtime.geometry import build_organized_geometry+from visual.runtime.rgbd import BOX, PEG, attach_rgbd+from visual.runtime.test.normal_diagnostics import endpoints+from 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()12Output: /Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/d3f14ee494894daabb8ba2fab8e1b00c/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/d3f14ee494894daabb8ba2fab8e1b00c123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200<!doctype html><html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Task03-D · Box rim coverage 진단</title><style>:root{color-scheme:light;--ink:#162635;--muted:#526579;--line:#d7e0e8;--paper:#fff;--bg:#f5f7fa;--s0:#64748b;--s2:#0b7e76;--s3:#a74c3b;--candidate:#8762e3;--priority:#dc8800;--surface:#0089bd;--covered:#16c785;--missing:#ff5778;--lost:#a7b0be}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans KR",sans-serif}a{color:#075b9e;text-underline-offset:3px}button,select,input{font:inherit}button,select{color:var(--ink);background:white;border:1px solid #b5c4d1;border-radius:6px;padding:6px 12px}button{cursor:pointer}button:hover,select:hover{border-color:var(--s2)}button:focus-visible,select:focus-visible,input:focus-visible{outline:3px solid #84c6ff;outline-offset:3px}button[aria-pressed=true]{background:var(--ink);color:white;border-color:var(--ink)}h1{font-size:clamp(25px,3vw,38px);line-height:1.25;margin:9px 0 16px;font-weight:650;letter-spacing:-.8px}h2{font-size:23px;line-height:1.4;margin:0 0 9px;letter-spacing:-.4px}h3{font-size:17px;margin:0 0 9px;font-weight:650}p{margin:0 0 14px}.wrap{max-width:1440px;margin:auto;padding:0 28px}.masthead{padding:36px 0 26px;background:#112536;color:#f4f8fc}.masthead p{max-width:900px;color:#c6d6e4}.eyebrow{font-size:12px;letter-spacing:1.4px;color:#8ed7cc}.masthead a{color:#bde8ff}.masthead .meta{font:12px/1.7 ui-monospace,SFMono-Regular,monospace;overflow-wrap:anywhere}.toolbar{position:sticky;top:0;z-index:10;background:rgba(255,255,255,.97);border-bottom:1px solid var(--line)}.toolbar .wrap{display:flex;align-items:center;gap:18px;padding-top:12px;padding-bottom:12px;flex-wrap:wrap}.toolbar label{font-weight:600}.toolbar nav{display:flex;gap:16px;flex-wrap:wrap;margin-left:auto}.toolbar nav a{font-size:13px;text-decoration:none;color:var(--muted)}main{padding-bottom:60px}section{padding:34px 0;border-bottom:1px solid var(--line);scroll-margin-top:95px}.intro{max-width:1000px;color:var(--muted)}.takeaway{border-left:4px solid var(--s2);background:#eaf4f1;padding:15px 20px;margin:22px 0 0}.takeaway strong{color:#085c55}.facets{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px;margin-top:24px}.facet{min-width:0}.method{display:flex;align-items:center;gap:8px}.swatch{display:inline-block;width:11px;height:11px;border-radius:2px;background:var(--s0);flex-shrink:0}.method.S2 .swatch{background:var(--s2)}.method.S3 .swatch{background:var(--s3)}.chart{width:100%;display:block;overflow:visible}.chart text{fill:var(--ink);font-size:12px;font-family:inherit}.chart .muted{fill:var(--muted)}.small{font-size:13px;color:var(--muted)}.note{font-size:13px;color:var(--muted);margin-top:14px}.controls{display:flex;gap:12px 22px;flex-wrap:wrap;align-items:center;margin:18px 0}.controls label{display:inline-flex;align-items:center;gap:7px}.controls input[type=checkbox]{width:17px;height:17px;accent-color:var(--s2)}.controls select{max-width:100%;min-width:0}.controls label{min-width:0}.layer-symbol{font-size:19px;line-height:1}.table-scroll{overflow-x:auto;max-width:100%;margin-top:18px}table{border-collapse:collapse;width:100%;font-size:13px;line-height:1.5;font-variant-numeric:tabular-nums}th,td{padding:9px 12px;border-bottom:1px solid var(--line);text-align:right;white-space:nowrap}th{font-size:12px;color:var(--muted);font-weight:600}td:first-child,th:first-child{text-align:left}tbody tr:hover{background:#edf3f7}caption{text-align:left;color:var(--muted);margin-bottom:9px}details{margin-top:16px}summary{cursor:pointer;color:#29536c;font-weight:550}canvas{display:block;width:100%;touch-action:pan-y}.image-frame{background:#112331;border:1px solid #263e51;margin:0}.image-caption{font-size:12px;color:var(--muted);min-height:42px;margin-top:8px}.legend{display:flex;gap:8px 20px;flex-wrap:wrap;font-size:13px;margin:12px 0}.legend span{display:inline-flex;align-items:center;gap:6px}.dot{display:inline-block;width:9px;height:9px;background:var(--s2);border-radius:50%}.tile-legend{display:flex;gap:18px;flex-wrap:wrap;font-size:13px;margin-top:14px}.tile-legend i{display:inline-block;width:12px;height:12px;margin-right:5px;background:#dce4eb;vertical-align:middle}.reference-wrap{margin-top:18px}.reference-wrap canvas{border:1px solid var(--line);background:white}.reference-detail{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.3fr);gap:26px;align-items:start;margin-top:18px}.detail-copy{padding:12px 0;font-size:14px}.detail-copy code{font-size:12px;overflow-wrap:anywhere}code{font-family:ui-monospace,SFMono-Regular,monospace;font-size:.9em;background:#eaf0f5;padding:2px 4px;border-radius:3px}.masthead code{background:transparent;color:inherit}.yes{color:#08695f;font-weight:650}.no{color:#9f3b42}.na{color:#6c7785}.comparison{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:28px}.allocation-chart{margin-top:15px}.provenance{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:30px}.provenance ul{padding-left:20px}.tooltip{position:fixed;z-index:30;pointer-events:none;background:#13293b;color:#f2f8ff;padding:9px 12px;border-radius:5px;font-size:12px;max-width:310px;box-shadow:0 5px 20px #0003;display:none;white-space:pre-line}.status{display:inline-flex;gap:8px;align-items:center;font-size:12px;color:#087366}.status:before{content:"";width:7px;height:7px;background:#178c6a;border-radius:50%}footer{padding:25px 0;font-size:12px;color:var(--muted)}.source-links{display:flex;gap:16px;flex-wrap:wrap}.empty{padding:24px;color:var(--muted)}.download{font-size:12px;padding:3px 8px;margin-left:auto}.frame-head{display:flex;align-items:center;gap:10px;margin-bottom:9px}.frame-head h3{margin:0}.screenreader{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}@media(max-width:900px){.facets{grid-template-columns:1fr;gap:25px}.reference-detail,.provenance,.comparison{grid-template-columns:1fr}.toolbar nav{margin-left:0}.wrap{padding-left:20px;padding-right:20px}.image-frame{max-width:650px}.frame-head{max-width:650px}}@media(max-width:480px){.wrap{padding-left:14px;padding-right:14px}.masthead{padding-top:24px}.toolbar .wrap{gap:9px}.toolbar nav{gap:8px 13px}.toolbar nav a{font-size:12px}section{padding:25px 0;scroll-margin-top:140px}h2{font-size:21px}.controls{gap:10px 14px}.controls label{font-size:13px}.takeaway{padding:12px 14px}th,td{padding:8px}.download{padding:5px 8px}.reference-detail{gap:10px}.toolbar select{max-width:155px}}@media print{.toolbar{position:static}.masthead{background:white;color:var(--ink)}.masthead p,.masthead .meta,.eyebrow{color:var(--muted)}.controls,.download{display:none}section{break-inside:avoid}.facets{grid-template-columns:repeat(3,1fr)}body{background:white}}</style></head><body><header class="masthead"><div class="wrap"><div class="eyebrow">TASK03-D / PHASE 1 / SAVED ARTIFACT ANALYSIS</div><h1>Box rim coverage는 어디에서 줄어드는가</h1><p>동일한 관측·reference에서 후보, Priority, Surface 경로를 분리해 비교합니다. 막대는 독립적인 집합 coverage이며 누적 손실 funnel이 아닙니다.</p><div class="meta">Run d3f14ee494894daabb8ba2fab8e1b00c · Source 2551448b0fae4c6bbce3caf48774275f<br>CPU · Frame 0 / 120 · 256 nodes · 20° · seed 0 · 동일 pair의 2px AND 3mm</div></div></header><div class="toolbar"><div class="wrap"><label for="frame">Source frame <select id="frame"><option value="0">Frame 0 · 중심 진단</option><option value="120">Frame 120 · 대조</option></select></label><span class="status">저장 결과 재현 PASS</span><nav aria-label="보고서 섹션"><a href="#coverage">Coverage</a><a href="#spatial">RGB overlay</a><a href="#references">Reference ID</a><a href="#roi">ROI</a><a href="#depth">Depth</a><a href="#allocation">Allocation</a></nav></div></div><main class="wrap"><section id="coverage"><h2>단계별 reference coverage</h2><p class="intro" id="observation"></p><div class="facets" id="coverage-charts"></div><p class="note">X는 전체 유효 Box 관측점입니다. C/P/S/F의 분모는 모두 O이며 S0의 C/P는 N/A입니다. P와 S의 coverage는 겹칠 수 있으므로 막대를 단순 합산하지 않습니다.</p><div class="takeaway" id="takeaway" aria-live="polite"></div><details open><summary>Node 수와 unique reference 수 구분</summary><div class="table-scroll" id="stage-table"></div></details></section><section id="spatial"><h2>같은 RGB와 crop에서 후보와 선택점 비교</h2><p class="intro">각 패널은 원본 RGB, 저장된 source pixel, 같은 GT reference를 사용합니다. 확대는 표시 범위만 바꾸며 입력이나 coverage를 바꾸지 않습니다.</p><div class="controls"><label>시야 <select id="crop"><option value="rim">Box rim 확대</option><option value="box">전체 Box mask 범위</option><option value="full">전체 RGB</option></select></label><label><input type="checkbox" id="layer-X"><span class="layer-symbol" style="color:#7f94a4">·</span>X 관측점</label><label><input type="checkbox" id="layer-C" checked><span class="layer-symbol" style="color:var(--candidate)">·</span>C 후보</label><label><input type="checkbox" id="layer-P" checked><span class="layer-symbol" style="color:var(--priority)">★</span>P Priority</label><label><input type="checkbox" id="layer-S" checked><span class="layer-symbol" style="color:var(--surface)">○</span>S Surface</label><label><input type="checkbox" id="layer-R" checked>+ Reference</label><label><input type="checkbox" id="layer-M">Tracker mask 윤곽</label></div><div class="legend"><span><i class="dot" style="background:var(--covered)"></i>최종 F가 덮는 reference</span><span><i class="dot" style="background:var(--missing)"></i>관측 가능 O 중 F가 덮지 못함</span><span><i class="dot" style="background:var(--lost)"></i>V ∖ O 관측 손실</span></div><div class="facets" id="image-panels"></div><p class="note">Reference를 클릭하면 세 패널과 아래 ID 행렬에 ���은 ID가 강조됩니다. 연결선은 선택된 reference와 joint tolerance를 만족한 P/S node를 나타냅니다. C 점, P 별, S 원은 선택 경로이며 물리 구조 분류가 아닙니다.</p></section><section id="references"><h2>Reference ID별 보존 상태</h2><p class="intro">열은 저장 reference 배열의 행 번호입니다. ID 순서는 물리적인 rim 경로 순서를 의미하지 않습니다. 채워진 칸은 해당 reference가 집합에 포함됨을 뜻합니다.</p><div class="reference-wrap"><canvas id="reference-matrix" role="img" aria-label="reference ID별 관측 후보 priority surface final 집합 포함 행렬"></canvas></div><div class="tile-legend"><span><i style="background:#dce4eb"></i>미포함</span><span><i style="background:var(--s2)"></i>S2 포함</span><span><i style="background:var(--s3)"></i>S3 포함</span><span><i style="background:var(--s0)"></i>관측 또는 S0 포함</span></div><div class="controls"><label for="reference-select">Reference ID <select id="reference-select"><option value="">선택 없음</option></select></label><button type="button" id="clear-reference">선택 해제</button><span class="small">좁은 화면에서는 ID 선택 목록을 사용할 수 있습니다.</span></div><div class="reference-detail"><div class="detail-copy" id="reference-info" aria-live="polite"></div><div class="table-scroll" id="reference-detail-table"></div></div><div class="comparison"><div><h3>Reference 집합 차이</h3><div class="table-scroll" id="difference-table"></div></div><div><h3>S2와 S3 직접 비교</h3><div class="table-scroll" id="comparison-table"></div><p class="note">각 행의 교집합과 차집합은 reference ID 기준입니다. 왼쪽 집합 차이 행들은 겹칠 수 있어 원인별 손실률처럼 합산할 수 없습니다.</p></div></div></section><section id="roi"><h2>Negative ROI의 경로별 점유</h2><p class="intro">ROI에 들어간 실제 node 수를 경로별 node 수로 나눕니다. 개별 ROI는 겹치고 known_negative_union은 논리 OR로 중복을 제거합니다. 일반 Surface node를 false selection이나 예산 낭비로 해석하지 않습니다.</p><div class="controls"><label>ROI <select id="roi-select"></select></label></div><div class="facets" id="roi-charts"></div><details open><summary>모든 ROI의 node count와 경로 대비 비율</summary><div class="table-scroll" id="roi-table"></div></details></section><section id="depth"><h2>Positive depth 분포와 선택 경로</h2><p class="intro">선분은 min–max, 원은 median, 삼각형은 p95입니다. 세 조건은 같은 축 범위를 사용합니다. 원거리 cutoff를 추가하거나 depth를 필터링하지 않았습니다.</p><div class="controls"><label>Depth 축 <select id="depth-scale"><option value="log">로그 축 · metre</option><option value="linear">선형 축 · metre</option></select></label></div><div class="legend"><span>┃ min / max</span><span>● median</span><span>▲ p95</span></div><div class="facets" id="depth-charts"></div><div class="table-scroll" id="depth-table"></div><h3 style="margin-top:28px">관측 X의 분위수 구간별 점유</h3><p class="intro" id="depth-bounds"></p><div class="legend"><span><i class="dot" style="background:#ccd8e3"></i>z ≤ X median</span><span><i class="dot" style="background:#7ca9c3"></i>X median < z ≤ X p95</span><span><i class="dot" style="background:#294e6d"></i>z > X p95</span></div><div class="facets" id="depth-band-charts"></div><p class="note">X 분위수는 해당 프레임의 관측 분포를 설명하는 경계이며 far point나 오류 판정 기준이 아닙니다. 구간 점유와 coverage의 상관만으로 FPS 거리 경쟁의 인과 효과를 확정할 수 없습니다.</p></section><section id="allocation"><h2>Peg와 Box의 node allocation</h2><p class="intro">물체별 실제 priority와 Surface 선택 node를 합쳐 256개 예산을 보여줍니다. 원본 frame metrics의 observed, budget, candidates, priority, surface_fps, selected를 연결했습니다.</p><div id="allocation-chart" class="allocation-chart"></div><div class="table-scroll" id="allocation-table"></div><p class="note">S0의 candidates count는 저장된 PCA5 진단 수치이며 General FPS의 후보 우선 선택을 의미하지 않습니다. S0의 후보 coverage는 N/A입니다.</p></section><section id="evidence"><h2>검증과 해석 범위</h2><div class="provenance"><div><h3>확인한 계약</h3><ul><li>저장 reference ID 순서, 모든 단계 node·matched node·unique reference 수 일치.</li><li>저장 selected XYZ와 원래 RGB-D raster geometry 정확히 일치.</li><li>동일 point/reference pair의 2px AND 3mm 조건.</li><li>원본 NPZ·JSON·RGB-D·mask hash 보존.</li><li>Phase 1 관련 테스트 31 PASS / 0 FAIL / 0 SKIP.</li></ul></div><div><h3>확인하지 않은 인과 원인</h3><p>후보에서 priority로 넘어갈 때의 reference 감소와 Surface 보완은 관측했습니다. 오염, 원거리 point, FPS 초기��·tie·거리 경쟁의 기여율은 미확인입니다.</p><p>시각화는 저장된 결과를 표시합니다. Sampler, 후보 추출, normal estimation, FPS trace, GPU, simulator를 실행하지 않았습니다.</p></div></div><div class="source-links"><a href="diagnostic.json">전체 진단 JSON</a><a href="visualizations_verification.json">시각화 검증</a><a href="verification.json">Phase 1 검증</a><a href="../../docs/visual-graph-integration/03d_box_rim_bottleneck_phase1.md">상세 보고서</a><a href="analysis.txt">분석 원문</a></div><noscript><p>이 HTML의 차트와 레이어 조회에는 JavaScript가 필요합니다. 위 JSON 또는 상세 보고서에서 수치를 확인할 수 있습니다.</p></noscript></section></main><footer class="wrap">로컬 자체 포함 HTML · 외부 리소스 요청 없음 · GT는 평가와 시각화에만 사용 · Phase 1 결과 보존</footer><div id="tooltip" class="tooltip" role="tooltip"></div><script type="application/json" id="data">/*__EMBEDDED_DATA__*/</script><script>'use strict';const DATA=JSON.parse(document.getElementById('data').textContent);const METHODS=['S0','S2','S3'];const COLORS={S0:'#64748b',S2:'#0b7e76',S3:'#a74c3b',C:'#8762e3',P:'#dc8800',S:'#0089bd',F:'#172f45',covered:'#16c785',missing:'#ff5778',lost:'#a7b0be'};const STAGES=['X','C','P','S','F'];const STAGE_NAMES={X:'관측',C:'후보',P:'Priority',S:'Surface',F:'최종'};const COV_KEYS={C:'candidate',P:'priority',S:'surface',F:'final_retention'};const DIFFS={V_minus_O:'V ∖ O',O_minus_C:'O ∖ R(C)',C_minus_P:'R(C) ∖ R(P)',C_minus_F:'R(C) ∖ R(F)',P_intersect_S:'R(P) ∩ R(S)',S_minus_P:'R(S) ∖ R(P)',S_minus_C:'R(S) ∖ R(C)',C_minus_P_intersect_S:'(R(C) ∖ R(P)) ∩ R(S)',O_minus_F:'O ∖ R(F)'};const ROI_LABELS={known_negative_union:'known_negative_union · 중복 제거 합집합',silhouette_2px:'silhouette_2px',occlusion_2px:'occlusion_2px',same_plane_tracker_cut_2px:'same_plane_tracker_cut_2px',invalid_depth_2px:'invalid_depth_2px',robot_occlusion_2px:'robot_occlusion_2px',contamination:'contamination',plane_interior:'plane_interior'};const $=id=>document.getElementById(id);const num=n=>n===null||n===undefined?'N/A':n.toLocaleString('en-US');const esc=s=>String(s).replaceAll('&','&').replaceAll('<','<').replaceAll('>','>').replaceAll('"','"');const pct=v=>v===null?'N/A':(100*v).toFixed(2)+'%';const frac=r=>r===null?'N/A':`${num(r.numerator)}/${num(r.denominator)} · ${pct(r.value)}`;const fnum=v=>v===null?'N/A':v.toFixed(6).replace(/0+$/,'').replace(/\.$/,'');const state={frame:0,reference:null,crop:'rim',roi:'known_negative_union',depth:'log'};const images={};let current,scene,geometries={},matrixGeometry;function table(headers,rows){return `<table><thead><tr>${headers.map(h=>`<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows.map(row=>`<tr>${row.map(c=>`<td>${c}</td>`).join('')}</tr>`).join('')}</tbody></table>`}function svg(content,w,h,label){return `<svg class="chart" viewBox="0 0 ${w} ${h}" role="img" aria-label="${esc(label)}"><title>${esc(label)}</title>${content}</svg>`}function text(x,y,value,anchor='start',extra=''){return `<text x="${x}" y="${y}" text-anchor="${anchor}" ${extra}>${esc(value)}</text>`}function methodHead(m){return `<h3 class="method ${m}"><i class="swatch"></i>${m} ${m==='S0'?'General FPS':m==='S2'?'FD 2px':'PCA 5×5'}</h3>`}function facets(id,draw){const target=$(id);target.innerHTML=METHODS.map(m=>`<div class="facet" id="${id}-${m}">${methodHead(m)}<div class="plot"></div></div>`).join('');for(const m of METHODS){const host=$(`${id}-${m}`).querySelector('.plot');host.innerHTML=draw(m,Math.max(270,host.clientWidth));}}function percentagePlot(m,w,values,labels,attribute='coverage'){ const left=67,right=118,top=18,rowHeight=36,h=top+values.length*rowHeight+46,pw=Math.max(70,w-left-right);let s=''; for(const t of [0,50,100]){const x=left+pw*t/100;s+=`<line x1="${x}" y1="8" x2="${x}" y2="${h-38}" stroke="#e0e7ee"/>`+text(x,h-19,t+'%','middle','class="muted"');} values.forEach((r,i)=>{const y=top+i*rowHeight;s+=text(0,y+14,labels[i]);if(r===null){s+=text(left,y+14,'N/A','start','class="muted"');return;}const len=r.value===null?0:pw*r.value;s+=`<rect x="${left}" y="${y}" width="${pw}" height="20" fill="#edf1f5"/><rect x="${left}" y="${y}" width="${len}" height="20" fill="${COLORS[m]}" data-chart="${attribute}" data-method="${m}" data-stage="${labels[i].split(' ')[0]}" data-numerator="${r.numerator}" data-denominator="${r.denominator}"/><g>${text(w-2,y+14,`${r.numerator}/${r.denominator} · ${r.value===null?'N/A':(r.value*100).toFixed(1)+'%'}`,'end')}</g>`;}); s+=text(left+pw/2,h-1,attribute==='coverage'?'reference / O (%)':'ROI nodes / 경로 nodes (%)','middle','class="muted"');return svg(s,w,h,m+' '+attribute);}function renderCoverage(){const c=current.conditions,obs=c.S2.coverage.observation; $('observation').innerHTML=`<strong>Frame ${state.frame}: 관측률 ${frac(obs)}</strong> · X ${num(c.S2.stages.X.node_count)} nodes 중 ${num(c.S2.stages.X.matched_node_count)}개가 가시 rim reference와 매칭됩니다.`; facets('coverage-charts',(m,w)=>percentagePlot(m,w,['C','P','S','F'].map(s=>c[m].coverage[COV_KEYS[s]]),['C 후보','P Priority','S Surface','F 최종'])); $('takeaway').innerHTML=state.frame===0?'<strong>S3의 후보 coverage는 더 높지만 priority에서 역전됩니다.</strong><br>S2: 후보 57 → Priority 13, Surface 보완 3 → 최종 16. S3: 후보 91 → Priority 3, Surface 보완 0 → 최종 3. 두 최종 reference 집합의 교집합은 0개입니다.':'<strong>41개 GT 중 관측 가능한 reference는 8개입니다.</strong><br>S2/S3 후보는 24/65 nodes여도 rim coverage는 모두 0/8입니다. S3의 최종 2개는 Surface 보완이며 S0는 3개를 남깁니다.'; const rows=[];for(const m of METHODS)for(const s of STAGES){const q=c[m].stages[s];rows.push([m,s+' '+STAGE_NAMES[s],q?num(q.node_count):'N/A',q?num(q.matched_node_count):'N/A',q?num(q.unique_reference_count):'N/A',frac(s==='X'?c[m].coverage.observation:c[m].coverage[COV_KEYS[s]])]);} $('stage-table').innerHTML=table(['조건','단계','실제 nodes','매칭 nodes','unique references','관측률 또는 retention'],rows);}function makeImages(){ $('image-panels').innerHTML=METHODS.map(m=>`<figure class="facet" style="margin:0"><div class="frame-head">${methodHead(m)}<button type="button" class="download" data-download="${m}" aria-label="${m} overlay PNG 저장">PNG 저장</button></div><div class="image-frame"><canvas id="overlay-${m}" role="img" aria-label="${m} 저장 source RGB와 후보 priority surface reference overlay"></canvas></div><figcaption class="image-caption" id="caption-${m}"></figcaption></figure>`).join(''); for(const m of METHODS){const canvas=$('overlay-'+m);canvas.addEventListener('pointermove',e=>overlayHover(e,m));canvas.addEventListener('pointerleave',hideTooltip);canvas.addEventListener('click',e=>overlaySelect(e,m));} document.querySelectorAll('[data-download]').forEach(button=>button.addEventListener('click',()=>{const m=button.dataset.download;const a=document.createElement('a');a.download=`task03d-f${String(state.frame).padStart(4,'0')}-${m}-overlay.png`;a.href=$('overlay-'+m).toDataURL();a.click();}));}function canvasContext(canvas,h){const w=canvas.clientWidth,dpr=window.devicePixelRatio||1;canvas.style.height=h+'px';canvas.width=Math.round(w*dpr);canvas.height=Math.round(h*dpr);const ctx=canvas.getContext('2d');ctx.setTransform(dpr,0,0,dpr,0,0);return {ctx,w,h};}function star(ctx,x,y,r){ctx.beginPath();for(let i=0;i<10;i++){const a=-Math.PI/2+i*Math.PI/5,rr=i%2?r*.42:r;const xx=x+Math.cos(a)*rr,yy=y+Math.sin(a)*rr;i?ctx.lineTo(xx,yy):ctx.moveTo(xx,yy);}ctx.closePath();}function renderImages(){if(!scene)return;geometries={};for(const m of METHODS){ const canvas=$('overlay-'+m),w=canvas.clientWidth,h=Math.max(260,Math.min(440,w*.96));const o=canvasContext(canvas,h),ctx=o.ctx; const crop=scene.crops[state.crop],cw=crop[2],ch=crop[3],scale=Math.min((w-44)/cw,(h-35)/ch),x0=22+(w-44-cw*scale)/2,y0=9+(h-35-ch*scale)/2; const point=(u,v)=>[x0+(u+.5-crop[0])*scale,y0+(v+.5-crop[1])*scale];const flatPoint=flat=>point(flat%scene.width,Math.floor(flat/scene.width)); geometries[m]={crop,scale,x0,y0,point};ctx.fillStyle='#112331';ctx.fillRect(0,0,w,h); const image=images[state.frame];if(image&&image.complete&&image.naturalWidth){ctx.drawImage(image,crop[0],crop[1],cw,ch,x0,y0,cw*scale,ch*scale);} ctx.save();ctx.beginPath();ctx.rect(x0,y0,cw*scale,ch*scale);ctx.clip();const nodes=scene.groups[m]; const dots=(flat,color,r,alpha)=>{ctx.fillStyle=color;ctx.globalAlpha=alpha;ctx.beginPath();for(const f of flat||[]){const [x,y]=flatPoint(f);if(x<x0||y<y0||x>x0+cw*scale||y>y0+ch*scale)continue;ctx.moveTo(x+r,y);ctx.arc(x,y,r,0,Math.PI*2);}ctx.fill();ctx.globalAlpha=1;}; if($('layer-X').checked)dots(nodes.X,'#d1dce4',.65,.3); if($('layer-M').checked)dots(scene.mask_outline,'#6aeb9a',.9,.85); if($('layer-C').checked)dots(nodes.C,COLORS.C,1.35,.6); if($('layer-S').checked){ctx.strokeStyle=COLORS.S;ctx.lineWidth=1.5;for(const f of nodes.S){const [x,y]=flatPoint(f);ctx.beginPath();ctx.arc(x,y,3.2,0,Math.PI*2);ctx.stroke();}} if($('layer-P').checked){ctx.fillStyle=COLORS.P;ctx.strokeStyle='#292512';ctx.lineWidth=.7;for(const f of nodes.P||[]){const [x,y]=flatPoint(f);star(ctx,x,y,6);ctx.fill();ctx.stroke();}} const refsets=current.conditions[m].reference_ids,oSet=new Set(refsets.O),fSet=new Set(refsets.F); if($('layer-R').checked){for(let i=0;i<scene.reference_uv.length;i++){const [x,y]=point(...scene.reference_uv[i]);ctx.strokeStyle=fSet.has(i)?COLORS.covered:oSet.has(i)?COLORS.missing:COLORS.lost;ctx.lineWidth=fSet.has(i)?2:1.2;const rr=fSet.has(i)?3.7:2.8;ctx.beginPath();ctx.moveTo(x-rr,y);ctx.lineTo(x+rr,y);ctx.moveTo(x,y-rr);ctx.lineTo(x,y+rr);ctx.stroke();}} if(state.reference!==null){const id=state.reference,[x,y]=point(...scene.reference_uv[id]);ctx.setLineDash([3,3]);ctx.lineWidth=1.2;for(const stage of ['P','S'])for(const f of scene.matched_nodes_by_reference[m][stage]?.[id]||[]){const [nx,ny]=flatPoint(f);ctx.strokeStyle=COLORS[stage];ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(nx,ny);ctx.stroke();ctx.beginPath();ctx.arc(nx,ny,6,0,Math.PI*2);ctx.stroke();}ctx.setLineDash([]);ctx.strokeStyle='#fff';ctx.lineWidth=2;ctx.beginPath();ctx.arc(x,y,8,0,Math.PI*2);ctx.stroke();ctx.fillStyle='#122a40';ctx.fillRect(x+10,y-19,44,19);ctx.fillStyle='#fff';ctx.font='11px sans-serif';ctx.fillText('#'+id,x+13,y-5);} ctx.restore();ctx.strokeStyle='#71889a';ctx.lineWidth=.7;ctx.strokeRect(x0,y0,cw*scale,ch*scale);ctx.fillStyle='#d1dee8';ctx.font='11px sans-serif';ctx.textAlign='left';ctx.fillText(String(crop[0]),x0,y0+ch*scale+15);ctx.textAlign='right';ctx.fillText(String(crop[0]+cw-1),x0+cw*scale,y0+ch*scale+15);ctx.textAlign='center';ctx.fillText('u (px)',x0+cw*scale/2,h-3);ctx.textAlign='left';ctx.fillText(String(crop[1]),2,y0+10);ctx.fillText(String(crop[1]+ch-1),2,y0+ch*scale);ctx.textAlign='left'; const row=current.conditions[m];$('caption-'+m).textContent=`P ${num(row.stages.P?.node_count??0)} · S ${row.stages.S.node_count} nodes / F ${row.stages.F.unique_reference_count}/${row.reference_ids.O.length} reference · crop (${crop[0]},${crop[1]}) ${cw}×${ch}px${m==='S0'?' · C/P N/A':''}`;}}function nearestRef(event,m){const g=geometries[m];if(!g)return null;const rect=event.currentTarget.getBoundingClientRect(),x=event.clientX-rect.left,y=event.clientY-rect.top;let best=null,dist=12;scene.reference_uv.forEach((uv,i)=>{const p=g.point(...uv),d=Math.hypot(p[0]-x,p[1]-y);if(d<dist){best=i;dist=d;}});return best;}function showTooltip(event,message){const el=$('tooltip');el.textContent=message;el.style.display='block';const r=el.getBoundingClientRect();el.style.left=Math.max(7,Math.min(innerWidth-r.width-8,event.clientX+14))+'px';el.style.top=Math.max(7,Math.min(innerHeight-r.height-8,event.clientY+14))+'px';}function hideTooltip(){$('tooltip').style.display='none';}function overlayHover(event,m){const id=nearestRef(event,m);if(id===null){hideTooltip();return;}const row=current.conditions[m];showTooltip(event,`${m} · Reference #${id}\n`+['C','P','S','F'].map(s=>`${s}: ${row.reference_ids[s]===null?'N/A':row.reference_ids[s].includes(id)?'포함':'미포함'}`).join(' · '));}function overlaySelect(event,m){const id=nearestRef(event,m);if(id!==null)selectReference(id);}function selectReference(id){state.reference=id;$('reference-select').value=id===null?'':String(id);renderReferenceDetail();renderMatrix();renderImages();}function matrixRows(){return [{label:'O 관측 가능',method:'S0',ids:current.conditions.S0.reference_ids.O,stage:'O'},...METHODS.flatMap(m=>(m==='S0'?['F']:['C','P','S','F']).map(s=>({label:`${m} ${s} ${STAGE_NAMES[s]}`,method:m,ids:current.conditions[m].reference_ids[s],stage:s})))];}function renderMatrix(){const rows=matrixRows(),canvas=$('reference-matrix'),left=105,top=30,rh=27,h=top+rows.length*rh+31;const {ctx,w}=canvasContext(canvas,h),n=scene.reference_uv.length,cw=(w-left-12)/n;ctx.clearRect(0,0,w,h);ctx.font='12px sans-serif';matrixGeometry={left,top,cw,rh,n};rows.forEach((row,j)=>{ctx.fillStyle='#33495d';ctx.textAlign='left';ctx.fillText(row.label,8,top+j*rh+16);const ids=new Set(row.ids);for(let i=0;i<n;i++){ctx.fillStyle=ids.has(i)?COLORS[row.method]:'#e5ebf0';ctx.fillRect(left+i*cw,top+j*rh+3,Math.max(.7,cw-1),18);}});const stride=n>60?20:10;ctx.fillStyle='#526579';ctx.textAlign='center';for(let i=0;i<n;i+=stride)if((n-1-i)*cw>27)ctx.fillText(String(i),left+(i+.5)*cw,17);ctx.fillText(String(n-1),w-14,17);ctx.fillText('저장 reference ID',left+(w-left-12)/2,h-5);if(state.reference!==null){ctx.strokeStyle='#172d41';ctx.lineWidth=1.7;ctx.strokeRect(left+state.reference*cw-.5,top,Math.max(cw,2),rows.length*rh);}}function renderReferenceDetail(){const id=state.reference;if(id===null){$('reference-info').innerHTML='RGB overlay 또는 행렬의 reference를 클릭하거나 위 목록에서 ID를 선택하세요. 좁은 화면에서는 목록으로 같은 정보를 조회할 수 있습니다.';$('reference-detail-table').innerHTML='';return;} const uv=scene.reference_uv[id],xyz=scene.reference_xyz[id],obs=current.conditions.S0.reference_ids.O.includes(id); $('reference-info').innerHTML=`<strong>Reference #${id}</strong> · ${obs?'관측 가능 O':'관측 손실 V ∖ O'}<br>UV (px): <code>${uv.map(v=>v.toFixed(4)).join(', ')}</code><br>CV XYZ (m): <code>${xyz.map(v=>v.toFixed(6)).join(', ')}</code><p class="note">각 셀의 숫자는 이 reference와 joint tolerance를 만족한 해당 경로의 실제 node 수입니다.</p>`; $('reference-detail-table').innerHTML=table(['조건','C','P','S','F'],METHODS.map(m=>[m,...['C','P','S','F'].map(s=>{const hits=scene.matched_nodes_by_reference[m][s];return hits===null?'<span class="na">N/A</span>':hits[id].length?`<span class="yes">포함 · ${hits[id].length}</span>`:'<span class="no">미포함 · 0</span>';})]));}function renderReferenceTables(){const conditions=current.conditions;$('difference-table').innerHTML=table(['reference 집합','S0','S2','S3'],Object.entries(DIFFS).map(([key,label])=>[esc(label),...METHODS.map(m=>num(conditions[m].differences[key]?.count))]));$('comparison-table').innerHTML=table(['집합','교집합','S2 only','S3 only'],['C','P','F'].map(s=>[`R(${s})`,...['intersection','S2_only','S3_only'].map(k=>num(current.S2_vs_S3[s][k].count))])); $('reference-select').innerHTML='<option value="">선택 없음</option>'+scene.reference_uv.map((uv,i)=>`<option value="${i}">#${i} · u ${uv[0].toFixed(1)}, v ${uv[1].toFixed(1)}</option>`).join('');$('reference-select').value=state.reference===null?'':String(state.reference);}function renderROI(){const name=state.roi;facets('roi-charts',(m,w)=>percentagePlot(m,w,STAGES.map(s=>current.conditions[m].negative_roi[name][s]?.fraction_of_path??null),STAGES.map(s=>s+' '+STAGE_NAMES[s]),'roi')); const rows=[];for(const [key,label] of Object.entries(ROI_LABELS))for(const m of METHODS){const roi=current.conditions[m].negative_roi[key];rows.push([esc(label.split(' · ')[0]),m,...STAGES.map(s=>roi[s]===null?'N/A':frac(roi[s].fraction_of_path))]);}$('roi-table').innerHTML=table(['ROI','조건','X','C','P','S','F'],rows);}function depthDomain(){const values=METHODS.flatMap(m=>Object.values(current.conditions[m].depth_m).filter(Boolean).flatMap(d=>[d.min,d.max]));return [Math.min(...values),Math.max(...values)];}function renderDepth(){const [lo,hi]=depthDomain(),log=state.depth==='log';facets('depth-charts',(m,w)=>{const left=58,right=20,pw=w-left-right,top=24,rh=w<400?57:42,h=top+rh*5+57;const a=log?Math.log10(lo):0,b=log?Math.log10(hi):hi,range=b-a,pad=range*.06;const x=z=>left+((log?Math.log10(z):z)-(a-pad))/(range+2*pad)*pw;let content='';let ticks=[];if(log){for(let e=Math.floor(Math.log10(lo));e<=Math.ceil(Math.log10(hi));e++)for(const k of [1,2,5]){const v=k*10**e;if(v>=lo&&v<=hi)ticks.push(v);}}else{ticks=Array.from({length:5},(_,i)=>hi*i/4);}if(ticks.length>5)ticks=ticks.filter((_,i)=>i%2===0);for(const v of ticks){content+=`<line x1="${x(v)}" y1="8" x2="${x(v)}" y2="${h-46}" stroke="#e0e7ee"/>`+text(x(v),h-25,v<1?v.toFixed(2):v.toFixed(v<5?1:0),'middle','class="muted"');} STAGES.forEach((s,i)=>{const d=current.conditions[m].depth_m[s],y=top+i*rh;content+=text(0,y+4,s);if(!d){content+=text(left,y+4,'N/A','start','class="muted"');return;}const color=COLORS[m];content+=`<g data-depth-method="${m}" data-depth-stage="${s}"><line x1="${x(d.min)}" y1="${y}" x2="${x(d.max)}" y2="${y}" stroke="${color}" stroke-width="2"/>`+`<path d="M${x(d.min)},${y-5}v10 M${x(d.max)},${y-5}v10" stroke="${color}"/><circle cx="${x(d.median)}" cy="${y}" r="4" fill="${color}"/><path d="M${x(d.p95)},${y-6}l-4,8h8z" fill="${color}"/>`+(w<400?text(left,y+18,`median ${fnum(d.median)} · p95 ${fnum(d.p95)}`,'start','class="muted"')+text(left,y+33,`max ${fnum(d.max)}m`,'start','class="muted"'):text(left,y+17,`median ${fnum(d.median)} · p95 ${fnum(d.p95)} · max ${fnum(d.max)}`,'start','class="muted"'))+'</g>';});content+=text(left+pw/2,h-3,`CV depth z (m) · ${log?'log₁₀':'linear'}`,'middle');return svg(content,w,h,m+' depth min median p95 max in metres');}); const rows=[];for(const m of METHODS)for(const s of STAGES){const d=current.conditions[m].depth_m[s];rows.push([m,s,...(d?[num(d.count),...['min','median','p95','max'].map(k=>fnum(d[k]))]:['N/A','N/A','N/A','N/A','N/A'])]);}$('depth-table').innerHTML=table(['조건','경로','nodes','min m','median m','p95 m','max m'],rows); const bounds=current.conditions.S2.depth_band_bounds_m;$('depth-bounds').textContent=`Frame ${state.frame}의 X median = ${fnum(bounds.median)}m, X p95 = ${fnum(bounds.p95)}m. 모든 조건·경로에 같은 경계를 적용합니다.`; facets('depth-band-charts',(m,w)=>{const left=28,right=10,pw=w-left-right,rh=43,h=5*rh+40;let content='';STAGES.forEach((s,i)=>{const d=current.conditions[m].depth_quantile_occupancy[s],y=12+i*rh;content+=text(0,y+14,s);if(d===null){content+=text(left,y+14,'N/A');return;}let x=left;const keys=['z_le_X_median','X_median_lt_z_le_X_p95','z_gt_X_p95'];const ns=keys.map(k=>d[k].numerator),den=d[keys[0]].denominator;keys.forEach((key,j)=>{const len=den?d[key].numerator/den*pw:0;content+=`<rect x="${x}" y="${y}" width="${len}" height="19" fill="${['#ccd8e3','#7ca9c3','#294e6d'][j]}"/>`;x+=len;});content+=text(left,y+34,`${ns.join(' / ')} nodes · >p95 ${den?(100*ns[2]/den).toFixed(1):'N/A'}%`,'start','class="muted"');});content+=text(left+pw/2,h-1,'경로 내 점유율 (0–100%)','middle');return svg(content,w,h,m+' observed depth quantile occupancy');});}function renderAllocation(){const host=$('allocation-chart'),w=host.clientWidth,left=42,pw=w-left-12,rh=w<600?78:58,h=METHODS.length*rh+45,colors=['#97a9b8','#d8e0e7','#edaa3e','#68b7d2'];let content='';METHODS.forEach((m,i)=>{const y=13+i*rh,a=current.conditions[m].allocation,values=[a.peg.priority,a.peg.surface_fps,a.box.priority,a.box.surface_fps];let x=left;content+=text(0,y+17,m);values.forEach((n,j)=>{const len=n/256*pw;content+=`<rect x="${x}" y="${y}" width="${len}" height="24" fill="${colors[j]}"/>`;if(len>40)content+=text(x+len/2,y+17,String(n),'middle');x+=len;});content+=w<600?text(left,y+44,`Peg ${a.peg.selected} = P ${a.peg.priority} + S ${a.peg.surface_fps}`,'start','class="muted"')+text(left,y+61,`Box ${a.box.selected} = P ${a.box.priority} + S ${a.box.surface_fps}`,'start','class="muted"'):text(left,y+44,`Peg ${a.peg.selected} = P ${a.peg.priority} + S ${a.peg.surface_fps} · Box ${a.box.selected} = P ${a.box.priority} + S ${a.box.surface_fps}`,'start','class="muted"');});content+=text(left+pw/2,h-1,'선택 node 수 / 전체 budget 256','middle');host.innerHTML=svg(content,w,h,'Peg Box priority Surface allocation')+`<div class="legend">${['Peg P','Peg S','Box P','Box S'].map((k,i)=>`<span><i class="dot" style="background:${colors[i]}"></i>${k}</span>`).join('')}</div>`; const rows=[];for(const m of METHODS)for(const obj of ['peg','box']){const a=current.conditions[m].allocation[obj];rows.push([m,obj,...['observed','budget','candidates','priority','surface_fps','selected'].map(k=>num(a[k]))]);}$('allocation-table').innerHTML=table(['조건','물체','observed','budget','candidates','priority','surface_fps','selected'],rows);}function render(){current=DATA.result.frames.find(f=>f.source_frame===state.frame);scene=DATA.scenes.find(s=>s.source_frame===state.frame);renderCoverage();renderReferenceTables();renderMatrix();renderReferenceDetail();renderROI();renderDepth();renderAllocation();renderImages();document.documentElement.dataset.frame=state.frame;}function initialize(){makeImages();$('roi-select').innerHTML=Object.entries(ROI_LABELS).map(([key,label])=>`<option value="${key}">${esc(label)}</option>`).join('');$('roi-select').value=state.roi; $('frame').addEventListener('change',event=>{state.frame=Number(event.target.value);state.reference=null;hideTooltip();render();});$('crop').addEventListener('change',event=>{state.crop=event.target.value;renderImages();});for(const layer of ['X','C','P','S','R','M'])$('layer-'+layer).addEventListener('change',renderImages); $('reference-select').addEventListener('change',event=>selectReference(event.target.value===''?null:Number(event.target.value)));$('clear-reference').addEventListener('click',()=>selectReference(null));$('roi-select').addEventListener('change',event=>{state.roi=event.target.value;renderROI();});$('depth-scale').addEventListener('change',event=>{state.depth=event.target.value;renderDepth();}); $('reference-matrix').addEventListener('click',event=>{const r=event.currentTarget.getBoundingClientRect(),g=matrixGeometry,x=event.clientX-r.left,y=event.clientY-r.top,id=Math.floor((x-g.left)/g.cw);if(id>=0&&id<g.n&&y>g.top&&y<g.top+matrixRows().length*g.rh)selectReference(id);}); $('reference-matrix').addEventListener('pointermove',event=>{const r=event.currentTarget.getBoundingClientRect(),g=matrixGeometry,x=event.clientX-r.left,y=event.clientY-r.top,id=Math.floor((x-g.left)/g.cw),row=matrixRows()[Math.floor((y-g.top)/g.rh)];if(id>=0&&id<g.n&&row)showTooltip(event,`Reference #${id} · ${row.label}\n${row.ids.includes(id)?'포함':'미포함'}`);else hideTooltip();});$('reference-matrix').addEventListener('pointerleave',hideTooltip); for(const s of DATA.scenes){const image=new Image();images[s.source_frame]=image;image.onload=()=>{if(state.frame===s.source_frame)renderImages();};image.src=s.image;} render();let timeout;new ResizeObserver(()=>{clearTimeout(timeout);timeout=setTimeout(render,90);}).observe(document.querySelector('main')); window.__rimViz={state,data:DATA,render,selectReference};}initialize();</script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217Task03-D — Box Hole Rim Bottleneck Analysis, Phase 1Run: d3f14ee494894daabb8ba2fab8e1b00c; source run: 2551448b0fae4c6bbce3caf48774275fCPU / saved ep000 / frames 0 and 120 / S0, S2, S3 only.
결론: Frame 0의 S3는 후보 reference coverage가 S2보다 높지만(91 vs 57), priority 선택 후에는 3 vs 13으로 역전된다.S2 Surface는 후보 밖 reference 3개를 보완하여 최종 16개, S3 Surface는 0개를 보완하여 최종 3개다.관측 손실은 frame 0에서 0개다. Frame 120은 관측 손실 33개와 후보 rim coverage 0/8을 구분해야 한다.이는 손실이 나타나는 단계를 확인한 결과다. 오염 또는 FPS 거리 경쟁의 인과 기여율은 이 자료로 확정하지 않는다.
정의와 구현R(A): 동일 물체의 동일 point/reference pair가 2D <=2px AND 3D <=3mm를 동시에 만족하는 unique saved reference ID 집합.ID는 저장 evaluation/box/reference_uv 및 reference_xyz의 행 번호다. 한 node의 다중 reference hit와 다중 node의 동일 reference hit를 구분했다.관측 분모는 V, 후보/priority/surface/final retention 분모는 O다. 분모 0은 null(N/A)이며 raw 분자/분모를 보존한다.S0는 General FPS 대조이며 C/P와 관련 집합 차이는 N/A다. 저장된 candidate 진단 count는 allocation 표에서만 별도 표시한다.기존 run_sampling.py를 수정하지 않고 독립 run_rim_bottleneck.py를 추가했다. 전체 sweep의 기본 동작과 입력 요구사항에 영향이 없기 때문이다.sampling_evaluation.py:47 reference_hits, :100 count_ratio, :106 staged_reference_coverage를 추가했다.기존 CoverageMatcher.__init__/score, evaluation_context(), Task02 rim_reference()와 평가 상수는 원본 AST와 같다.run_rim_bottleneck.py:47 source_contract, :84 geometry_evidence, :97 validate_saved_selection, :176 diagnose_frame, :257 diagnose.geometry_evidence는 기존 RGB-D adapter와 build_organized_geometry 및 ROI에 필요한 object_mask/validity boundary만 사용한다.normal estimation, feature extraction, candidate extraction, sampler, 별도 FPS를 실제 진단에서 호출하지 않는다.착수 시 유일한 원본 source byte 차이였던 edge_evidence.py는 끝의 빈 줄 제거뿐이며 AST가 같다.변경 파일: sampling_evaluation.py(+74), run_rim_bottleneck.py(신규 342줄), test_sampling_evaluation.py(+135/-1; 신규 테스트 8개).production sampling.py/estimator/FPS, allocation, 기존 runner는 변경하지 않았다.
Frame 0 — Box 단계별 집계method | stage | actual nodes | matched nodes | unique references | coverageS0 | X | 11665 | 153 | 103 | 103/103 (100.00%)S0 | C | N/A | N/A | N/A | N/AS0 | P | N/A | N/A | N/A | N/AS0 | S | 127 | 2 | 6 | 6/103 (5.83%)S0 | F | 127 | 2 | 6 | 6/103 (5.83%)S2 | X | 11665 | 153 | 103 | 103/103 (100.00%)S2 | C | 297 | 101 | 57 | 57/103 (55.34%)S2 | P | 32 | 4 | 13 | 13/103 (12.62%)S2 | S | 95 | 1 | 3 | 3/103 (2.91%)S2 | F | 127 | 5 | 16 | 16/103 (15.53%)S3 | X | 11665 | 153 | 103 | 103/103 (100.00%)S3 | C | 599 | 127 | 91 | 91/103 (88.35%)S3 | P | 32 | 1 | 3 | 3/103 (2.91%)S3 | S | 95 | 0 | 0 | 0/103 (0.00%)S3 | F | 127 | 1 | 3 | 3/103 (2.91%)
집합 차이 — reference 수. 서로 겹치는 행을 원인별 손실률로 합산하지 않는다.expression | S0 | S2 | S3V_minus_O | 0 | 0 | 0O_minus_C | N/A | 46 | 12C_minus_P | N/A | 44 | 88C_minus_F | N/A | 44 | 88P_intersect_S | N/A | 0 | 0S_minus_P | N/A | 3 | 0S_minus_C | N/A | 3 | 0C_minus_P_intersect_S | N/A | 0 | 0O_minus_F | 97 | 87 | 100
S2/S3 직접 비교: stage | intersection | S2 only | S3 onlyC | 56 | 1 | 35P | 0 | 13 | 3F | 0 | 16 | 3
Allocation: method | object | observed | budget | candidates(saved diagnostic for S0) | priority | surface_fps | selectedS0 | box | 11665 | 127 | 599 | 0 | 127 | 127S0 | peg | 11780 | 129 | 703 | 0 | 129 | 129S2 | box | 11665 | 127 | 297 | 32 | 95 | 127S2 | peg | 11780 | 129 | 870 | 32 | 97 | 129S3 | box | 11665 | 127 | 599 | 32 | 95 | 127S3 | peg | 11780 | 129 | 703 | 32 | 97 | 129
Negative ROI node counts: ROI | X | S0 S/F | S2 C/P/S/F | S3 C/P/S/Fsilhouette_2px | 1164 | 19 | 0/0/15/15 | 2/1/17/18occlusion_2px | 510 | 5 | 0/0/6/6 | 94/5/3/8same_plane_tracker_cut_2px | 96 | 5 | 0/0/4/4 | 5/1/2/3invalid_depth_2px | 296 | 6 | 0/0/2/2 | 0/0/5/5robot_occlusion_2px | 510 | 5 | 0/0/6/6 | 94/5/3/8contamination | 482 | 21 | 59/3/15/18 | 186/4/16/20plane_interior | 8387 | 38 | 0/0/25/25 | 0/0/35/35known_negative_union | 10506 | 82 | 59/3/61/64 | 281/9/70/79개별 ROI는 겹친다. known_negative_union은 논리 OR로 중복을 제거하여 한 번만 센다.known_negative_union: method | C/path | P/path | S/path | F/pathS0 | N/A | N/A | 82/127 (64.57%) | 82/127 (64.57%)S2 | 59/297 (19.87%) | 3/32 (9.38%) | 61/95 (64.21%) | 64/127 (50.39%)S3 | 281/599 (46.91%) | 9/32 (28.12%) | 70/95 (73.68%) | 79/127 (62.20%)ROI별 path 비율과 관측 ROI 대비 비율의 raw 분자/분모는 diagnostic.json에 모두 ���장했다.일반 Surface node가 평면/negative ROI에 있다는 사실을 false selection이나 예산 낭비로 해석하지 않는다.
Positive finite depth (CV-camera z, metres): method | path | count | min | median | p95 | max | count z > X p95 / pathS0 | X | 11665 | 0.295000 | 0.496000 | 0.535000 | 30.726000 | 562/11665 (4.82%)S0 | S | 127 | 0.296000 | 0.524000 | 8.431000 | 30.726000 | 57/127 (44.88%)S0 | F | 127 | 0.296000 | 0.524000 | 8.431000 | 30.726000 | 57/127 (44.88%)S2 | X | 11665 | 0.295000 | 0.496000 | 0.535000 | 30.726000 | 562/11665 (4.82%)S2 | C | 297 | 0.303000 | 0.500000 | 0.632000 | 0.690000 | 47/297 (15.82%)S2 | P | 32 | 0.303000 | 0.506000 | 0.665300 | 0.690000 | 12/32 (37.50%)S2 | S | 95 | 0.296000 | 0.533000 | 8.431000 | 30.726000 | 47/95 (49.47%)S2 | F | 127 | 0.296000 | 0.529000 | 8.431000 | 30.726000 | 59/127 (46.46%)S3 | X | 11665 | 0.295000 | 0.496000 | 0.535000 | 30.726000 | 562/11665 (4.82%)S3 | C | 599 | 0.295000 | 0.488000 | 0.666500 | 1.426000 | 80/599 (13.36%)S3 | P | 32 | 0.306000 | 0.580500 | 1.405650 | 1.426000 | 20/32 (62.50%)S3 | S | 95 | 0.296000 | 0.522000 | 8.431000 | 30.726000 | 40/95 (42.11%)S3 | F | 127 | 0.296000 | 0.525000 | 8.431000 | 30.726000 | 60/127 (47.24%)X의 median/p95에서 나눈 세 구간은 분포 설명용이며 임의 far cutoff, filter 또는 오류 label이 아니다. 전체 구간별 점유는 JSON에 있다.
Frame 120 — Box 단계별 집계method | stage | actual nodes | matched nodes | unique references | coverageS0 | X | 5618 | 11 | 8 | 8/41 (19.51%)S0 | C | N/A | N/A | N/A | N/AS0 | P | N/A | N/A | N/A | N/AS0 | S | 197 | 1 | 3 | 3/8 (37.50%)S0 | F | 197 | 1 | 3 | 3/8 (37.50%)S2 | X | 5618 | 11 | 8 | 8/41 (19.51%)S2 | C | 24 | 0 | 0 | 0/8 (0.00%)S2 | P | 24 | 0 | 0 | 0/8 (0.00%)S2 | S | 173 | 0 | 0 | 0/8 (0.00%)S2 | F | 197 | 0 | 0 | 0/8 (0.00%)S3 | X | 5618 | 11 | 8 | 8/41 (19.51%)S3 | C | 65 | 0 | 0 | 0/8 (0.00%)S3 | P | 49 | 0 | 0 | 0/8 (0.00%)S3 | S | 148 | 1 | 2 | 2/8 (25.00%)S3 | F | 197 | 1 | 2 | 2/8 (25.00%)
집합 차이 — reference 수. 서로 겹치는 행을 원인별 손실률로 합산하지 않는다.expression | S0 | S2 | S3V_minus_O | 33 | 33 | 33O_minus_C | N/A | 8 | 8C_minus_P | N/A | 0 | 0C_minus_F | N/A | 0 | 0P_intersect_S | N/A | 0 | 0S_minus_P | N/A | 0 | 2S_minus_C | N/A | 0 | 2C_minus_P_intersect_S | N/A | 0 | 0O_minus_F | 5 | 8 | 6
S2/S3 직접 비교: stage | intersection | S2 only | S3 onlyC | 0 | 0 | 0P | 0 | 0 | 0F | 0 | 0 | 2
Allocation: method | object | observed | budget | candidates(saved diagnostic for S0) | priority | surface_fps | selectedS0 | box | 5618 | 197 | 65 | 0 | 197 | 197S0 | peg | 1353 | 59 | 247 | 0 | 59 | 59S2 | box | 5618 | 197 | 24 | 24 | 173 | 197S2 | peg | 1353 | 59 | 206 | 40 | 19 | 59S3 | box | 5618 | 197 | 65 | 49 | 148 | 197S3 | peg | 1353 | 59 | 247 | 15 | 44 | 59
Negative ROI node counts: ROI | X | S0 S/F | S2 C/P/S/F | S3 C/P/S/Fsilhouette_2px | 689 | 28 | 24/24/25/49 | 33/29/20/49occlusion_2px | 445 | 21 | 0/0/23/23 | 8/4/21/25same_plane_tracker_cut_2px | 177 | 12 | 0/0/11/11 | 0/0/10/10invalid_depth_2px | 0 | 0 | 0/0/0/0 | 0/0/0/0robot_occlusion_2px | 315 | 14 | 0/0/17/17 | 8/4/14/18contamination | 105 | 32 | 0/0/29/29 | 21/14/23/37plane_interior | 4325 | 113 | 0/0/94/94 | 0/0/83/83known_negative_union | 5556 | 193 | 24/24/170/194 | 62/47/146/193개별 ROI는 겹친다. known_negative_union은 논리 OR로 중복을 제거하여 한 번만 센다.known_negative_union: method | C/path | P/path | S/path | F/pathS0 | N/A | N/A | 193/197 (97.97%) | 193/197 (97.97%)S2 | 24/24 (100.00%) | 24/24 (100.00%) | 170/173 (98.27%) | 194/197 (98.48%)S3 | 62/65 (95.38%) | 47/49 (95.92%) | 146/148 (98.65%) | 193/197 (97.97%)ROI별 path 비율과 관측 ROI 대비 비율의 raw 분자/분모는 diagnostic.json에 모두 저장했다.일반 Surface node가 평면/negative ROI에 있다는 사실을 false selection이나 예산 낭비로 해석하지 않는다.
Positive finite depth (CV-camera z, metres): method | path | count | min | median | p95 | max | count z > X p95 / pathS0 | X | 5618 | 0.413000 | 0.511000 | 0.531000 | 1.177000 | 276/5618 (4.91%)S0 | S | 197 | 0.413000 | 0.512000 | 0.761000 | 1.177000 | 30/197 (15.23%)S0 | F | 197 | 0.413000 | 0.512000 | 0.761000 | 1.177000 | 30/197 (15.23%)S2 | X | 5618 | 0.413000 | 0.511000 | 0.531000 | 1.177000 | 276/5618 (4.91%)S2 | C | 24 | 0.530000 | 0.537000 | 0.538000 | 0.538000 | 17/24 (70.83%)S2 | P | 24 | 0.530000 | 0.537000 | 0.538000 | 0.538000 | 17/24 (70.83%)S2 | S | 173 | 0.413000 | 0.513000 | 0.765400 | 1.177000 | 24/173 (13.87%)S2 | F | 197 | 0.413000 | 0.516000 | 0.761000 | 1.177000 | 41/197 (20.81%)S3 | X | 5618 | 0.413000 | 0.511000 | 0.531000 | 1.177000 | 276/5618 (4.91%)S3 | C | 65 | 0.426000 | 0.533000 | 0.539000 | 0.569000 | 38/65 (58.46%)S3 | P | 49 | 0.426000 | 0.535000 | 0.539000 | 0.569000 | 34/49 (69.39%)S3 | S | 148 | 0.413000 | 0.513000 | 0.786950 | 1.177000 | 21/148 (14.19%)S3 | F | 197 | 0.413000 | 0.517000 | 0.753000 | 1.177000 | 55/197 (27.92%)X의 median/p95에서 나눈 세 구간은 분포 설명용이며 임의 far cutoff, filter 또는 오류 label이 아니다. 전체 구간별 점유는 JSON에 있다.
해석과 한계Frame 0: O=103/103이므로 관측 단계 손실은 없다. S3 후보 599개가 91 reference를 덮고 S2 후보 297개가 57개를 덮는다.후보 개수가 충분한 것과 rim reference를 덮는 것은 다르다. S3의 더 낮은 최종 coverage를 후보 reference coverage 부족으로 설명할 수 없다.C에서 P로 가며 S3는 88개, S2는 44개 reference가 남지 않았다. Surface가 이 C 손실을 회복한 수는 양쪽 모두 0개다.S2 Surface는 R(C) 밖의 3개를 추가했고, S3 Surface는 reference를 추가하지 않았다. P/S reference overlap은 양쪽 0개다.S2/S3 최종 reference 교집합은 0개다. 따라서 16 vs 3은 동일 13개 ID만의 증감으로 해석할 수 없다.Frame 0 Peg/Box 예산은 129/127, priority는 S2/S3 모두 32/32다. 후보 크기의 차이와 실제 allocation 차이를 혼동하지 않는다.Frame 120: V=41, O=8. 후보 C는 S2 24개, S3 65개이나 양쪽 rim coverage는 0/8이다.S2 Box는 후보 24개 전부 priority이며 rim은 0개다. S3는 priority 49개에서 0개, Surface 148개 중 1 node가 후보 밖 2 reference를 덮는다.S0는 197개 중 1 node가 3 reference를 덮는다. S0/S2/S3 retention은 37.50%/0%/25%, GT coverage는 7.32%/0%/4.88%다.Frame 120 Peg/Box priority는 S2 40/24, S3 15/49다. 기존 sampler는 object budget 가중치와 후보 capacity로 전역 64개 priority를 배분한다.이는 저장 count 및 변경하지 않은 source를 확인한 설명이며 allocation을 재실행하지 않았다.Frame 0의 contamination priority는 S2 3개, S3 4개; known_negative_union priority는 3/32와 9/32다.S3 priority median/p95/max depth는 0.5805/1.40565/1.426m, S2는 0.506/0.6653/0.690m다.X 최대 30.726m의 유효 positive depth는 두 조건 모두 Surface 경로에 남았다. 두 Surface의 p95/max는 8.431/30.726m다.ROI 점유와 depth 분포의 차이는 관측 사실이다. 그 차이가 rim 손실에 기여한 비율, 거리 경쟁/초기점/tie/priority seeding의 영향은 미확인이다.특히 S3 priority의 후보 밖 원거리 극단치 때문에 실패했다고 단정할 수 없다. C/P와 Surface의 depth 범위는 다르다.
FPS trace 판단Phase 1의 손실 단계 구분에는 FPS trace가 필요하지 않다. 관측/후보/priority/Surface 차이는 saved sets로 확인했다.다음 질문이 왜 91개 후보 reference 중 priority가 3개만 남기는가라면 추가 trace가 유용하다. 아직 실행하거나 변경하지 않았다.별도 승인 시 최소 범위: frame 0 Box S2/S3 기본 조건만, 기존 선택 결과를 바꾸지 않는 priority 순서·source flat ID·현재 min-distance²·argmax/tie·rim hit 여부 기록.선택된 극단 depth 점/초기점과 미선택 rim 후보의 거리 상태를 비교한다. Surface 보완 3 vs 0을 설명해야 할 때만 같은 두 조건의 Surface 초기 상태와 선택 순서를 추가한다.trace만으로 filtering/allocation 변경의 인과 효과를 확정하지 않는다. GT는 사후 hit annotation에만 사용한다.
검증과 보존WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03d-mpl .venv/bin/python -m unittest visual.runtime.test.test_sampling_evaluation visual.runtime.test.test_sampling visual.runtime.test.test_sampling_geometry -v결과: 31 tests, PASS 31 / FAIL 0 / SKIP 0 (신규 8개). 테스트의 sampler 실행은 synthetic fixture에 한정한다.같은 pair의 2px AND 3mm(다른 두 node가 각 조건을 만족하는 반례 포함), 다중 reference hit/중복 제거, P/S union/overlap, Surface 후보 밖 보완, 빈 집합/분모0을 확인했다.source row/raster/pixel centre/invalid/overlap/XYZ 일치 및 손상된 source/geometry 거부, historical 평가 정의 변경 시 실패도 검증했다.WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03d-mpl .venv/bin/python -m visual.runtime.test.run_rim_bottleneck결과: PASS. Source frame 0/120만 진단. 저장 reference 좌표와 순서 bit-exact; selected XYZ exact equality (오차0), 객체 소속 및 모든 Peg/Box allocation counter 일치.C⊆X, P⊆C, F⊆X, R(C)⊆O, R(F)⊆O, R(F)=R(P)∪R(S)를 reference ID 수준에서 확인했다.기존 frame-level 모든 tolerance(1px/2mm, 2px/3mm, 3px/5mm)의 coverage 및 기존 negative ROI count가 정확히 일치한다. 새 tolerance sweep을 수행한 것은 아니다.필수 재현 target: frame 0 103/103 및 S0/S2/S3=6/16/3; frame 120 41/8 및 3/0/2 — 전부 일치.git diff --check: PASS. 원본 NPZ/JSON, episode, masks, tracking/segmentation map의 실행 전후 SHA256 동일.첫 검증 UUID 847985ac6e004b55967b080906c166d3는 보존했다. 2-node 반례 테스트를 기본 2px/3mm로 명시한 후 현재 UUID에서 재검증했다. 진단 결과는 동일하다.ExperimentLogger와 experiment_artifacts.digests/register_existing_output의 UUID, local metrics, manifest, sidecar 계약을 재사용했다. W&B disabled. 외부 업로드 없음.원본 input에는 새 sidecar를 쓰지 않았고 source_run_id 및 input hashes로 연결했다. 현재 git_dirty=true 및 실행 source snapshot을 보존했다.GPU/CUDA/MPS, simulator backend, tracking, 실제 ep000 sampler 재실행, FPS trace, filtering/threshold/allocation ablation, PCL, Graph/BC 학습은 NOT RUN.설치/commit/외부 게시 없음. Phase 1 결과 제출 후 중단한다.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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Render the completed Task03-D result; no experiment, sampler or FPS rerun.
From repository root: .venv/bin/python experiments/d3f14ee494894daabb8ba2fab8e1b00c/build_visualizations.py"""import base64from io import BytesIOimport jsonfrom pathlib import Pathimport sys
import numpy as npfrom PIL import Image
HERE = Path(__file__).resolve().parentREPO = HERE.parents[1]sys.path.insert(0, str(REPO))from utils.experiment_artifacts import digests, register_existing_outputfrom visual.runtime.geometry import build_organized_geometryfrom visual.runtime.rgbd import BOX, attach_rgbdfrom visual.runtime.test.sampling_evaluation import CoverageMatcher
def png_url(rgb): buffer = BytesIO() Image.fromarray(rgb).save(buffer, format='PNG') return 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode('ascii')
def extent(uv, shape, padding): if not len(uv): return [0, 0, shape[1], shape[0]] left, top = np.floor(uv.min(axis=0)-padding).astype(int) right, bottom = np.ceil(uv.max(axis=0)+padding+1).astype(int) left, top = max(0, left), max(0, top) right, bottom = min(shape[1], right), min(shape[0], bottom) return [int(left), int(top), int(right-left), int(bottom-top)]
def main(): result_path = HERE/'diagnostic.json' result = json.loads(result_path.read_text()) config = result['config'] original = Path(config['source_directory']) comparison = json.loads((original/'comparison.json').read_text())['config'] episode, masks = Path(comparison['input']), Path(comparison['masks']) tracked = [result_path, HERE/'verification.json', HERE/'analysis.txt', *map(Path, config['input_sha256'])] before = {str(p): digests(p)[1] for p in tracked} for path, expected in config['input_sha256'].items(): if before[path] != expected: raise ValueError('historical diagnostic input changed: '+path) scenes = [] with np.load(episode, allow_pickle=False) as ep, np.load(masks, allow_pickle=False) as masks_npz: source_rows = masks_npz['source_frame'] requested = [row['source_frame'] for row in result['frames']] rows = [int(np.flatnonzero(source_rows == s).item()) for s in requested] peg, box = masks_npz['peg'], masks_npz['box'] tracking = ((i, {1: peg[row], 2: box[row]}) for i, row in enumerate(rows)) frames = attach_rgbd(tracking, ep, camera=comparison['camera'], source_frames=source_rows[rows]) for frame, report in zip(frames, result['frames']): assert frame.source_frame == report['source_frame'] geometry = build_organized_geometry(frame) with np.load(original/f'f{frame.source_frame:04d}_samples.npz', allow_pickle=False) as saved: assert int(saved['source_frame']) == frame.source_frame refs = tuple(saved['evaluation/box/reference_'+suffix] for suffix in ('uv', 'xyz')) matcher = CoverageMatcher(geometry, BOX, refs) adjacency = matcher.adjacencies['2px_3mm'] groups, per_ref = {}, {} for method, row in report['conditions'].items(): condition = row['condition'] belongs = saved[condition+'/object_id'] == BOX final = saved[condition+'/flat_index'][belongs] role = saved[condition+'/priority_selected'][belongs] np.testing.assert_array_equal(saved[condition+'/points'][belongs], geometry.xyz.reshape(-1, 3)[final]) candidate = None if method == 'S0' else saved[ f'evidence/{"fd2" if method == "S2" else "pca5"}/1/20/orientation_flat'] nodes = dict(X=matcher.flat, C=candidate, P=final[role] if candidate is not None else None, S=final[~role], F=final) groups[method] = {s: flat.tolist() if flat is not None else None for s, flat in nodes.items()} per_ref[method] = {} for stage, flat in nodes.items(): if flat is None: per_ref[method][stage] = None continue hits, matched = matcher.reference_hits(flat) assert hits.tolist() == row['reference_ids'][stage] expected = row['stages'][stage] assert (len(flat), len(matched), len(hits)) == tuple(expected[k] for k in ('node_count', 'matched_node_count', 'unique_reference_count')) subset = adjacency[np.searchsorted(matcher.flat, flat)].tocsc() per_ref[method][stage] = [flat[subset.indices[subset.indptr[i]:subset.indptr[i+1]]].tolist() for i in range(matcher.nref)] raw_mask = geometry.object_masks[BOX] padded = np.pad(raw_mask, 1) interior = (padded[1:-1, :-2] & padded[1:-1, 2:] & padded[:-2, 1:-1] & padded[2:, 1:-1]) outline = np.flatnonzero(raw_mask & ~interior) all_vu = np.column_stack(np.nonzero(raw_mask)) scenes.append(dict(source_frame=frame.source_frame, image=png_url(frame.rgb), width=frame.depth.shape[1], height=frame.depth.shape[0], reference_uv=refs[0].tolist(), reference_xyz=refs[1].tolist(), groups=groups, matched_nodes_by_reference=per_ref, mask_outline=outline.tolist(), crops=dict(rim=extent(refs[0], frame.depth.shape, 16), box=extent(all_vu[:, ::-1], frame.depth.shape, 10), full=[0, 0, frame.depth.shape[1], frame.depth.shape[0]]))) after = {str(p): digests(p)[1] for p in tracked} assert after == before payload = dict(result=result, scenes=scenes) encoded = json.dumps(payload, ensure_ascii=False, separators=(',', ':'), allow_nan=False).replace('</', '<\\/') template = (HERE/'visualizations_template.html').read_text() assert template.count('/*__EMBEDDED_DATA__*/') == 1 output = HERE/'visualizations.html' output.write_text(template.replace('/*__EMBEDDED_DATA__*/', encoded), encoding='utf-8') checks = dict(run_id=result['run_id'], source_run_id=result['source_run_id'], renderer='build_visualizations.py', frames=[s['source_frame'] for s in scenes], geometry_and_saved_reference_ids_exact=True, all_stage_node_counts_exact=True, all_stage_matched_node_counts_exact=True, original_inputs_unchanged=True, input_sha256=before, sampler_executed=False, fps_executed=False, normal_estimation_executed=False, external_dependencies=[], display_coordinates='source raster UV + 0.5 onto original RGB pixel centres', html_sha256=digests(output)[1], html_bytes=output.stat().st_size) check_path = HERE/'visualizations_verification.json' check_path.write_text(json.dumps(checks, indent=2, ensure_ascii=False)+'\n') for path, kind in [(output, 'reports'), (Path(__file__), 'reports'), (HERE/'visualizations_template.html', 'reports'), (check_path, 'metrics')]: register_existing_output(HERE, path, kind=kind) print(output) print(f'PASS: exact saved reference sets / node counts / XYZ; preserved {len(before)} inputs')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247"""Task03 denominator / joint-tolerance / visible-only rim evaluation contracts."""from dataclasses import replaceimport jsonimport osfrom pathlib import Pathimport tempfileimport unittestfrom unittest.mock import patchimport numpy as np
from visual.runtime.geometry import build_organized_geometryfrom visual.runtime.rgbd import PEG, BOXfrom visual.runtime.sampling import extract_sampling_evidence, sample_points, SamplingConfigfrom visual.runtime.test.normal_diagnostics import synthetic_frame, oracle, box_primitives, rim_regionfrom visual.runtime.test.run_structural_edges import rim_referencefrom visual.runtime.test.sampling_evaluation import CoverageMatcher, staged_reference_coveragefrom visual.runtime.test.run_rim_bottleneck import ( geometry_evidence, validate_saved_selection, occupancy, source_contract,)from visual.runtime.test.run_sampling import conditions, evaluate
class SamplingEvaluationTests(unittest.TestCase): def test_tracking_and_sampling_losses_have_separate_denominators(self): k=np.array([[100.,0,8],[0,100.,8],[0,0,1]]) mask=np.zeros((16,16),bool);mask[5,5]=True;mask[5,6]=True frame=synthetic_frame(np.full((16,16),.3,np.float32),k,mask) g=build_organized_geometry(frame) uv=np.array([[5,5],[6,5],[12,12]],float) xyz=g.xyz[uv[:,1].astype(int),uv[:,0].astype(int)] matcher=CoverageMatcher(g,PEG,(uv,xyz),((.1,.0001),)) row,_=matcher.score(np.array([5*16+5])) r=row['tolerance']['0.1px_0.1mm'] self.assertEqual((r['gt_visible'],r['tracker_observed'],r['sampled']),(3,2,1)) self.assertEqual(r['gt_coverage'],1/3);self.assertEqual(r['sampling_retention'],.5) row,arrays=matcher.score(np.array([],np.int64)) self.assertEqual(row['tolerance']['0.1px_0.1mm']['sampled'],0) self.assertEqual(row['missing_reference_distances'],3) self.assertEqual(len(arrays['gt_to_sample_mm']),0)
def test_joint_tolerance_requires_same_pair(self): k=np.array([[100.,0,8],[0,100.,8],[0,0,1]]) mask=np.zeros((16,16),bool);mask[5,5]=True g=build_organized_geometry(synthetic_frame(np.full((16,16),.3,np.float32),k,mask)) # One reference is near only in image; the other only in 3D. refs=(np.array([[5.,5.],[12.,12.]]),np.array([g.xyz[5,5]+[0,0,.1],g.xyz[5,5]])) row,_=CoverageMatcher(g,PEG,refs).score(np.array([85])) self.assertEqual(row['tolerance']['2px_3mm']['sampled'],0)
def test_hole_reference_only_observed_entrance_not_hidden_projection(self): k=np.array([[100.,0,64],[0,100.,64],[0,0,1]]) pose=np.array([0.,0,.5,np.sqrt(.5),0,np.sqrt(.5),0]) frame=synthetic_frame(np.full((128,128),.4,np.float32),k,np.ones((128,128),bool)) truth=oracle(frame,pose,box_primitives(.1,.025,np.zeros(2))) visible=np.isfinite(truth['depth']) rim,_=rim_region(frame,truth,visible,pose,.1,.025,np.zeros(2)) gt={'box_pose':pose[None], 'box_hole_pose':pose[None], 'box_hole_radii':np.array(.025),'peg_half_sizes':np.array([.1,.02,.02])} ref=rim_reference(frame,gt,truth,rim) self.assertGreater(len(ref[0]),0) hidden=rim_reference(frame,gt,truth,np.zeros_like(rim)) self.assertEqual(len(hidden[0]),0) # Hide half the actual entrance for evaluation and omit it from tracker support. partial=rim.copy();partial[:64]=False ref=rim_reference(frame,gt,truth,partial) self.assertTrue((ref[0][:,1]>=62.5).all()) depth=np.where(visible,truth['depth'],0).astype(np.float32) frame=replace(frame,depth=depth,masks={BOX:visible & (np.indices(visible.shape)[0]>=64)}) e=extract_sampling_evidence(frame) a=sample_points(e,SamplingConfig(num_points=64),method='S4') self.assertTrue((a.pixels_vu[:,0]>=64).all()) self.assertTrue(visible[tuple(a.pixels_vu.T)].all())
def test_empty_reference_is_undefined_not_perfect(self): k=np.eye(3);frame=synthetic_frame(np.ones((8,8),np.float32),k,np.ones((8,8),bool)) matcher=CoverageMatcher(build_organized_geometry(frame),PEG,(np.empty((0,2)),np.empty((0,3)))) row,_=matcher.score(np.array([0,1])) self.assertIsNone(row['tolerance']['2px_3mm']['gt_coverage']) self.assertEqual(row['tolerance']['2px_3mm']['selected'],2)
def test_staged_sweeps_cover_all_requested_values(self): c=conditions();self.assertEqual(len(c),54) for method in ('S1','S2','S3','S4'): rows=[v for v in c.values() if v['method']==method] self.assertEqual({v['num_points'] for v in rows},{64,128,256,512}) self.assertEqual({v['structural_ratio'] for v in rows},{0.,.125,.25,.5}) self.assertEqual({v['orientation_threshold_deg'] for v in rows},{10,20,30,40}) self.assertEqual({v['seed'] for v in rows},{0,1,2})
def test_saved_evaluation_logging_all_frames_and_metadata(self): n,h,w=2,16,16 ep={'camera/rgb':np.zeros((n,h,w,3),np.uint8),'camera/depth':np.full((n,h,w),.3,np.float32), 'camera/intrinsic':np.tile([[100,0,8],[0,100,8],[0,0,1]],(n,1,1)), 'camera/cam2world':np.tile(np.eye(4),(n,1,1)),'tcp_pose':np.tile([0,0,0,1,0,0,0],(n,1)), 'camera/seg':np.ones((n,h,w),np.int16),'peg_id':np.array(1),'box_id':np.array(2), 'peg_pose':np.tile([0,0,.4,1,0,0,0],(n,1)),'box_pose':np.tile([1,0,.5,1,0,0,0],(n,1)), 'box_hole_pose':np.tile([1,0,.5,1,0,0,0],(n,1)),'peg_half_sizes':np.array([.1,.1,.1]), 'box_hole_radii':np.array(.02),'seed':np.array(0)} with tempfile.TemporaryDirectory() as d: root=Path(d);episode=root/'ep.npz';masks=root/'masks.npz' np.savez(episode,**ep);np.savez(masks,source_frame=np.arange(n),peg=np.ones((n,h,w),bool),box=np.zeros((n,h,w),bool)) with patch.dict(os.environ,{'WANDB_MODE':'disabled','EXPERIMENTS_DIR':str(root/'experiments')}): out=evaluate(episode,masks,root/'out',camera='camera',selected=(),seeds=(0,),make_plots=False) report=json.loads((out/'comparison.json').read_text()) self.assertEqual(report['evaluated_frames'],2);self.assertEqual(report['conditions'],44) self.assertFalse(report['config']['gt_sampling_input']) self.assertEqual(len(list(out.glob('*_samples.npz'))),2) with np.load(out/'f0000_samples.npz',allow_pickle=False) as ar: self.assertIn('S4_n256_r0.25_t20_s0/metadata/depth_discontinuity',ar.files) self.assertEqual(len(ar['S0_n256_r0_t20_s0/points']),256) meta=json.loads((root/'experiments'/out.name/'metadata.json').read_text()) self.assertEqual(meta['status'],'finished');self.assertEqual(meta['run_id'],out.name) np.savez(masks,source_frame=np.array([0]),peg=np.ones((1,h,w),bool),box=np.zeros((1,h,w),bool)) 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()123version https://git-lfs.github.com/spec/v1oid sha256:912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3asize 1051700123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""Evaluation-only GT matching and surface/false-selection metrics for Task03."""from dataclasses import replaceimport numpy as npfrom scipy.spatial import cKDTreefrom scipy.sparse import csr_matrixfrom scipy.ndimage import labelfrom visual.runtime.test.normal_diagnostics import stats, dilate, endpoints, erodefrom visual.runtime.test.run_normal_comparison import real_truthfrom visual.runtime.test.run_structural_edges import raster_reference, rim_reference, negative_regionsfrom visual.runtime.rgbd import PEG, BOX
TOLERANCES = ((1., .002), (2., .003), (3., .005))
class CoverageMatcher: """Same-pair joint 2D/3D matching. No reference-dependent sampling inputs.
Distances are unfiltered by a GT corridor. Missing selected points yield zero hits; distances then stay undefined and missing_reference_distances is explicit. Sampling retention denominator is only tracker-recoverable refs. """ def __init__(self, geometry, oid, reference, tolerances=TOLERANCES): self.flat = np.flatnonzero(geometry.observed_mask(oid)) self.uv = np.column_stack(np.unravel_index(self.flat, geometry.valid_depth.shape))[:, ::-1] self.xyz = geometry.xyz.reshape(-1, 3)[self.flat] self.ref_uv, self.ref_xyz = reference self.nref = len(self.ref_uv) self.tolerances = tolerances self.adjacencies = {} if len(self.flat) and self.nref: self.to_gt_px = cKDTree(self.ref_uv).query(self.uv)[0] self.to_gt_mm = cKDTree(self.ref_xyz).query(self.xyz)[0]*1000 else: self.to_gt_px = np.full(len(self.flat), np.nan) self.to_gt_mm = self.to_gt_px.copy() for px, m in tolerances: if len(self.flat) and self.nref: matrix = cKDTree(self.uv).sparse_distance_matrix(cKDTree(self.ref_uv), px, output_type='coo_matrix') good = np.linalg.norm(self.xyz[matrix.row]-self.ref_xyz[matrix.col], axis=1) <= m adj = csr_matrix((np.ones(good.sum(), bool), (matrix.row[good], matrix.col[good])), shape=(len(self.flat), self.nref)) else: adj = csr_matrix((len(self.flat), self.nref), dtype=bool) self.adjacencies[self.key(px,m)] = adj
@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)): raise ValueError('evaluation points outside observed support') out = dict(selected=len(rows), gt_visible=self.nref, tolerance={}) arrays = dict(sample_to_gt_px=self.to_gt_px[rows], sample_to_gt_mm=self.to_gt_mm[rows]) if len(rows) and self.nref: arrays['gt_to_sample_px'] = cKDTree(self.uv[rows]).query(self.ref_uv)[0] arrays['gt_to_sample_mm'] = cKDTree(self.xyz[rows]).query(self.ref_xyz)[0]*1000 else: arrays['gt_to_sample_px'] = np.empty(0); arrays['gt_to_sample_mm'] = np.empty(0) out['missing_reference_distances'] = self.nref if not len(rows) else 0 for key, adjacency in self.adjacencies.items(): observable = adjacency.getnnz(axis=0) > 0 covered = adjacency[rows].getnnz(axis=0) > 0 matched = adjacency[rows].getnnz(axis=1) > 0 row = dict(gt_visible=self.nref, tracker_observed=int(observable.sum()), sampled=int(covered.sum()), selected=len(rows), selected_near_gt=int(matched.sum())) # Every visible reference remains in the denominator, including tracker losses. row.update(gt_coverage=row['sampled']/self.nref if self.nref else None, tracker_coverage=row['tracker_observed']/self.nref if self.nref else None, sampling_retention=row['sampled']/row['tracker_observed'] if row['tracker_observed'] else None) # Spatial distribution of preservation, fixed image-axis halves of visible references. if self.nref: mid = np.median(self.ref_uv, axis=0) quadrants = (self.ref_uv[:,0] >= mid[0]).astype(int)+2*(self.ref_uv[:,1] >= mid[1]).astype(int) row['reference_quadrants'] = [dict(gt_visible=int((quadrants==q).sum()), tracker_observed=int((observable & (quadrants==q)).sum()), sampled=int((covered & (quadrants==q)).sum())) for q in range(4)] else: row['reference_quadrants'] = [] out['tolerance'][key] = row out['distances'] = {k:stats(v) for k,v in arrays.items()} 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) refs, matchers, negatives, surfaces = {}, {}, {}, {} for name, oid in [('peg',PEG), ('box',BOX)]: t = truths[name]; r = regions[name] robot = np.isin(gt[f'{camera}/seg'][frame.source_frame],robot_ids) & np.isfinite(t['depth']) & evidence.frame.geometry.valid_depth & (frame.depth < t['depth']-.0015) r['robot_occlusion_2px'] = dilate(endpoints(r['gt_visible'],robot),2) & r['gt_visible'] if name == 'box': r['plane_interior'] = np.logical_or.reduce([erode(r['gt_visible'] & (t['face']==f),3) for f in range(6)]) & ~dilate(r['hole_rim'],4) reference = raster_reference(maps[name]['seam'],t,frame.intrinsic) if name=='peg' else rim_reference(frame,gt,t,r['hole_rim']) refs[name] = reference matchers[name] = CoverageMatcher(evidence.frame.geometry,oid,reference) # Include other physical box seams when excluding negatives, exactly as Task02-C. other = raster_reference(maps[name]['seam'], t, frame.intrinsic) all_ref = tuple(np.concatenate([reference[i], other[i]]) for i in (0,1)) negatives[name] = negative_regions(r, maps[name], all_ref, frame.depth.shape) support = evidence.frame.geometry.observed_mask(oid) flat = np.flatnonzero(support) components, count = label(support) comp = components.ravel()[flat] sizes = np.bincount(comp, minlength=count+1) surfaces[name] = dict(flat=flat, xyz=evidence.frame.geometry.xyz.reshape(-1,3)[flat], plane=r['plane_interior'].ravel()[flat], face=t['face'].ravel()[flat], small_component=(sizes[comp] <= 64), component_count=count) return dict(truths=truths, regions=regions, maps=maps, references=refs, matchers=matchers, negatives=negatives, surfaces=surfaces)
def score_selection(result, context): row, arrays = dict(objects={}), {} for name, oid in [('peg',PEG),('box',BOX)]: choose = result.object_id==oid flat = result.flat_index[choose] structural, dist = context['matchers'][name].score(flat) arrays.update({name+'/'+k:v for k,v in dist.items()}) surface = context['surfaces'][name] nearest = cKDTree(result.points[choose]).query(surface['xyz'])[0]*1000 if choose.any() else np.empty(0) surface_dist = {'all':nearest} if len(nearest): surface_dist.update(plane=nearest[surface['plane']],small_components=nearest[surface['small_component']]) surface_dist.update({f'face_{f}':nearest[surface['face']==f] for f in range(6)}) surface_metrics = {k:dict(distance_mm=stats(v), within_3mm=int((v<=3).sum()), points=len(v)) for k,v in surface_dist.items()} surface_metrics['component_count'] = surface['component_count'] arrays.update({name+'/surface_'+k:v for k,v in surface_dist.items()}) priority = result.priority_selected[choose] negative = {} for k, mask in context['negatives'][name].items(): hit = mask.ravel()[flat] negative[k] = dict(observed=int(mask.ravel()[surface['flat']].sum()), selected=int(hit.sum()), priority=int((hit&priority).sum()), depth_priority=int((hit&result.depth_priority_selected[choose]).sum())) # Union is evaluated once; region counts deliberately overlap. false_union = np.logical_or.reduce(list(context['negatives'][name].values())) hit = false_union.ravel()[flat] negative['known_negative_union'] = dict(observed=int(false_union.ravel()[surface['flat']].sum()), selected=int(hit.sum()), priority=int((hit&priority).sum()), depth_priority=int((hit&result.depth_priority_selected[choose]).sum())) row['objects'][name] = dict(structural=structural,surface=surface_metrics,negative=negative,counts=result.counts[oid]) row['timings_ms'] = result.timings_ms return row, arrays
def summarize(rows, arrays): """Micro counts plus per-frame coverage distributions; no independent-frame CI.""" result = dict(frames=len(rows),objects={}) for name in ('peg','box'): objects = [r['objects'][name] for r in rows] counts = {k:sum(o['counts'][k] for o in objects) for k in objects[0]['counts']} structural = {} for tol in objects[0]['structural']['tolerance']: original = [o['structural']['tolerance'][tol] for o in objects] summed = {k:sum(o[k] for o in original) for k in ('gt_visible','tracker_observed','sampled','selected','selected_near_gt')} n,obs,sel = summed['gt_visible'],summed['tracker_observed'],summed['sampled'] summed.update(gt_coverage=sel/n if n else None,tracker_coverage=obs/n if n else None, sampling_retention=sel/obs if obs else None, frame_gt_coverage=stats([v['gt_coverage'] for v in original if v['gt_coverage'] is not None]), frame_sampling_retention=stats([v['sampling_retention'] for v in original if v['sampling_retention'] is not None])) structural[tol] = summed negatives = {k:{c:sum(o['negative'][k][c] for o in objects) for c in objects[0]['negative'][k]} for k in objects[0]['negative']} for v in negatives.values(): v['fraction_of_priority'] = v['priority']/counts['priority'] if counts['priority'] else None v['fraction_of_selected_budget'] = v['priority']/counts['selected'] if counts['selected'] else None distance = {k:stats(np.concatenate(v)) for k,v in arrays.items() if k.startswith(name+'/')} surfaces = {} for key in objects[0]['surface']: if key=='component_count': continue valid = [o['surface'][key] for o in objects if key in o['surface']] n=sum(v['points'] for v in valid); hit=sum(v['within_3mm'] for v in valid) surfaces[key] = dict(points=n,within_3mm=hit,coverage_3mm=hit/n if n else None, distance_mm=distance.get(name+'/surface_'+key)) result['objects'][name] = dict(counts=counts,structural=structural,surface=surfaces,negative=negatives, distances=distance,missing_reference_distances=sum(o['structural']['missing_reference_distances'] for o in objects)) result['timings_ms'] = {k:stats([r['timings_ms'][k] for r in rows]) for k in rows[0]['timings_ms']} return result1234567891011121314151617181920212223242526272829303132333435363738test_empty_reference_is_undefined_not_perfect (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_empty_reference_is_undefined_not_perfect) ... oktest_hole_reference_only_observed_entrance_not_hidden_projection (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_hole_reference_only_observed_entrance_not_hidden_projection) ... oktest_joint_tolerance_requires_same_pair (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_joint_tolerance_requires_same_pair) ... oktest_saved_evaluation_logging_all_frames_and_metadata (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_saved_evaluation_logging_all_frames_and_metadata) ... Output: /private/var/folders/_2/xcfq65k14fsfgp0n7w86w3_m0000gn/T/tmp7ldrj9p4/out/1a24bfdb32674eb5a470972ddcca585cFrames 1/2; 44 conditions eachoktest_staged_sweeps_cover_all_requested_values (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_staged_sweeps_cover_all_requested_values) ... oktest_tracking_and_sampling_losses_have_separate_denominators (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_tracking_and_sampling_losses_have_separate_denominators) ... oktest_empty_points_zero_observation_and_zero_visible (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_empty_points_zero_observation_and_zero_visible) ... oktest_general_fps_candidate_and_priority_are_inapplicable (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_general_fps_candidate_and_priority_are_inapplicable) ... oktest_geometry_alignment_invalid_depth_overlap_and_pixel_centres (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_geometry_alignment_invalid_depth_overlap_and_pixel_centres) ... oktest_historical_evaluation_changes_fail_closed (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_historical_evaluation_changes_fail_closed) ... oktest_invalid_nodes_and_non_partition_are_rejected (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_invalid_nodes_and_non_partition_are_rejected) ... oktest_negative_union_deduplicates_and_depth_bands_cover_paths (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_negative_union_deduplicates_and_depth_bands_cover_paths) ... oktest_reference_overlap_union_and_surface_outside_candidates (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_reference_overlap_union_and_surface_outside_candidates) ... oktest_two_different_nodes_cannot_satisfy_one_reference_pair (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_two_different_nodes_cannot_satisfy_one_reference_pair) ... oktest_all_false_candidates_still_respect_contract_and_roles (visual.runtime.test.test_sampling.SamplingTests.test_all_false_candidates_still_respect_contract_and_roles) ... oktest_budget_ratio_observed_uniqueness_alignment_and_reproducibility (visual.runtime.test.test_sampling.SamplingTests.test_budget_ratio_observed_uniqueness_alignment_and_reproducibility) ... oktest_fps_seed_ties_initial_and_coincident_rows (visual.runtime.test.test_sampling.SamplingTests.test_fps_seed_ties_initial_and_coincident_rows) ... oktest_gt_not_accepted_and_rgb_cannot_change_selection (visual.runtime.test.test_sampling.SamplingTests.test_gt_not_accepted_and_rgb_cannot_change_selection) ... oktest_insufficient_both_empty_and_zero_budget (visual.runtime.test.test_sampling.SamplingTests.test_insufficient_both_empty_and_zero_budget) ... oktest_invalid_config_is_explicit (visual.runtime.test.test_sampling.SamplingTests.test_invalid_config_is_explicit) ... oktest_mask_cut_and_invalid_hole_not_structural_but_depth_step_separate (visual.runtime.test.test_sampling.SamplingTests.test_mask_cut_and_invalid_hole_not_structural_but_depth_step_separate) ... oktest_minimums_and_configurable_observation_allocation (visual.runtime.test.test_sampling.SamplingTests.test_minimums_and_configurable_observation_allocation) ... oktest_normal_and_candidate_regression_against_task02_all_fields (visual.runtime.test.test_sampling.SamplingTests.test_normal_and_candidate_regression_against_task02_all_fields) ... oktest_one_object_empty_current_observation_no_cache (visual.runtime.test.test_sampling.SamplingTests.test_one_object_empty_current_observation_no_cache) ... oktest_overlap_invalid_depth_and_input_immutability (visual.runtime.test.test_sampling.SamplingTests.test_overlap_invalid_depth_and_input_immutability) ... oktest_plane_has_no_invented_structural_and_equals_fps (visual.runtime.test.test_sampling.SamplingTests.test_plane_has_no_invented_structural_and_equals_fps) ... oktest_real_crease_priority_hits_visible_edge_and_spreads (visual.runtime.test.test_sampling.SamplingTests.test_real_crease_priority_hits_visible_edge_and_spreads) ... oktest_sparse_candidates_surface_fills_without_duplicates (visual.runtime.test.test_sampling.SamplingTests.test_sparse_candidates_surface_fills_without_duplicates) ... oktest_zero_ratio_matches_general_fps_for_every_method (visual.runtime.test.test_sampling.SamplingTests.test_zero_ratio_matches_general_fps_for_every_method) ... oktest_clustered_candidates_fps_covers_small_remote_region (visual.runtime.test.test_sampling_geometry.SamplingGeometryTests.test_clustered_candidates_fps_covers_small_remote_region) ... oktest_cuboid_visible_seam_is_preserved_by_priority (visual.runtime.test.test_sampling_geometry.SamplingGeometryTests.test_cuboid_visible_seam_is_preserved_by_priority) ... ok
----------------------------------------------------------------------Ran 31 tests in 0.670s
OK123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124{ "artifacts": [ { "kind": "metrics", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/70a7c74709bce2a757c1512e415829cb3b676714cad85267d7c1b1eb836535d6/metrics.json", "sha256": "70a7c74709bce2a757c1512e415829cb3b676714cad85267d7c1b1eb836535d6", "size": 4266 }, { "kind": "metrics", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/857eec6078322285809c0322622eca4059e5be4d5d088bbb62e68a7ef6714796/diagnostic.json", "sha256": "857eec6078322285809c0322622eca4059e5be4d5d088bbb62e68a7ef6714796", "size": 184582 }, { "kind": "metrics", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/f36e98379144581c4d26815b4530f805053b7d46aaed4979e388049a5c075dac/verification.json", "sha256": "f36e98379144581c4d26815b4530f805053b7d46aaed4979e388049a5c075dac", "size": 927 }, { "kind": "metrics", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/1d2fd5719d0b9828c07dde87543c0468afc2d6e59d3c092ff337d735d9559d9f/visualizations_verification.json", "sha256": "1d2fd5719d0b9828c07dde87543c0468afc2d6e59d3c092ff337d735d9559d9f", "size": 3091 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.py", "sha256": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "size": 20175 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.py", "sha256": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "size": 15611 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.py", "sha256": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "size": 15253 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/70742cb85640c3ab9a3441dcabbcb62bbce4b887dc5858890ec0c2054a0149b1/analysis.txt", "sha256": "70742cb85640c3ab9a3441dcabbcb62bbce4b887dc5858890ec0c2054a0149b1", "size": 15669 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/e937b9f22220beb77e4a4a7ba6f641e179b0b1832d0f89ea27e85197c26127ef/tests.log", "sha256": "e937b9f22220beb77e4a4a7ba6f641e179b0b1832d0f89ea27e85197c26127ef", "size": 5665 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/34c14a7aba8eba48f7aafc5f2a0ca6708dd0ffa1732a1ae68e00c84be750f4e8/execution.log", "sha256": "34c14a7aba8eba48f7aafc5f2a0ca6708dd0ffa1732a1ae68e00c84be750f4e8", "size": 226 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/1de58f1273afcf997f91399d3bee129ab9eabcd1407f28a9d0d36808f01f6f13/implementation.patch", "sha256": "1de58f1273afcf997f91399d3bee129ab9eabcd1407f28a9d0d36808f01f6f13", "size": 35358 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/9850f748895cb1decc1bb5ad67a951ac61df8cd5d5aff39bc79faf06b933c0da/visualizations.html", "sha256": "9850f748895cb1decc1bb5ad67a951ac61df8cd5d5aff39bc79faf06b933c0da", "size": 1164642 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8663cba6a243baf6c4a12fee5be066aeaf724c25bfcf5208e35c3014cd46ba17/build_visualizations.py", "sha256": "8663cba6a243baf6c4a12fee5be066aeaf724c25bfcf5208e35c3014cd46ba17", "size": 7618 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/6f789bf37516620bdbd2e45b27a729a331ef1d14961cd97e0606533d28c4790f/visualizations_template.html", "sha256": "6f789bf37516620bdbd2e45b27a729a331ef1d14961cd97e0606533d28c4790f", "size": 39058 }, { "kind": "reports", "path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a/report-912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a.zip", "sha256": "912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a", "size": 1051700 } ], "config_path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/config/0e7e72647775333761a724f0c55247849b01753f51df2a4089535c30867eaedd/config.yaml", "environment": null, "episode_metadata_paths": [], "git_commit": "2e10a51736826aa980f2fe79a801eb6c9da8e288", "git_dirty": true, "metrics_path": "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/70a7c74709bce2a757c1512e415829cb3b676714cad85267d7c1b1eb836535d6/metrics.json", "model_name": "task03d_rim_bottleneck", "random_seed": 0, "report_paths": [ "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.py", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.py", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.py", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/70742cb85640c3ab9a3441dcabbcb62bbce4b887dc5858890ec0c2054a0149b1/analysis.txt", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/e937b9f22220beb77e4a4a7ba6f641e179b0b1832d0f89ea27e85197c26127ef/tests.log", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/34c14a7aba8eba48f7aafc5f2a0ca6708dd0ffa1732a1ae68e00c84be750f4e8/execution.log", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/1de58f1273afcf997f91399d3bee129ab9eabcd1407f28a9d0d36808f01f6f13/implementation.patch", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/9850f748895cb1decc1bb5ad67a951ac61df8cd5d5aff39bc79faf06b933c0da/visualizations.html", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8663cba6a243baf6c4a12fee5be066aeaf724c25bfcf5208e35c3014cd46ba17/build_visualizations.py", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/6f789bf37516620bdbd2e45b27a729a331ef1d14961cd97e0606533d28c4790f/visualizations_template.html", "visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a/report-912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a.zip" ], "run_id": "d3f14ee494894daabb8ba2fab8e1b00c", "schema_version": 1, "selection": [ "metrics", "reports" ], "task": null, "team": "visual", "wandb_run_id": "d3f14ee494894daabb8ba2fab8e1b00c"}visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/config/0e7e72647775333761a724f0c55247849b01753f51df2a4089535c30867eaedd/config.yamlAdded+43
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/1d2fd5719d0b9828c07dde87543c0468afc2d6e59d3c092ff337d735d9559d9f/visualizations_verification.jsonAdded+34
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/70a7c74709bce2a757c1512e415829cb3b676714cad85267d7c1b1eb836535d6/metrics.jsonAdded+92
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/857eec6078322285809c0322622eca4059e5be4d5d088bbb62e68a7ef6714796/diagnostic.jsonAdded
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/metrics/f36e98379144581c4d26815b4530f805053b7d46aaed4979e388049a5c075dac/verification.jsonAdded+28
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/1de58f1273afcf997f91399d3bee129ab9eabcd1407f28a9d0d36808f01f6f13/implementation.patchAdded+592
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/34c14a7aba8eba48f7aafc5f2a0ca6708dd0ffa1732a1ae68e00c84be750f4e8/execution.logAdded+2
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/6f789bf37516620bdbd2e45b27a729a331ef1d14961cd97e0606533d28c4790f/visualizations_template.htmlAdded+200
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/70742cb85640c3ab9a3441dcabbcb62bbce4b887dc5858890ec0c2054a0149b1/analysis.txtAdded+217
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8663cba6a243baf6c4a12fee5be066aeaf724c25bfcf5208e35c3014cd46ba17/build_visualizations.pyAdded+135
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.pyAdded+247
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a/report-912dc970744ab2d7810032c279d3b3d4bb66c8da01d622685cb21305dfa2ac3a.zipAdded+3
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/9850f748895cb1decc1bb5ad67a951ac61df8cd5d5aff39bc79faf06b933c0da/visualizations.htmlAdded
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.pyAdded+248
visual/d3f14ee494894daabb8ba2fab8e1b00c/artifacts/reports/e937b9f22220beb77e4a4a7ba6f641e179b0b1832d0f89ea27e85197c26127ef/tests.logAdded+38
visual/d3f14ee494894daabb8ba2fab8e1b00c/manifests/c90a11bf99c71db2fe8a003348a41743c9e544ff60a7f0753486b8bcb6fdf5a1/manifest.jsonAdded+124