Publish experiment f68c59f210b5499dadc7e962c7f64492 (rollouts)
Browse filesFiles changed (43)
- .gitattributes+1
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/config/937bd74f8b4c75bc2f57a7281c25b32c475dc0119549647cb1bb5ce4211a6895/config.yamlAdded+44
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/03ad42a3d0690b248d45f7c8bf7a1e0b5e78a216b959a0a1a6e19afe89e644db/frame_metrics.jsonAdded+3
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/3170812df18b2b7df42f3b521e5f028104d4dc6144bb89e0e37b22f9f621ec14/analysis.jsonAdded+476
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/68383ee1b98ecbf9f7dd2d65b499e7c9dd11188195f55d4aed89bc36dea5621e/metrics.jsonAdded+14
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/6f3cdc53d79413f85fcc2f9289fc9f314d2ed28d42ac2c9aadd2ba85fe1af37c/verification.jsonAdded+1130
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/725de8bb396a97bc5de7127adbd02c0c4e814420d3e54f931e49625ac20b437f/latency.jsonAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/abfa92e4b11dfa7aca06b7ec00edec04bd109ce66016943eef0bdf1ac9ef957b/adaptive_node_budget.jsonAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/eb0adba87fb5be06430941687f23d712389a1229525a6d25518181744093a712/preservation_before.jsonAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/0dce4af6f35bbad39f1c86a5cc8772082dcc3b5568182ac7849b0e045df17b98/execution.logAdded+21
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/1033399dea794928598c433dd74c43424b714d2a8d82ce051cd5f32319e52663/f0045_overlay.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/105fac262d8756896c72f9708632d0e259a45a727e6a446566a58f4de89a628a/tests.logAdded+52
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2aabb94be317001751f0ff6b1465dfe21b4b022619f1b85ea93bf58f6c49991a/f0015_overlay.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.pyAdded+81
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36561474573076ee17f2ee639eda9bf409eb1571d02502a313aac06556eb916a/f0018_overlay.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.pyAdded+255
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9/run_adaptive_node_budget.pyAdded+745
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.pyAdded+266
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/623718ac7c7715adf6235f9a634496660e299d79185d1be17e3391fc447b2749/f0000_overlay.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b/report-67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b.zipAdded+3
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.pyAdded+475
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.pyAdded+258
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8269602147f2255e8aacb1ac62f20bcd02159711bf464b0b812bfe2e78fd10ce/adaptive_node_budget.htmlAdded+90
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.pyAdded+206
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.pyAdded+247
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a3ed390c821e53b3ef181025d3f8dc84fa7fed86f35cb2c695e30557124bb91a/f0120_overlay.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031/test_sampling_geometry.pyAdded+43
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b/run_normal_comparison.pyAdded+453
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164/rgbd.pyAdded+202
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e/normal_estimators.pyAdded+130
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc/normal_diagnostics.pyAdded+303
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d743c6d0dcffbf1928434f522a58a9eb3eeea29e195680d81ffe0d7e61dd157e/latency_depth.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189/test_adaptive_node_budget.pyAdded+182
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.pyAdded+248
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081/run_sampling.pyAdded+203
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dea26841465aa6959e4e07f09d6e407d45108112c001a5e57e2ffb67cf019867/implementation.patchAdded+1343
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/ea0cf309e75b8c90b1dcc5054db7dfe3db8653dabd248ab13ad177a259c3fa7e/preservation_temporal.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe/run_structural_edges.pyAdded+411
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/f903d46f913aec28e967da93017980784f97ae9701a874e1d815b63c3fbb7c92/budget_timeseries.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223/sampling_plots.pyAdded+126
- visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fe9ddb73b2487529bec08235b79107b3e542036c1c2ed3a75cf21157f855d4e0/f0080_overlay.pngAdded
- visual/f68c59f210b5499dadc7e962c7f64492/manifests/c4b3bc965a4e5a872aae8d5f40f1fe305fdc6eeb05e52e3e6eb3c2720bdf1c1c/manifest.jsonAdded+296
60 unmodified lines61626360 unmodified linesvisual/4b1c377ae2044344a4f596b249627d89/artifacts/metrics/68e8f59f7b091d5ade085452084a7b5caedc9deca6f164e707952519d40a30e2/comparison.json filter=lfs diff=lfs merge=lfs -textvisual/03d9777a004349e3a794147e4e55a2f0/artifacts/metrics/ecdb9a75c006a9822b674871bd969a4548da3269795aaadca003a2d1d9a2b940/optimization.json filter=lfs diff=lfs merge=lfs -textvisual/b622e76deceb419ab9c5aa80a8f8280c/artifacts/metrics/50dd45bb896a33f557ee2b3fee7067efb155f1880697a16150812010b7c91889/comparison.json filter=lfs diff=lfs merge=lfs -text60 unmodified lines6162636460 unmodified linesvisual/4b1c377ae2044344a4f596b249627d89/artifacts/metrics/68e8f59f7b091d5ade085452084a7b5caedc9deca6f164e707952519d40a30e2/comparison.json filter=lfs diff=lfs merge=lfs -textvisual/03d9777a004349e3a794147e4e55a2f0/artifacts/metrics/ecdb9a75c006a9822b674871bd969a4548da3269795aaadca003a2d1d9a2b940/optimization.json filter=lfs diff=lfs merge=lfs -textvisual/b622e76deceb419ab9c5aa80a8f8280c/artifacts/metrics/50dd45bb896a33f557ee2b3fee7067efb155f1880697a16150812010b7c91889/comparison.json filter=lfs diff=lfs merge=lfs -textvisual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/03ad42a3d0690b248d45f7c8bf7a1e0b5e78a216b959a0a1a6e19afe89e644db/frame_metrics.json filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "alpha": 1, "baseline": "S3_n256_r0.25_t20_s0", "camera": "base_camera", "device": "cpu", "extraction": "once per frame; lossless cache to enforce all-frame gates first", "independent_episode": false, "input": "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/data/step2/ep000.npz", "masks": "/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/results/runtime_tracking/ep000/masks.npz", "matched": { "adaptive_selected_sum": 11482, "budget": 95, "causal_online": false, "fixed_selected_sum": 11495, "mean_error_nodes": 0.10743801652892562, "selection": "count-only absolute total difference; smaller integer on ties" }, "maximum": 256, "minimum_per_object": 16, "numpy": "2.4.6", "platform": "macOS-27.0.1-arm64-arm-64bit", "policy_inputs": "current observed support counts and fixed first-positive reference only", "python": "3.11.13", "reference": 23445, "reference_source": 0, "seed": 0, "source_run_id": "2551448b0fae4c6bbce3caf48774275f", "task": "03-AB", "timing_repetitions": 3, "tolerances": [ [ 1.0, 0.002 ], [ 2.0, 0.003 ], [ 3.0, 0.005 ] ]}123version https://git-lfs.github.com/spec/v1oid sha256:03ad42a3d0690b248d45f7c8bf7a1e0b5e78a216b959a0a1a6e19afe89e644dbsize 44649989123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476{ "areas": { "box": { "invalid_depth": { "count": 121, "max": 7.0, "mean": 0.4462809917355372, "min": 0.0, "p50": 0.0, "p95": 2.0, "p99": 6.0, "sum": 54 }, "positive_depth_overlap": { "count": 121, "max": 75.0, "mean": 17.09090909090909, "min": 0.0, "p50": 0.0, "p95": 60.0, "p99": 70.39999999999999, "sum": 2068 }, "raw": { "count": 121, "max": 11755.0, "mean": 3037.1404958677685, "min": 0.0, "p50": 2542.0, "p95": 9415.0, "p99": 11665.0, "sum": 367494 }, "valid": { "count": 121, "max": 11755.0, "mean": 3019.603305785124, "min": 0.0, "p50": 2540.0, "p95": 9415.0, "p99": 11665.0, "sum": 365372 } }, "peg": { "invalid_depth": { "count": 121, "max": 0.0, "mean": 0.0, "min": 0.0, "p50": 0.0, "p95": 0.0, "p99": 0.0, "sum": 0 }, "positive_depth_overlap": { "count": 121, "max": 75.0, "mean": 17.09090909090909, "min": 0.0, "p50": 0.0, "p95": 60.0, "p99": 70.39999999999999, "sum": 2068 }, "raw": { "count": 121, "max": 11805.0, "mean": 5684.545454545455, "min": 1295.0, "p50": 6156.0, "p95": 11789.0, "p99": 11802.0, "sum": 687830 }, "valid": { "count": 121, "max": 11805.0, "mean": 5667.454545454545, "min": 1249.0, "p50": 6156.0, "p95": 11789.0, "p99": 11802.0, "sum": 685762 } } }, "component_diagnostics": { "box": { "Adaptive": { "candidate_without_final": 0, "candidate_without_priority": 0, "component_frame_count": 208, "small_component_frame_count": 16 }, "Fixed256": { "candidate_without_final": 0, "candidate_without_priority": 0, "component_frame_count": 208, "small_component_frame_count": 16 }, "FixedMatched": { "candidate_without_final": 0, "candidate_without_priority": 0, "component_frame_count": 208, "small_component_frame_count": 16 } }, "peg": { "Adaptive": { "candidate_without_final": 0, "candidate_without_priority": 0, "component_frame_count": 122, "small_component_frame_count": 1 }, "Fixed256": { "candidate_without_final": 0, "candidate_without_priority": 0, "component_frame_count": 122, "small_component_frame_count": 1 }, "FixedMatched": { "candidate_without_final": 0, "candidate_without_priority": 0, "component_frame_count": 122, "small_component_frame_count": 1 } } }, "depth_area_association": { "box": { "camera_range_m": { "count": 102, "max": 0.5320230615564371, "mean": 0.5133684861967052, "min": 0.5066481720103897, "p50": 0.5120682851386587, "p95": 0.5222466553997192, "p99": 0.5294799499294053 }, "camera_z_m": { "count": 102, "max": 0.527999997138977, "mean": 0.5019607836124944, "min": 0.47200000286102295, "p50": 0.5080000162124634, "p95": 0.5189499944448471, "p99": 0.5249599766731262 }, "interpretation": "descriptive repeated frames; tracking/viewpoint/occlusion confounded; no distance policy", "spearman_range_vs_area": 0.023897532218657043, "spearman_z_vs_area": 0.18220919518557122 }, "peg": { "camera_range_m": { "count": 121, "max": 0.40287560010578594, "mean": 0.262579505721998, "min": 0.18995498132906843, "p50": 0.23619651258313568, "p95": 0.40126835223535107, "p99": 0.40268510280942016 }, "camera_z_m": { "count": 121, "max": 0.4009999930858612, "mean": 0.24414049704705387, "min": 0.17000000178813934, "p50": 0.20600000023841858, "p95": 0.39899998903274536, "p99": 0.4000000059604645 }, "interpretation": "descriptive repeated frames; tracking/viewpoint/occlusion confounded; no distance policy", "spearman_range_vs_area": -0.6648008928702599, "spearman_z_vs_area": -0.7218920339215498 } }, "largest_node_change_frames": [ { "delta": -13, "paired_retention_pp": { "box": null, "peg": -28.97862232779097 }, "selected": 135, "source": 16 }, { "delta": -11, "paired_retention_pp": { "box": -12.0, "peg": -14.502164502164504 }, "selected": 169, "source": 13 }, { "delta": -11, "paired_retention_pp": { "box": null, "peg": -24.434389140271495 }, "selected": 148, "source": 15 }, { "delta": -11, "paired_retention_pp": { "box": null, "peg": -35.25 }, "selected": 124, "source": 17 }, { "delta": -10, "paired_retention_pp": { "box": 0.0, "peg": -9.956709956709952 }, "selected": 180, "source": 12 }, { "delta": -10, "paired_retention_pp": { "box": null, "peg": -20.26143790849673 }, "selected": 159, "source": 14 }, { "delta": -9, "paired_retention_pp": { "box": -5.825242718446602, "peg": -4.978354978354976 }, "selected": 223, "source": 7 }, { "delta": -9, "paired_retention_pp": { "box": 0.0, "peg": -9.956709956709958 }, "selected": 190, "source": 11 } ], "paired_adaptive_minus_fixedmatched": { "box": { "count": 47, "losses": 12, "max": 5.825242718446602, "mean": -16.33386123160963, "min": -100.0, "p50": 0.0, "p95": 5.825242718446602, "p99": 5.825242718446602, "ties": 25, "wins": 10 }, "peg": { "count": 121, "losses": 60, "max": 23.16017316017316, "mean": -1.1626534358113723, "min": -45.91836734693878, "p50": 0.0, "p95": 21.21212121212121, "p99": 22.9004329004329, "ties": 17, "wins": 44 } }, "postcheck": { "all_html_links_resolve": 156, "causal_requests_and_fixedmatched_verified": true, "frames": 121, "independent_total_counts": { "Adaptive": 11482, "Fixed256": 30976, "FixedMatched": 11495 }, "selection_feature_alignment": true, "timing_aliases_and_accounting_verified": true }, "stage_totals": { "box": { "Adaptive": { "C": { "matched_node_count": 1596, "node_count": 11594, "unique_reference_count": 1143 }, "F": { "matched_node_count": 39, "node_count": 4226, "unique_reference_count": 106 }, "P": { "matched_node_count": 26, "node_count": 813, "unique_reference_count": 75 }, "S": { "matched_node_count": 13, "node_count": 3413, "unique_reference_count": 31 }, "X": { "matched_node_count": 2027, "node_count": 365372, "unique_reference_count": 1365 }, "observation_loss": 413, "sampling_loss": 1259, "surface_extra_reference": 31 }, "Fixed256": { "C": { "matched_node_count": 1596, "node_count": 11594, "unique_reference_count": 1143 }, "F": { "matched_node_count": 67, "node_count": 11376, "unique_reference_count": 156 }, "P": { "matched_node_count": 40, "node_count": 2332, "unique_reference_count": 103 }, "S": { "matched_node_count": 27, "node_count": 9044, "unique_reference_count": 53 }, "X": { "matched_node_count": 2027, "node_count": 365372, "unique_reference_count": 1365 }, "observation_loss": 413, "sampling_loss": 1209, "surface_extra_reference": 53 }, "FixedMatched": { "C": { "matched_node_count": 1596, "node_count": 11594, "unique_reference_count": 1143 }, "F": { "matched_node_count": 36, "node_count": 4370, "unique_reference_count": 85 }, "P": { "matched_node_count": 17, "node_count": 841, "unique_reference_count": 47 }, "S": { "matched_node_count": 19, "node_count": 3529, "unique_reference_count": 38 }, "X": { "matched_node_count": 2027, "node_count": 365372, "unique_reference_count": 1365 }, "observation_loss": 413, "sampling_loss": 1280, "surface_extra_reference": 38 } }, "peg": { "Adaptive": { "C": { "matched_node_count": 46122, "node_count": 49430, "unique_reference_count": 30355 }, "F": { "matched_node_count": 1833, "node_count": 7256, "unique_reference_count": 9141 }, "P": { "matched_node_count": 1783, "node_count": 2004, "unique_reference_count": 8935 }, "S": { "matched_node_count": 50, "node_count": 5252, "unique_reference_count": 206 }, "X": { "matched_node_count": 82154, "node_count": 685762, "unique_reference_count": 32460 }, "observation_loss": 204, "sampling_loss": 23319, "surface_extra_reference": 206 }, "Fixed256": { "C": { "matched_node_count": 46122, "node_count": 49430, "unique_reference_count": 30355 }, "F": { "matched_node_count": 4936, "node_count": 19600, "unique_reference_count": 19893 }, "P": { "matched_node_count": 4834, "node_count": 5412, "unique_reference_count": 19588 }, "S": { "matched_node_count": 102, "node_count": 14188, "unique_reference_count": 306 }, "X": { "matched_node_count": 82154, "node_count": 685762, "unique_reference_count": 32460 }, "observation_loss": 204, "sampling_loss": 12567, "surface_extra_reference": 305 }, "FixedMatched": { "C": { "matched_node_count": 46122, "node_count": 49430, "unique_reference_count": 30355 }, "F": { "matched_node_count": 1734, "node_count": 7125, "unique_reference_count": 8410 }, "P": { "matched_node_count": 1683, "node_count": 1942, "unique_reference_count": 8226 }, "S": { "matched_node_count": 51, "node_count": 5183, "unique_reference_count": 184 }, "X": { "matched_node_count": 82154, "node_count": 685762, "unique_reference_count": 32460 }, "observation_loss": 204, "sampling_loss": 24050, "surface_extra_reference": 184 } } }}1234567891011121314[ { "metrics": { "eval/task03ab/Adaptive/mean_nodes": 94.89256198347107, "eval/task03ab/Adaptive/reduction": 0.6293259297520661, "eval/task03ab/Fixed256/mean_nodes": 256.0, "eval/task03ab/Fixed256/reduction": 0.0, "eval/task03ab/FixedMatched/mean_nodes": 95.0, "eval/task03ab/FixedMatched/reduction": 0.62890625 }, "run_id": "f68c59f210b5499dadc7e962c7f64492", "step": null }]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130{ "adaptive_geometry_executed": true, "adaptive_request256_exact_frames": [ 0, 1, 2 ], "deterministic_repetitions": true, "evaluated_frames": 121, "final_new_repository_files_sha256": { "docs/visual-graph-integration/03ab_adaptive_node_budget.md": "50af20b5d8176b1d7e978fd9afeec5abfa276bb6458797eeb81a2dc74abf524a", "visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189" }, "final_preservation": { "changed_or_missing": [], "checked_files": 1226, "unchanged": true }, "frame_gates": [ { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 0, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 1, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 2, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 3, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 4, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 5, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 6, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 7, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 8, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 9, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 10, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 11, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 12, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 13, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 14, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 15, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 16, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 17, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 18, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 19, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 20, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 21, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 22, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 23, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 24, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 25, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 26, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 27, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 28, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 29, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 30, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 31, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 32, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 33, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 34, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 35, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 36, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 37, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 38, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 39, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 40, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 41, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 42, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 43, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 44, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 45, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 46, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 47, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 48, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 49, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 50, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 51, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 52, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 53, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 54, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 55, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 56, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 57, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 58, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 59, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 60, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 61, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 62, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 63, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 64, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 65, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 66, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 67, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 68, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 69, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 70, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 71, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 72, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 73, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 74, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 75, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 76, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 77, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 78, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 79, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 80, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 81, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 82, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 83, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 84, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 85, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 86, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 87, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 88, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 89, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 90, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 91, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 92, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 93, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 94, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 95, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 96, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 97, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 98, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 99, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 100, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 101, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 102, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 103, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 104, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 105, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 106, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 107, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 108, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 109, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 110, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 111, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 112, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 113, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 114, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 115, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 116, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 117, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 118, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 119, "support_exact": true }, { "candidate_exact": true, "fixed256_all_fields_exact": true, "fixed256_original_metrics_exact": true, "reference_exact": true, "source_frame": 120, "support_exact": true } ], "gates_passed": true, "gpu_executed": false, "input_hashes": { "visual/data/step2/ep000.npz": "22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba", "visual/results/runtime_tracking/ep000/masks.npz": "6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042" }, "markdown_relative_links_verified": 30, "preservation": { "changed_or_missing": [], "checked_files": 1226, "unchanged": true }, "primary_tolerance": "same pair 2px AND 3mm", "saved_output_postcheck": { "all_html_links_resolve": 156, "causal_requests_and_fixedmatched_verified": true, "frames": 121, "independent_total_counts": { "Adaptive": 11482, "Fixed256": 30976, "FixedMatched": 11495 }, "selection_feature_alignment": true, "timing_aliases_and_accounting_verified": true }, "source_contract": { "visual/runtime/edge_evidence.py": { "current_sha256": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "original_sha256": "14ab164cd98a0be16c7f12e2e6679b932b697028e567975b0dc31a939bf903b4", "status": "AST identical (formatting only)" }, "visual/runtime/geometry.py": { "current_sha256": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "original_sha256": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "status": "byte identical" }, "visual/runtime/normal_estimators.py": { "current_sha256": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "original_sha256": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "status": "byte identical" }, "visual/runtime/pca.py": { "current_sha256": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "original_sha256": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "status": "byte identical" }, "visual/runtime/rgbd.py": { "current_sha256": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "original_sha256": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "status": "byte identical" }, "visual/runtime/sampling.py": { "current_sha256": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "original_sha256": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "status": "byte identical" }, "visual/runtime/test/normal_diagnostics.py": { "current_sha256": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "original_sha256": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "status": "byte identical" }, "visual/runtime/test/run_normal_comparison.py": { "current_sha256": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "original_sha256": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "status": "byte identical" }, "visual/runtime/test/run_normal_diagnostics.py": { "current_sha256": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "original_sha256": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "status": "byte identical" }, "visual/runtime/test/run_sampling.py": { "current_sha256": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "original_sha256": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "status": "byte identical" }, "visual/runtime/test/run_structural_edges.py": { "current_sha256": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "original_sha256": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "status": "byte identical" }, "visual/runtime/test/sampling_evaluation.py": { "current_sha256": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "original_sha256": "a99654f398d1e429601459878ed4080100bc3dc19b42e78471572298c6e05e4a", "status": "original definitions unchanged; additive diagnostics only" }, "visual/runtime/test/sampling_plots.py": { "current_sha256": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "original_sha256": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "status": "byte identical" }, "visual/runtime/test/test_sampling.py": { "current_sha256": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "original_sha256": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "status": "byte identical" }, "visual/runtime/test/test_sampling_evaluation.py": { "current_sha256": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "original_sha256": "1705fd07af7fb611be87f2570d8c4dce3dfd9be8020873018aeeda258924e303", "status": "diagnostic tests extended; not an evaluation dependency" }, "visual/runtime/test/test_sampling_geometry.py": { "current_sha256": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "original_sha256": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "status": "byte identical" } }, "source_snapshot_sha256": { "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031" }, "visual_review_pngs": [ "plots/budget_timeseries.png", "plots/preservation_temporal.png", "plots/latency_depth.png", "frames/f0000_overlay.png", "frames/f0015_overlay.png", "frames/f0018_overlay.png", "frames/f0045_overlay.png", "frames/f0080_overlay.png", "frames/f0120_overlay.png" ], "whitespace_check": "PASS"}123456789101112131415161718192021Output: /Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/f68c59f210b5499dadc7e962c7f64492Gate 1/121: support/candidates/selection/features/reference/metrics exactGate 16/121: support/candidates/selection/features/reference/metrics exactGate 31/121: support/candidates/selection/features/reference/metrics exactGate 46/121: support/candidates/selection/features/reference/metrics exactGate 61/121: support/candidates/selection/features/reference/metrics exactGate 76/121: support/candidates/selection/features/reference/metrics exactGate 91/121: support/candidates/selection/features/reference/metrics exactGate 106/121: support/candidates/selection/features/reference/metrics exactGate 121/121: support/candidates/selection/features/reference/metrics exactAll 121 gates passed. Starting paired ablation.Ablation 1/121: adaptive request=256, matched=95Ablation 16/121: adaptive request=148, matched=95Ablation 31/121: adaptive request=100, matched=95Ablation 46/121: adaptive request=95, matched=95Ablation 61/121: adaptive request=78, matched=95Ablation 76/121: adaptive request=52, matched=95Ablation 91/121: adaptive request=58, matched=95Ablation 106/121: adaptive request=65, matched=95Ablation 121/121: adaptive request=76, matched=95Completed: /Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/f68c59f210b5499dadc7e962c7f6449212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152test_256_reproduction_including_support_shortfall (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_256_reproduction_including_support_shortfall) ... oktest_causal_prefix_and_future_independence (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_causal_prefix_and_future_independence) ... oktest_first_positive_reference_never_resets (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_first_positive_reference_never_resets) ... oktest_fixedmatched_capacity_tie_and_count_only (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_fixedmatched_capacity_tie_and_count_only) ... oktest_gt_annotation_and_reference_cannot_affect_selection (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_gt_annotation_and_reference_cannot_affect_selection) ... oktest_half_up_minimum_maximum_and_invalid_inputs (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_half_up_minimum_maximum_and_invalid_inputs) ... oktest_lossless_evidence_cache_and_source_preservation (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_lossless_evidence_cache_and_source_preservation) ... oktest_missing_distance_ratios_distributions_and_timer_aliases (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_missing_distance_ratios_distributions_and_timer_aliases) ... oktest_raw_valid_partition_invalid_and_overlap (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_raw_valid_partition_invalid_and_overlap) ... oktest_requested_priority_cap_and_roles (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_requested_priority_cap_and_roles) ... oktest_sampler_empty_sparse_capacity_and_alignment (visual.runtime.test.test_adaptive_node_budget.AdaptiveBudgetTests.test_sampler_empty_sparse_capacity_and_alignment) ... 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) ... oktest_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/tmpc2gp97_0/out/95787f7655d24a54856e7fbdbfacd995Frames 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) ... ok
----------------------------------------------------------------------Ran 42 tests in 0.704s
OK
Artifact postcheck: 121-frame source/pixel/XYZ/all-feature alignment; counts/minimum/capacity/priority/causal/matched totals; role/reference union; timing aliases/residual; HTML local links; source/artifact preservation: PASSFinal document links: 30 PASS; PNG visual review: 9 files; whitespace check: PASS; pre-existing 1226 file hashes: unchanged.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Observation-only adjacent-pixel evidence promoted unchanged from Task 02-C.
These are independent causes, never final structural labels or graph edges."""from dataclasses import dataclassimport numpy as npfrom visual.runtime.geometry import GeometryParametersPARAMETERS = GeometryParameters()
@dataclass(frozen=True)class PairEvidence: shape: tuple pixels: np.ndarray # [P,2] source flat indices, right/down neighbour once supported: np.ndarray # [P,2] unambiguous observed object endpoint mask_boundary: np.ndarray invalid_depth_boundary: np.ndarray # XOR depth validity, not zero-depth jump overlap: np.ndarray # [P,2], ambiguous tracker membership signed_depth_delta_m: np.ndarray # z(second)-z(first), NaN unless both valid depth_jump: np.ndarray normal_angle_deg: np.ndarray # NaN unless both normals available near_endpoint: np.ndarray # local pair endpoint 0/1, -1 unless a depth jump far_endpoint: np.ndarray
def endpoint_mask(self, selected, side=None): result = np.zeros(np.prod(self.shape), bool) for k in (0, 1): keep = selected & self.supported[:, k] if side is not None: keep &= side == k result[self.pixels[keep, k]] = True return result.reshape(self.shape)
def candidates(self, threshold): if not np.isfinite(threshold) or threshold < 0: raise ValueError('angle threshold must be finite and nonnegative') orientation = self.endpoint_mask(self.normal_angle_deg > threshold) depth = self.endpoint_mask(self.depth_jump) return dict(orientation=orientation, depth=depth, union=orientation | depth, occluding=self.endpoint_mask(self.depth_jump, self.near_endpoint), occluded=self.endpoint_mask(self.depth_jump, self.far_endpoint), invalid=self.endpoint_mask(self.invalid_depth_boundary), mask=self.endpoint_mask(self.mask_boundary))
def pair_evidence(geometry, object_id, normals, normal_valid, parameters=PARAMETERS): """Preserve all adjacent pairs touching the raw object mask, even invalids.
Mask transition, invalid depth and overlap flags are independent. An external finite-depth neighbour is retained to determine jump direction. Its XYZ is never included as an object normal support or an object candidate point. """ shape = geometry.valid_depth.shape indices = np.arange(np.prod(shape), dtype=np.int32).reshape(shape) mask = geometry.object_masks[object_id] support = geometry.observed_mask(object_id) parts = [] for a, b in (((slice(None), slice(None, -1)), (slice(None), slice(1, None))), ((slice(None, -1), slice(None)), (slice(1, None), slice(None)))): keep = mask[a] | mask[b] parts.append(np.column_stack((indices[a][keep], indices[b][keep]))) pixels = np.concatenate(parts) valid = geometry.valid_depth.ravel()[pixels] both = valid.all(1) z = geometry.xyz[..., 2].ravel()[pixels] delta = np.full(len(pixels), np.nan, np.float32) delta[both] = z[both, 1]-z[both, 0] jump = np.zeros(len(pixels), bool) jump[both] = np.abs(delta[both]) > (parameters.depth_jump_abs_m + parameters.depth_jump_rel*np.min(z[both], axis=1)) nv = normal_valid.ravel()[pixels].all(1) angles = np.full(len(pixels), np.nan, np.float32) n = normals.reshape(-1, 3)[pixels[nv]] angles[nv] = np.rad2deg(np.arctan2(np.linalg.norm(np.cross(n[:, 0], n[:, 1]), axis=1), np.einsum('ij,ij->i', n[:, 0], n[:, 1]))) near = np.full(len(pixels), -1, np.int8) near[jump] = np.argmin(z[jump], axis=1).astype(np.int8) far = np.where(jump, 1-near, -1).astype(np.int8) return PairEvidence(shape, pixels, support.ravel()[pixels], np.logical_xor(mask.ravel()[pixels[:, 0]], mask.ravel()[pixels[:, 1]]), valid[:, 0] ^ valid[:, 1], geometry.overlap_mask.ravel()[pixels], delta, jump, angles, near, far)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Organized, observation-only NumPy geometry diagnostics (Task 01).
All arrays retain the source (v, u) image layout. This is an internal baseline,not structural classification, sampling, or the final Vision--Graph interface.No RGB values, object GT, erosion, outlier removal, or reconstruction are used."""
from __future__ import annotations
from dataclasses import dataclassfrom time import perf_counter
import numpy as np
from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFrame
@dataclass(frozen=True)class GeometryParameters: """Adjacent z jump > abs + rel * min(z1, z2), in metres.
These are diagnostic baseline thresholds, not edge-classification settings. The same gate prevents a normal stencil from crossing a detected z jump. """
depth_jump_abs_m: float = 0.01 depth_jump_rel: float = 0.02
def __post_init__(self) -> None: values = (self.depth_jump_abs_m, self.depth_jump_rel) if not np.isfinite(values).all() or min(values) < 0: raise ValueError("depth jump thresholds must be finite and nonnegative")
@dataclass(frozen=True)class OrganizedGeometry: """CV-camera XYZ in metres; invalid depth has three NaNs, never a point.
``xyz[v, u]`` corresponds to source pixel centre ``(u+.5, v+.5)``. Finite background geometry is retained, but only ``observed_mask(id)`` may be used as that object's points. Overlapping tracker masks are preserved and marked ambiguous; those pixels are excluded from BOTH object supports. """
xyz: np.ndarray valid_depth: np.ndarray object_masks: dict[int, np.ndarray] overlap_mask: np.ndarray
def observed_mask(self, object_id: int) -> np.ndarray: return self.object_masks[object_id] & self.valid_depth & ~self.overlap_mask
@dataclass(frozen=True)class GeometricFeatures: """Pixel-aligned diagnostics for one object, without semantic edge labels.
Unavailable floating features are NaN and have explicit validity masks. ``depth_jump_m`` compares a supported centre to ANY finite 4-neighbour, including other labels/background; it measures observation discontinuity. Mask, invalid-depth, and image boundaries are separate diagnostic flags. ``mask_boundary`` can include invalid/ambiguous mask pixels: it is NOT a point selection. Geometry selection always requires ``valid_points``. Normal variation is the maximum angle (radians) to supported same-object 4-neighbour normals; even a smooth curved surface can have a large value. """
object_mask: np.ndarray valid_points: np.ndarray normals: np.ndarray normal_valid: np.ndarray depth_jump_m: np.ndarray depth_pair_valid: np.ndarray depth_discontinuity: np.ndarray mask_boundary: np.ndarray depth_validity_boundary: np.ndarray image_boundary: np.ndarray normal_variation_rad: np.ndarray normal_variation_valid: np.ndarray normal_neighbor_count: np.ndarray
@dataclass(frozen=True)class GeometryFrame: source_frame: int camera: str frame_idx: int | None timestamp: float | None geometry: OrganizedGeometry objects: dict[int, GeometricFeatures] timings_ms: dict[str, float]
def build_organized_geometry(frame: TrackedRGBDFrame) -> OrganizedGeometry: """Adapt pointcloud.backproject's pixel-centre equations to dense layout.
Kept NumPy-only rather than importing the legacy plotting/SciPy module. No depth is filtered, filled, smoothed, or selected before feature analysis. """ depth = np.asarray(frame.depth) if depth.ndim != 2 or not min(depth.shape) or not np.issubdtype(depth.dtype, np.floating): raise ValueError("depth must be a nonempty floating point (H,W) array in metres") intrinsic = np.asarray(frame.intrinsic, dtype=np.float64) if (intrinsic.shape != (3, 3) or not np.isfinite(intrinsic).all() or intrinsic[0, 0] <= 0 or intrinsic[1, 1] <= 0): raise ValueError("intrinsic must be finite (3,3) with positive focal lengths") # The legacy equations assume the standard zero-skew CV pinhole intrinsic. if not np.allclose(intrinsic[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1]): raise ValueError("intrinsic must use the standard zero-skew CV pinhole form") if set(frame.masks) - {PEG, BOX}: raise ValueError("unknown output object ID; expected PEG=0 or BOX=1") masks = {} for object_id in (PEG, BOX): mask = np.asarray(frame.masks.get(object_id, np.zeros(depth.shape, dtype=bool))) if mask.shape != depth.shape or mask.dtype != np.bool_: raise ValueError("object masks must be boolean (H,W) arrays matching depth") masks[object_id] = mask.copy() valid = np.isfinite(depth) & (depth > 0) xyz = np.full((*depth.shape, 3), np.nan, dtype=np.float32) v, u = np.nonzero(valid) # Exactly the equations in visual/scripts/pointcloud.py::backproject. z = depth[v, u] xyz[v, u, 0] = (u + 0.5 - intrinsic[0, 2]) * z / intrinsic[0, 0] xyz[v, u, 1] = (v + 0.5 - intrinsic[1, 2]) * z / intrinsic[1, 1] xyz[v, u, 2] = z if not np.isfinite(xyz[valid]).all(): raise ValueError("finite positive depth/intrinsic must yield representable float32 XYZ") return OrganizedGeometry(xyz, valid, masks, masks[PEG] & masks[BOX])
def _pairs(): """Each in-image horizontal/vertical pair once; no wrap or padded neighbours.""" yield (slice(None), slice(None, -1)), (slice(None), slice(1, None)) yield (slice(None, -1), slice(None)), (slice(1, None), slice(None))
def _jump(z1: np.ndarray, z2: np.ndarray, parameters: GeometryParameters) -> np.ndarray: # Inputs have invalid z replaced by zero by callers, avoiding NaN/Inf math. return np.abs(z1 - z2) > ( parameters.depth_jump_abs_m + parameters.depth_jump_rel * np.minimum(z1, z2) )
def estimate_surface_normals( geometry: OrganizedGeometry, object_id: int, parameters: GeometryParameters,) -> tuple[np.ndarray, np.ndarray]: """Central cross product from a full, same-object 5-pixel (+) stencil.
Centre and four neighbours must have unambiguous valid depth, and none of the four centre-to-neighbour pairs may exceed the z-jump gate. No one-sided fallback or extrapolation is performed at holes, mask/image borders, or tiny fragments. Unit normals point towards the camera (n dot XYZ <= 0). """ xyz = geometry.xyz normals = np.full_like(xyz, np.nan) normal_valid = np.zeros(geometry.valid_depth.shape, dtype=bool) if min(normal_valid.shape) < 3: return normals, normal_valid support = geometry.observed_mask(object_id) centre = (slice(1, -1), slice(1, -1)) neighbours = ((slice(1, -1), slice(None, -2)), (slice(1, -1), slice(2, None)), (slice(None, -2), slice(1, -1)), (slice(2, None), slice(1, -1))) usable = support[centre].copy() z = np.where(geometry.valid_depth, xyz[..., 2], 0) for neighbour in neighbours: usable &= support[neighbour] & ~_jump(z[centre], z[neighbour], parameters) # Compute only complete stencils, so invalid XYZ never enters a cross product. v, u = np.nonzero(usable) v, u = v + 1, u + 1 dx = xyz[v, u + 1].astype(np.float64) - xyz[v, u - 1] dy = xyz[v + 1, u].astype(np.float64) - xyz[v - 1, u] cross = np.cross(dx, dy) length = np.linalg.norm(cross, axis=1) good = np.isfinite(length) & (length > 0) v, u, cross = v[good], u[good], cross[good] / length[good, None] cross[np.einsum("ij,ij->i", cross, xyz[v, u]) > 0] *= -1 normals[v, u] = cross.astype(np.float32) normal_valid[v, u] = True return normals, normal_valid
def compute_geometric_features( geometry: OrganizedGeometry, object_id: int, normals: np.ndarray, normal_valid: np.ndarray, parameters: GeometryParameters,) -> GeometricFeatures: """Measure separate 4-neighbour boundary causes and local normal variation.""" mask = geometry.object_masks[object_id] support = geometry.observed_mask(object_id) shape = mask.shape z = np.where(geometry.valid_depth, geometry.xyz[..., 2], 0) jump_m = np.zeros(shape, np.float32) pair_valid = np.zeros(shape, bool) discontinuity = np.zeros(shape, bool) mask_boundary = np.zeros(shape, bool) validity_boundary = np.zeros(shape, bool) variation = np.zeros(shape, np.float32) count = np.zeros(shape, np.uint8) for a, b in _pairs(): both_depth = geometry.valid_depth[a] & geometry.valid_depth[b] dz = np.abs(z[a] - z[b]) jumps = both_depth & _jump(z[a], z[b], parameters) both_normals = normal_valid[a] & normal_valid[b] angle = np.zeros(both_normals.shape, np.float32) n1, n2 = normals[a][both_normals], normals[b][both_normals] # atan2 is stable near zero, including identical rounded float32 normals. angle[both_normals] = np.arctan2( np.linalg.norm(np.cross(n1, n2), axis=1), np.einsum("ij,ij->i", n1, n2) ) for p, q in ((a, b), (b, a)): available = support[p] & both_depth pair_valid[p] |= available np.maximum(jump_m[p], np.where(available, dz, 0), out=jump_m[p]) discontinuity[p] |= support[p] & jumps mask_boundary[p] |= mask[p] & ~mask[q] validity_boundary[p] |= support[p] & ~geometry.valid_depth[q] np.maximum(variation[p], angle, out=variation[p]) count[p] += both_normals jump_m[~pair_valid] = np.nan variation_valid = normal_valid & (count > 0) variation[~variation_valid] = np.nan image_boundary = np.zeros(shape, bool) image_boundary[[0, -1], :] = mask[[0, -1], :] image_boundary[:, [0, -1]] = mask[:, [0, -1]] return GeometricFeatures( object_mask=mask, valid_points=support, normals=normals, normal_valid=normal_valid, depth_jump_m=jump_m, depth_pair_valid=pair_valid, depth_discontinuity=discontinuity, mask_boundary=mask_boundary, depth_validity_boundary=validity_boundary, image_boundary=image_boundary, normal_variation_rad=variation, normal_variation_valid=variation_valid, normal_neighbor_count=count, )
def process_geometry( frame: TrackedRGBDFrame, parameters: GeometryParameters | None = None,) -> GeometryFrame: """Process one current observation; no cache, final classification, or RGB features.""" parameters = parameters or GeometryParameters() start = perf_counter() geometry = build_organized_geometry(frame) after_geometry = perf_counter() normals = {object_id: estimate_surface_normals(geometry, object_id, parameters) for object_id in geometry.object_masks} after_normals = perf_counter() features = {object_id: compute_geometric_features( geometry, object_id, *normals[object_id], parameters, ) for object_id in geometry.object_masks} end = perf_counter() timings = dict(geometry=(after_geometry - start) * 1000, normals=(after_normals - after_geometry) * 1000, discontinuity_features=(end - after_normals) * 1000, total=(end - start) * 1000) return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timings)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745"""Task03-AB: gated CPU offline total-budget ablation; no production changes.
WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03ab-mpl .venv/bin/python -m \ visual.runtime.test.run_adaptive_node_budget --preservation-before PATH"""from __future__ import annotations
import argparsefrom dataclasses import dataclassimport htmlimport jsonfrom numbers import Integralfrom pathlib import Pathimport platformimport shutilimport subprocessfrom time import perf_counter
import numpy as npfrom scipy.ndimage import labelfrom scipy.spatial import cKDTree
from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.edge_evidence import PairEvidencefrom visual.runtime.geometry import GeometricFeatures, GeometryFrame, OrganizedGeometryfrom visual.runtime.rgbd import PEG, BOX, iter_saved_rgbdfrom visual.runtime.sampling import ( SamplingConfig, SamplingEvidence, allocate_budget, extract_candidates, extract_sampling_evidence, sample_points,)from visual.runtime.test.normal_diagnostics import statsfrom visual.runtime.test.run_rim_bottleneck import source_contract, occupancyfrom visual.runtime.test.run_sampling import validate_resultfrom visual.runtime.test.sampling_evaluation import ( CoverageMatcher, TOLERANCES, evaluation_context, score_selection, staged_reference_coverage, summarize,)
REPO = Path(__file__).resolve().parents[3]SOURCE = REPO / 'visual/results/sampling/2551448b0fae4c6bbce3caf48774275f'KEY = 'S3_n256_r0.25_t20_s0'CONDITIONS = ('Fixed256', 'Adaptive', 'FixedMatched')OBJECTS = (('peg', PEG), ('box', BOX))REPRESENTATIVE = (0, 15, 18, 45, 80, 120)FIELDS = ('points', 'pixels_vu', 'flat_index', 'object_id', 'priority_selected', 'depth_priority_selected')TIMERS = ('candidate_selection', 'budget_allocation', 'structural_sampling', 'surface_fps')
def write_json(path, value): Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + '\n', encoding='utf-8')
def distribution(values): a = np.asarray([x for x in values if x is not None], float) a = a[np.isfinite(a)] return dict(stats(a), min=float(a.min()) if len(a) else None)
def ratio(n, d): return n / d if d else None
def support_counts(counts): if len(counts) != 2 or any(not isinstance(x, Integral) or isinstance(x, (bool, np.bool_)) or x < 0 for x in counts): raise ValueError('two nonnegative integer support counts required') return tuple(int(x) for x in counts)
def requested_budget(counts, reference): """Only current support counts and an immutable past/current reference.""" counts = support_counts(counts) area = sum(counts) minimums = tuple(min(16, x) for x in counts) if reference is None: if area: raise ValueError('positive support requires initialized reference') return 0, minimums if not isinstance(reference, Integral) or reference <= 0: raise ValueError('reference must be a positive integer') rounded = (512 * area + int(reference)) // (2 * int(reference)) return min(256, max(sum(minimums), rounded)), minimums
@dataclassclass AreaBudget: reference: int | None = None reference_source: int | None = None
def step(self, counts, source): counts = support_counts(counts) if self.reference is None and sum(counts): self.reference, self.reference_source = sum(counts), int(source) return requested_budget(counts, self.reference)
def matched_budget(areas, requests): """One offline matched-count control, selected without geometry scores.""" if len(areas) != len(requests) or not len(areas): raise ValueError('aligned nonempty counts required') target = sum(min(int(a), int(n)) for a, n in zip(areas, requests)) b = min(range(32, 257), key=lambda n: (abs(sum(min(n, int(a)) for a in areas) - target), n)) actual = sum(min(b, int(a)) for a in areas) return dict(budget=b, adaptive_selected_sum=target, fixed_selected_sum=actual, mean_error_nodes=(actual-target)/len(areas), causal_online=False, selection='count-only absolute total difference; smaller integer on ties')
def measure_areas(frame, geometry): """Validity count cost and diagnostic raw-mask scans are separate.""" t0 = perf_counter() counts = tuple(int(np.count_nonzero(geometry.observed_mask(oid))) for _, oid in OBJECTS) count_ms = (perf_counter()-t0)*1000 t0 = perf_counter() result = {} for (name, oid), valid in zip(OBJECTS, counts): mask = frame.masks[oid] raw = int(np.count_nonzero(mask)) invalid = int(np.count_nonzero(mask & ~geometry.valid_depth)) overlap = int(np.count_nonzero(mask & geometry.valid_depth & geometry.overlap_mask)) if raw != valid + invalid + overlap: raise AssertionError('raw/valid exclusion partition') result[name] = dict(raw=raw, valid=valid, invalid_depth=invalid, positive_depth_overlap=overlap, minimum=min(16, valid)) raw_ms = (perf_counter()-t0)*1000 return result, count_ms, raw_ms
def exact_result(first, second): for field in FIELDS: np.testing.assert_array_equal(getattr(first, field), getattr(second, field), err_msg=field) if set(first.metadata) != set(second.metadata): raise AssertionError('feature field mismatch') for field in first.metadata: np.testing.assert_array_equal(first.metadata[field], second.metadata[field], err_msg=field) if first.counts != second.counts or first.object_budgets != second.object_budgets: raise AssertionError('selection counts mismatch')
def exact_saved(result, archive, key=KEY): for field in FIELDS: np.testing.assert_array_equal(getattr(result, field), archive[f'{key}/{field}'], err_msg=field) saved = {n.split('/metadata/')[1] for n in archive.files if n.startswith(key+'/metadata/')} if saved != set(result.metadata): raise AssertionError('available feature fields mismatch') for field in result.metadata: np.testing.assert_array_equal(result.metadata[field], archive[f'{key}/metadata/{field}'], err_msg=field)
def validate_selection(result, evidence, config, candidates): validate_result(result, evidence, config) counts = [len(candidates[i].points) for _, i in OBJECTS] expected = allocate_budget(config.num_points, counts, config.min_points, counts) np.testing.assert_array_equal([result.object_budgets[i] for _, i in OBJECTS], expected) if len(result.points) != min(config.num_points, sum(counts)): raise AssertionError('selected total differs from capacity-limited request') if len(np.unique(result.points, axis=0)) != len(result.points): raise AssertionError('duplicate XYZ') for _, oid in OBJECTS: keep = result.object_id == oid rows = np.searchsorted(candidates[oid].flat_index, result.flat_index[keep]) for field, values in result.metadata.items(): np.testing.assert_array_equal(values[keep], candidates[oid].metadata[field][rows], err_msg=field) c = result.counts[oid] if c['selected'] != c['priority'] + c['surface_fps'] or c['depth_priority']: raise AssertionError('S3 role accounting')
def save_evidence(path, evidence): """Lossless temporary observation cache: global gate before any ablation.""" f = evidence.frame g = f.geometry a = dict(xyz=g.xyz, valid_depth=g.valid_depth, overlap=g.overlap_mask) for _, oid in OBJECTS: a[f'mask/{oid}'] = g.object_masks[oid] for field in GeometricFeatures.__dataclass_fields__: a[f'feature/{oid}/{field}'] = getattr(f.objects[oid], field) for field in PairEvidence.__dataclass_fields__: a[f'pair/{oid}/{field}'] = np.asarray(getattr(evidence.pairs[oid], field)) a['provenance'] = np.array(json.dumps(dict(source_frame=f.source_frame, camera=f.camera, frame_idx=f.frame_idx, timestamp=f.timestamp, timings_ms=evidence.timings_ms))) np.savez_compressed(path, **a)
def load_evidence(path): with np.load(path, allow_pickle=False) as a: p = json.loads(str(a['provenance'])) g = OrganizedGeometry(a['xyz'], a['valid_depth'], {i:a[f'mask/{i}'] for _, i in OBJECTS}, a['overlap']) features = {i:GeometricFeatures(**{k:a[f'feature/{i}/{k}'] for k in GeometricFeatures.__dataclass_fields__}) for _, i in OBJECTS} pairs = {i:PairEvidence(**{k:tuple(a[f'pair/{i}/{k}']) if k == 'shape' else a[f'pair/{i}/{k}'] for k in PairEvidence.__dataclass_fields__}) for _, i in OBJECTS} f = GeometryFrame(p['source_frame'], p['camera'], p['frame_idx'], p['timestamp'], g, features, p['timings_ms']) return SamplingEvidence(f, pairs, 'pca5', p['timings_ms'])
def nearest(source, target): if not len(source): return np.empty(0) return cKDTree(target).query(source)[0]*1000 if len(target) else np.full(len(source), np.nan)
def distance_summary(distances): finite = np.isfinite(distances) return dict(distance_mm=distribution(distances), source_count=len(distances), missing_count=int((~finite).sum()), within_3mm=int((distances[finite] <= 3).sum()), coverage_3mm=ratio(int((distances[finite] <= 3).sum()), len(distances)))
def general_geometry(frame, evidence, candidates, sample, context): report, arrays = {}, {} g = evidence.frame.geometry for name, oid in OBJECTS: obj = candidates[oid] x = obj.flat_index c = x[obj.metadata['structural_candidate']] chosen = sample.object_id == oid f = sample.flat_index[chosen] p = sample.flat_index[chosen & sample.priority_selected] s = sample.flat_index[chosen & ~sample.priority_selected] xyz = g.xyz.reshape(-1, 3) xf, cp = nearest(xyz[x], xyz[f]), nearest(xyz[c], xyz[p]) components, count = label(g.observed_mask(oid)) component_rows = [] component_index = components.ravel() for k in range(1, count+1): keep = component_index[x] == k nc, np_, nf = (int((component_index[v] == k).sum()) for v in (c, p, f)) component_rows.append(dict(id=k, support=int(keep.sum()), candidate=nc, priority=np_, final=nf, small=bool(keep.sum() <= 64), candidate_without_priority=bool(nc and not np_), candidate_without_final=bool(nc and not nf), **distance_summary(xf[keep]))) paths = dict(X=x, C=c, P=p, S=s, F=f) stages = staged_reference_coverage(context['matchers'][name], c, p, s, f) depth = occupancy(frame, paths, context['negatives'][name]) report[name] = dict(x_to_f=distance_summary(xf), c_to_p=distance_summary(cp), components=component_rows, stages=stages, occupancy=depth, camera_range_m=distribution(np.linalg.norm(xyz[x].astype(float), axis=1))) arrays[name+'/c_to_p'] = cp arrays[name+'/x_to_f'] = xf return report, arrays
def sampling_timing(sample): t = {k:float(sample.timings_ms[k]) for k in (*TIMERS, 'sampling_total')} t['gather_packaging_and_other_overhead'] = t['sampling_total']-sum(t[k] for k in TIMERS) if t['gather_packaging_and_other_overhead'] < -1e-9: raise AssertionError('negative timer residual') return t
def latency_summary(records): result = {} for condition in CONDITIONS: rows = [r for r in records if r['condition'] == condition] per_frame, effective, executed = {}, {}, {} for r in rows: owner = next(x for x in records if x['source_frame'] == r['source_frame'] and x['repeat'] == r['repeat'] and x['condition'] == (r['alias_of'] or condition)) for key, value in owner['timings_ms'].items(): effective.setdefault(key, []).append(value) per_frame.setdefault(key, {}).setdefault(r['source_frame'], []).append(value) if r['executed']: executed.setdefault(key, []).append(value) result[condition] = dict(executed_calls=sum(r['executed'] for r in rows), alias_calls=sum(not r['executed'] for r in rows), frame_median_then_distribution={k:distribution([np.median(v) for v in frames.values()]) for k, frames in per_frame.items()}, all_repetitions_effective_including_explicit_alias={k:distribution(v) for k,v in effective.items()}, executed_only={k:distribution(v) for k,v in executed.items()}) return result
def preserve_check(before): changed = [name for name, expected in before['sha256'].items() if not (REPO/name).is_file() or digests(REPO/name)[1] != expected] return dict(checked_files=len(before['sha256']), changed_or_missing=changed, unchanged=not changed)
def add_temporal_and_pairs(rows): for index, row in enumerate(rows): if row['source_frame'] != index: raise AssertionError('source frame continuity') for condition, data in row['conditions'].items(): previous = rows[index-1]['conditions'][condition] if index else None for field in ('requested', 'selected'): delta = data[field]-previous[field] if previous else None data['delta_'+field] = delta data['abs_delta_'+field] = abs(delta) if delta is not None else None fixed = row['conditions']['Fixed256']['selected'] data['node_reduction_vs_fixed256'] = 1-data['selected']/fixed if fixed else None for name, _ in OBJECTS: base = row['conditions']['Fixed256']['geometry']['objects'][name] current = data['geometry']['objects'][name] f, a = (v['structural']['tolerance']['2px_3mm']['sampling_retention'] for v in (base, current)) data['objects'][name]['retention_difference_pp_vs_fixed256'] = (a-f)*100 if a is not None and f is not None else None for field in ('mean', 'p95'): f, a = (v['surface']['all']['distance_mm'][field] for v in (base, current)) data['objects'][name]['surface_'+field+'_difference_mm_vs_fixed256'] = a-f if a is not None and f is not None else None
def make_summary(rows, pools, distance_pools, matched, policy): summary = {} fixed_sum = sum(r['conditions']['Fixed256']['selected'] for r in rows) for condition in CONDITIONS: geometry = summarize(pools[condition], distance_pools[condition]) geometry.pop('timings_ms', None) # timings are paired separately, with explicit aliases counts = {field:distribution([r['conditions'][condition][field] for r in rows]) for field in ('requested', 'selected', 'priority', 'surface', 'shortfall', 'delta_requested', 'delta_selected', 'abs_delta_selected')} selected = sum(r['conditions'][condition]['selected'] for r in rows) objects = {} for name, _ in OBJECTS: objects[name] = dict( allocated=distribution([r['conditions'][condition]['objects'][name]['allocated'] for r in rows]), selected=distribution([r['conditions'][condition]['objects'][name]['selected'] for r in rows]), density_per_valid_pixel=distribution([r['conditions'][condition]['objects'][name]['density_per_valid_pixel'] for r in rows]), retention_difference_pp=distribution([r['conditions'][condition]['objects'][name]['retention_difference_pp_vs_fixed256'] for r in rows]), c_to_p_mm=distribution(np.concatenate(distance_pools[condition][name+'/c_to_p']))) summary[condition] = dict(counts=counts, selected_sum=selected, node_reduction_fraction=1-selected/fixed_sum, geometry=geometry, objects=objects, requested_max_frames=[r['source_frame'] for r in rows if r['conditions'][condition]['requested'] == 256], requested_min_frames=[r['source_frame'] for r in rows if r['conditions'][condition]['requested'] == r['minimum_total']]) area = [sum(r['areas'][name]['valid'] for name, _ in OBJECTS) for r in rows] median_area = float(np.median(area)) strata = {} for title, ids in [('area_le_median',[i for i,a in enumerate(area) if a <= median_area]), ('area_gt_median',[i for i,a in enumerate(area) if a > median_area]), ('box_support_zero',[i for i,r in enumerate(rows) if not r['areas']['box']['valid']])]: strata[title] = dict(source_frames=ids, objects={name:distribution([ rows[i]['conditions']['Adaptive']['objects'][name]['retention_difference_pp_vs_fixed256'] for i in ids]) for name, _ in OBJECTS}) return dict(conditions=summary, matched=matched, policy=dict(alpha=1, reference=policy.reference, reference_source=policy.reference_source, rounding='integer half-up', maximum=256, minimum='sum min(16, current object support)'), area_strata=dict(median_valid_area=median_area, strata=strata))
def plot_results(output, rows, latency): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt colors = dict(Fixed256='#64748b', Adaptive='#e76f51', FixedMatched='#247ba0') x = np.arange(len(rows)) plotdir = output/'plots' plotdir.mkdir(exist_ok=True) def finish(fig, axes, filename): for ax in np.asarray(axes).ravel(): for lo, hi in ((18,26),(56,65)): if ax.get_xlabel() == 'Source frame': ax.axvspan(lo-.5,hi+.5,color='#cbd5e1',alpha=.4) ax.grid(alpha=.2) ax.legend(fontsize=7, loc='best') fig.savefig(plotdir/filename, dpi=140) plt.close(fig) fig, axes = plt.subplots(4,1,figsize=(15,12),layout='constrained') for name, _ in OBJECTS: for field, ls in [('raw','--'),('valid','-')]: axes[0].plot(x,[r['areas'][name][field] for r in rows],ls,label=name+' '+field) for condition in CONDITIONS: axes[1].plot(x,[r['conditions'][condition]['selected'] for r in rows],label=condition,color=colors[condition]) for name, ls in [('peg','-'),('box','--')]: axes[2].plot(x,[r['conditions'][condition]['objects'][name]['allocated'] for r in rows],ls, label=condition+' '+name,color=colors[condition]) for field, ls in [('priority','-'),('surface','--')]: axes[3].plot(x,[r['conditions'][condition][field] for r in rows],ls,label=condition+' '+field,color=colors[condition]) for ax,title in zip(axes,['Raw / valid projected pixel areas','Actual point nodes','Object allocated budgets','Priority / Surface roles']): ax.set(title=title,xlabel='Source frame') finish(fig,axes,'budget_timeseries.png') fig, axes = plt.subplots(2,3,figsize=(17,9),layout='constrained') area = [sum(r['areas'][n]['valid'] for n,_ in OBJECTS) for r in rows] reduction = [r['conditions']['Adaptive']['node_reduction_vs_fixed256']*100 for r in rows] for col,(name,_) in enumerate(OBJECTS): for condition in CONDITIONS: retention = [r['conditions'][condition]['geometry']['objects'][name]['structural']['tolerance']['2px_3mm']['sampling_retention'] for r in rows] axes[0,col].scatter(reduction,retention,s=10,label=condition,color=colors[condition],alpha=.7) axes[1,col].plot(x,[r['conditions'][condition]['geometry']['objects'][name]['surface']['all']['distance_mm']['p95'] for r in rows], label=condition,color=colors[condition]) axes[0,col].set(title=name+' retention vs Adaptive node reduction',xlabel='Adaptive node reduction (%)',ylabel='Observable reference retention') axes[1,col].set(title=name+' X to F p95 distance',xlabel='Source frame',ylabel='mm') for condition in CONDITIONS: axes[0,2].scatter(area,[r['conditions'][condition]['selected'] for r in rows],s=12,label=condition,color=colors[condition]) axes[0,2].set(title='Area / node relationship (cap 256)',xlabel='Valid projected pixels',ylabel='Actual nodes',ylim=(0,270)) axes[1,2].plot(x,[r['conditions']['Adaptive']['delta_selected'] for r in rows],label='Adaptive signed delta') axes[1,2].plot(x,[r['conditions']['Adaptive']['abs_delta_selected'] for r in rows],label='Adaptive abs delta') axes[1,2].set(title='Temporal node changes',xlabel='Source frame',ylabel='Nodes / frame') finish(fig,axes,'preservation_temporal.png') fig, axes = plt.subplots(2,2,figsize=(15,9),layout='constrained') for condition in CONDITIONS: ys = [np.median([next(t for t in latency if t['source_frame']==r['source_frame'] and t['repeat']==rep and t['condition']==(next(z for z in latency if z['source_frame']==r['source_frame'] and z['repeat']==rep and z['condition']==condition)['alias_of'] or condition))['timings_ms']['sampling_total'] for rep in range(3)]) for r in rows] axes[0,0].plot(x,ys,label=condition,color=colors[condition]) axes[0,1].scatter([r['conditions'][condition]['selected'] for r in rows],ys,s=12,label=condition,color=colors[condition]) axes[0,0].set(title='Paired sampling (frame median; aliases explicit in JSON)',xlabel='Source frame',ylabel='ms') axes[0,1].set(title='Selected nodes / actual measured selection latency',xlabel='Actual nodes',ylabel='ms') for name,_ in OBJECTS: axes[1,0].plot(x,[r['conditions']['Adaptive']['general'][name]['occupancy']['depth_m']['X']['median'] for r in rows],label=name+' median z') axes[1,1].scatter([r['areas'][name]['valid'] for r in rows], [r['conditions']['Adaptive']['objects'][name]['retention_difference_pp_vs_fixed256'] for r in rows],s=15,label=name) axes[1,0].set(title='Observed depth; contamination retained',xlabel='Source frame',ylabel='Camera z (m)') axes[1,1].set(title='Small masks / sampling retention loss',xlabel='Valid projected pixels',ylabel='Adaptive - Fixed256 (pp)') finish(fig,axes,'latency_depth.png')
def overlay(output, frame, candidates, samples, context): import matplotlib.pyplot as plt h,w = frame.depth.shape fig,axes = plt.subplots(3,3,figsize=(15,13),layout='constrained') for row, oid in enumerate((None, PEG, BOX)): union = frame.masks[PEG] | frame.masks[BOX] if oid is None else frame.masks[oid] v,u = np.nonzero(union) limits = (max(0,int(u.min())-10),min(w-1,int(u.max())+10),min(h-1,int(v.max())+10),max(0,int(v.min())-10)) if len(u) else (0,w-1,h-1,0) for col,condition in enumerate(CONDITIONS): ax=axes[row,col]; ax.imshow(frame.rgb) for name,i in OBJECTS: if oid is not None and oid != i: continue mask=frame.masks[i] if mask.any() and not mask.all(): ax.contour(mask,[.5],colors=['#69ff72'],linewidths=.5) flat=candidates[i].flat_index[candidates[i].metadata['structural_candidate']] cv,cu=np.unravel_index(flat,(h,w));ax.scatter(cu,cv,s=2,c='#ff5d41',alpha=.45) uv=context['references'][name][0];ax.scatter(uv[:,0],uv[:,1],s=12,c='#ff65cc',marker='+',linewidths=.4) s=samples[condition] keep=np.ones(len(s.points),bool) if oid is None else s.object_id==oid for priority,color,marker,size in [(False,'#00d9ff','o',9),(True,'#ffff00','*',24)]: pv,pu=s.pixels_vu[keep & (s.priority_selected==priority)].T ax.scatter(pu,pv,s=size,c=color,marker=marker,edgecolors='black',linewidths=.2) ax.set(xlim=limits[:2],ylim=limits[2:],title=f'{condition} | {"All" if oid is None else ("Peg" if oid==PEG else "Box")} N={int(keep.sum())}') ax.axis('off') fig.suptitle(f'Source {frame.source_frame} | same crop per row | yellow=Priority, cyan=Surface, red=candidate, pink=GT eval\nMasks may be contaminated; absent object remains empty. No padding.') fig.savefig(output/'frames'/f'f{frame.source_frame:04d}_overlay.png',dpi=140);plt.close(fig)
def html_report(output, data, rows): def value(v): return 'N/A' if v is None else f'{v:.3f}' summary=[] for condition,s in data['conditions'].items(): g=s['geometry']['objects'] summary.append('<tr>'+''.join(f'<td>{html.escape(str(v))}</td>' for v in [condition, value(s['counts']['selected']['mean']), value(s['counts']['selected']['p50']), value(100*s['node_reduction_fraction']), value(100*g['peg']['structural']['2px_3mm']['sampling_retention']), value(100*g['box']['structural']['2px_3mm']['sampling_retention']), value(g['peg']['surface']['all']['distance_mm']['p95']), value(g['box']['surface']['all']['distance_mm']['p95'])])+'</tr>') table=[] for r in rows: source=r['source_frame'] links=f'<a href="frames/f{source:04d}_samples.npz">NPZ</a>' if source in REPRESENTATIVE: links+=f' <a href="frames/f{source:04d}_overlay.png">overlay</a>' table.append('<tr>'+''.join(f'<td>{v}</td>' for v in [source, r['areas']['peg']['raw'],r['areas']['peg']['valid'],r['areas']['box']['raw'],r['areas']['box']['valid'], *[r['conditions'][c]['selected'] for c in CONDITIONS],links])+'</tr>') plots=''.join(f'<a href="plots/{p.name}"><img src="plots/{p.name}" alt="{p.stem}"></a>' for p in sorted((output/'plots').glob('*.png'))) images=''.join(f'<a href="frames/f{s:04d}_overlay.png"><img src="frames/f{s:04d}_overlay.png" alt="Source {s}"></a>' for s in REPRESENTATIVE) dependencies=''.join(f'<li><a href="{html.escape(v)}">{html.escape(k)}</a></li>' for k,v in data['dependency_links'].items()) (output/'adaptive_node_budget.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><title>Task03-AB adaptive total node budget</title><style>body{font:15px system-ui;max-width:1500px;margin:28px auto;padding:0 16px;color:#17212b}img{width:100%;margin:15px 0}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{padding:7px;border:1px solid #ccd3da;text-align:right}th:first-child,td:first-child{text-align:left}pre{white-space:pre-wrap}a{color:#146cb2}</style><h1>Task03-AB — Adaptive Total Node Budget</h1>'''+f'<p>Run {data["run_id"]}. CPU only; ep000 source 0–120. All 121-frame gates passed before adaptive geometry evaluation.</p>' +'<p>First positive valid support fixes the causal reference. Pixel area is projected area, not physical 3D surface area. FixedMatched uses episode counts offline. Same S3 / 20° / .25 / seed0 / 3D FPS; Priority cap changes with requested budget.</p>' +'<p>Joint matcher: the same pair within 2px AND 3mm. Retention denominator is tracker-observable references. N/A is preserved. Gray bands mark recorded Box support loss, not independently proven occlusion. Sampling latency excludes PCA5 extraction, GT and I/O; aliases have no invented FPS calls. No GNN/BC, stale-cache integration, GPU or end-to-end 20Hz claim.</p>' +'<p><a href="adaptive_node_budget.json">Summary/config</a> · <a href="frame_metrics.json">All frame metrics</a> · <a href="latency.json">Raw/aggregated timing</a> · <a href="verification.json">Gates/preservation</a> · <a href="tests.log">Tests</a> · <a href="implementation.patch">Implementation diff</a></p>' +'<table><tr><th>Condition</th><th>Mean N</th><th>Median N</th><th>Reduction %</th><th>Peg retention %</th><th>Box retention %</th><th>Peg surface p95 mm</th><th>Box surface p95 mm</th></tr>'+''.join(summary)+'</table>' +plots+'<h2>Representative frames</h2>'+images+'<h2>All frame artifacts</h2><table><tr><th>Source</th><th>Peg raw</th><th>Peg valid</th><th>Box raw</th><th>Box valid</th><th>Fixed256</th><th>Adaptive</th><th>FixedMatched</th><th>Files</th></tr>'+''.join(table)+'</table>' +'<h2>Original read-only dependencies</h2><ul>'+dependencies+'</ul><details><summary>Policy / reference / matched control</summary><pre>' +html.escape(json.dumps(dict(policy=data['policy'],reference=data['reference_camera'],matched=data['matched']),indent=2))+'</pre></details></html>',encoding='utf-8')
def evaluate(preservation_before, tests_log=None): source=SOURCE original=json.loads((source/'comparison.json').read_text()) cfg=original['config'] episode=REPO/'visual/data/step2/ep000.npz' masks=REPO/'visual/results/runtime_tracking/ep000/masks.npz' camera='base_camera' saved=[json.loads((source/f'f{i:04d}_metrics.json').read_text())[KEY] for i in range(121)] counts=[tuple(r['objects'][n]['counts']['observed'] for n,_ in OBJECTS) for r in saved] policy=AreaBudget() planned=[policy.step(c,i)[0] for i,c in enumerate(counts)] matched=matched_budget([sum(c) for c in counts],planned) config=dict(task='03-AB', source_run_id=original['run_id'], input=str(episode), masks=str(masks), camera=camera, alpha=1, maximum=256, minimum_per_object=16, matched=matched, reference=policy.reference, reference_source=policy.reference_source, baseline=KEY, tolerances=TOLERANCES, seed=0, device='cpu', independent_episode=False, timing_repetitions=3, extraction='once per frame; lossless cache to enforce all-frame gates first', policy_inputs='current observed support counts and fixed first-positive reference only', python=platform.python_version(), numpy=np.__version__, platform=platform.platform()) with ExperimentLogger(team='visual',config=config,seed=0,model='task03ab_adaptive_node_budget',job_type='evaluate') as logger: output=logger.directory print('Output:',output,flush=True) for p in ('cache','frames','evaluated_source'): (output/p).mkdir() before=json.loads(Path(preservation_before).read_text()) write_json(output/'preservation_before.json',before) verification=dict(gates_passed=False,adaptive_geometry_executed=False,frame_gates=[], primary_tolerance='same pair 2px AND 3mm') try: for path, expected in ((episode,cfg['input_sha256']),(masks,cfg['masks_sha256'])): if digests(path)[1] != expected: raise AssertionError('input hash mismatch: '+str(path)) verification['input_hashes']={str(p.relative_to(REPO)):digests(p)[1] for p in (episode,masks)} verification['source_contract']=source_contract(source,cfg) with np.load(masks,allow_pickle=False) as ar: np.testing.assert_array_equal(ar['source_frame'],np.arange(121)) tracking=json.loads(masks.with_name('tracking.json').read_text()) if tracking['camera'] != camera: raise AssertionError('tracker camera mismatch') if digests(Path(tracking['input']))[1] != cfg['input_sha256']: raise AssertionError('tracker input provenance mismatch') if TOLERANCES != ((1.,.002),(2.,.003),(3.,.005)): raise AssertionError('joint tolerances changed') for relative in (*cfg['source_sha256'], 'visual/runtime/test/run_rim_bottleneck.py', 'visual/runtime/test/run_adaptive_node_budget.py', 'visual/runtime/test/test_adaptive_node_budget.py'): dest=output/'evaluated_source'/relative dest.parent.mkdir(parents=True,exist_ok=True) shutil.copyfile(REPO/relative,dest) patch='' for relative in ('visual/runtime/test/run_adaptive_node_budget.py','visual/runtime/test/test_adaptive_node_budget.py'): proc=subprocess.run(['git','diff','--no-index','--','/dev/null',relative],cwd=REPO,capture_output=True,text=True) patch+=proc.stdout (output/'implementation.patch').write_text(patch) if tests_log: shutil.copyfile(tests_log,output/'tests.log') required=[f'{camera}/seg','peg_id','box_id','peg_pose','box_pose','box_hole_pose','peg_half_sizes','box_hole_radii','seed'] with np.load(episode,allow_pickle=False) as ar: if len(ar[f'{camera}/depth']) != 121: raise AssertionError('episode frame count') gt={k:ar[k] for k in required} # never supplied to the budget helper or sampler robot_ids=cfg['robot_ids'] pools={c:[] for c in CONDITIONS} distance_pools={c:{} for c in CONDITIONS} gate_rows=[] reference_camera=None for index,frame in enumerate(iter_saved_rgbd(episode,masks,camera=camera)): if frame.source_frame != index: raise AssertionError('source mapping') evidence=extract_sampling_evidence(frame,'pca5') candidates=extract_candidates(evidence,SamplingConfig(),'S3') areas,count_ms,raw_ms=measure_areas(frame,evidence.frame.geometry) actual=tuple(areas[n]['valid'] for n,_ in OBJECTS) if actual != counts[index]: raise AssertionError('observed count mismatch') fixed=sample_points(evidence,SamplingConfig(),method='S3') validate_selection(fixed,evidence,SamplingConfig(),candidates) with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as archive: if int(archive['source_frame']) != index: raise AssertionError('archive source mapping') np.testing.assert_array_equal(archive['shape'],frame.depth.shape) for _,oid in OBJECTS: c=candidates[oid] np.testing.assert_array_equal(c.flat_index[c.metadata['structural_candidate']], archive[f'evidence/pca5/{oid}/20/orientation_flat']) exact_saved(fixed,archive) context=evaluation_context(frame,evidence,gt,camera,robot_ids) for name,oid in OBJECTS: reference=tuple(archive[f'evaluation/{name}/reference_{s}'] for s in ('uv','xyz')) for a,b in zip(reference,context['references'][name]): np.testing.assert_array_equal(a,b) context['references'][name]=reference context['matchers'][name]=CoverageMatcher(evidence.frame.geometry,oid,reference) score,dist=score_selection(fixed,context) np.testing.assert_equal(score['objects'],saved[index]['objects']) score['source_frame']=index pools['Fixed256'].append(score) for k,v in dist.items(): distance_pools['Fixed256'].setdefault(k,[]).append(v.astype(np.float32)) save_evidence(output/'cache'/f'f{index:04d}_evidence.npz',evidence) gate_rows.append(dict(source_frame=index,areas=areas,support_count_ms=count_ms, raw_area_diagnostics_ms=raw_ms,extraction_ms=evidence.timings_ms)) if index == policy.reference_source: reference_camera=dict(source_frame=index,frame_idx=frame.frame_idx,timestamp=frame.timestamp, shape=list(frame.depth.shape),camera=camera,intrinsic=frame.intrinsic.tolist(), cam2world=frame.cam2world.tolist(),areas=areas,unit='projected pixel count') verification['frame_gates'].append(dict(source_frame=index,support_exact=True,candidate_exact=True, fixed256_all_fields_exact=True,reference_exact=True,fixed256_original_metrics_exact=True)) if index%15 == 0: print(f'Gate {index+1}/121: support/candidates/selection/features/reference/metrics exact',flush=True) if len(verification['frame_gates']) != 121: raise AssertionError('all-frame gate incomplete') verification['gates_passed']=True write_json(output/'verification.json',verification) print('All 121 gates passed. Starting paired ablation.',flush=True) except Exception as exc: verification['failure']=dict(type=type(exc).__name__,message=str(exc)) write_json(output/'verification.json',verification) (output/'adaptive_node_budget.html').write_text('<!doctype html><meta charset="utf-8"><h1>Gate failed; adaptive geometry NOT RUN</h1><a href="verification.json">Verification</a>') raise
rows=[];timings=[];actual_policy=AreaBudget();warmups=[] for index,frame in enumerate(iter_saved_rgbd(episode,masks,camera=camera)): evidence=load_evidence(output/'cache'/f'f{index:04d}_evidence.npz') candidates=extract_candidates(evidence,SamplingConfig(),'S3') area=gate_rows[index]['areas'] current_counts=tuple(area[n]['valid'] for n,_ in OBJECTS) request,minimums=actual_policy.step(current_counts,index) if request != planned[index]: raise AssertionError('causal policy differs from count-only planning') configs=dict(Fixed256=SamplingConfig(),Adaptive=SamplingConfig(num_points=request,min_points=minimums), FixedMatched=SamplingConfig(num_points=matched['budget'])) owner={};unique={} for condition,c in configs.items(): signature=(c.num_points,tuple(min(m,a) for m,a in zip(c.min_points,current_counts))) owner[condition]=unique.setdefault(signature,condition) names=list(dict.fromkeys(owner.values())) if index == 0: for condition in names: sample_points(evidence,configs[condition],method='S3') warmups.append(dict(condition=condition,source_frame=0,measured=False)) selected={} budget_times=[] for repeat in range(3): start=perf_counter();check=requested_budget(current_counts,actual_policy.reference) budget_times.append((perf_counter()-start)*1000) if check != (request,minimums): raise AssertionError('deterministic budget') order=names[(index+repeat)%len(names):]+names[:(index+repeat)%len(names)] for condition in order: sample=sample_points(evidence,configs[condition],method='S3') measured=sampling_timing(sample) validate_selection(sample,evidence,configs[condition],candidates) if repeat: exact_result(sample,selected[condition]) else: selected[condition]=sample timings.append(dict(source_frame=index,repeat=repeat,condition=condition,executed=True, alias_of=None,order=order,timings_ms=measured)) for condition in CONDITIONS: if owner[condition] != condition: timings.append(dict(source_frame=index,repeat=repeat,condition=condition,executed=False, alias_of=owner[condition],timings_ms=None)) results={c:selected[owner[c]] for c in CONDITIONS} with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as ar: exact_saved(results['Fixed256'],ar) if request == 256: exact_saved(results['Adaptive'],ar) # No GT is supplied until all selections and deterministic checks are complete. context=evaluation_context(frame,evidence,gt,camera,robot_ids) with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as ar: for name,oid in OBJECTS: reference=tuple(ar[f'evaluation/{name}/reference_{s}'] for s in ('uv','xyz')) for a,b in zip(reference,context['references'][name]): np.testing.assert_array_equal(a,b) context['references'][name]=reference context['matchers'][name]=CoverageMatcher(evidence.frame.geometry,oid,reference) row=dict(gate_rows[index],minimum_total=sum(minimums),adaptive_budget_ms=budget_times, intrinsic=frame.intrinsic.tolist(),cam2world=frame.cam2world.tolist(),conditions={}) archive=dict(source_frame=np.array(index),shape=np.array(frame.depth.shape)) for name,oid in OBJECTS: c=candidates[oid] archive[f'support/{name}/flat_index']=c.flat_index archive[f'support/{name}/xyz']=c.points archive[f'candidate/{name}/flat_index']=c.flat_index[c.metadata['structural_candidate']] archive[f'candidate/{name}/xyz']=c.points[c.metadata['structural_candidate']] for suffix,a in zip(('uv','xyz'),context['references'][name]): archive[f'evaluation/{name}/reference_{suffix}']=a for condition,sample in results.items(): if condition == 'Fixed256': score=pools['Fixed256'][index] else: score,dist=score_selection(sample,context);score['source_frame']=index pools[condition].append(score) for k,v in dist.items(): distance_pools[condition].setdefault(k,[]).append(v.astype(np.float32)) general,dist=general_geometry(frame,evidence,candidates,sample,context) for k,v in dist.items(): distance_pools[condition].setdefault(k,[]).append(v.astype(np.float32)) object_rows={} for name,oid in OBJECTS: c=sample.counts[oid] object_rows[name]=dict(allocated=c['budget'],selected=c['selected'],priority=c['priority'], surface=c['surface_fps'],candidates=c['candidates'],selected_candidates=c['selected_candidates'], shortfall=c['budget']-c['selected'],minimum_support_shortfall=max(0,16-area[name]['valid']), density_per_valid_pixel=ratio(c['selected'],area[name]['valid']), density_per_raw_pixel=ratio(c['selected'],area[name]['raw'])) n=configs[condition].num_points row['conditions'][condition]=dict(requested=n,selected=len(sample.points), allocated_total=sum(sample.object_budgets.values()),priority=int(sample.priority_selected.sum()), surface=int((~sample.priority_selected).sum()),priority_cap=n//4, shortfall=n-len(sample.points),maximum_saturated=n==256,minimum_saturated=n==sum(minimums), alias_of=owner[condition] if owner[condition]!=condition else None, objects=object_rows,geometry=score,general=general) for field in FIELDS: archive[f'{condition}/{field}']=getattr(sample,field) for field,a in sample.metadata.items(): archive[f'{condition}/metadata/{field}']=a rows.append(row) np.savez_compressed(output/'frames'/f'f{index:04d}_samples.npz',**archive) if index in REPRESENTATIVE: overlay(output,frame,candidates,results,context) if index%15 == 0: print(f'Ablation {index+1}/121: adaptive request={request}, matched={matched["budget"]}',flush=True) add_temporal_and_pairs(rows) latency=dict(raw=timings,summary=latency_summary(timings),warmups=warmups, adaptive_budget_ms=distribution([np.median(r['adaptive_budget_ms']) for r in rows]), support_count_ms=distribution([r['support_count_ms'] for r in rows]), raw_area_diagnostics_ms=distribution([r['raw_area_diagnostics_ms'] for r in rows]), extraction_ms={k:distribution([r['extraction_ms'][k] for r in rows]) for k in rows[0]['extraction_ms']}, scope='CPU same process, 3 rotated repetitions; per-frame median then across frames. Raw diagnostic scan excluded; support count shared once. Aliases have timings_ms=null; effective statistics reference an actual owner call. Gather residual includes overhead. GT/I/O/plots/extraction excluded from sampling_total.') data=make_summary(rows,pools,distance_pools,matched,actual_policy) import os data.update(run_id=logger.run_id,source_run_id=original['run_id'],config=config, reference_camera=reference_camera,latency=latency['summary'], input_hashes=verification['input_hashes'],source_contract=verification['source_contract'], dependency_links={k:os.path.relpath(v,output) for k,v in dict( original_comparison=source/'comparison.json', original_html=source/'comparison.html', original_samples_frame0=source/'f0000_samples.npz', rgbd=episode, tracker_masks=masks).items()}) write_json(output/'adaptive_node_budget.json',data) write_json(output/'frame_metrics.json',rows) write_json(output/'latency.json',latency) plot_results(output,rows,timings) html_report(output,data,rows) verification.update(adaptive_geometry_executed=True,deterministic_repetitions=True, adaptive_request256_exact_frames=[r['source_frame'] for r in rows if r['conditions']['Adaptive']['requested']==256], preservation=preserve_check(before),evaluated_frames=len(rows),gpu_executed=False, source_snapshot_sha256={str(p.relative_to(output/'evaluated_source')):digests(p)[1] for p in (output/'evaluated_source').rglob('*') if p.is_file()}) if not verification['preservation']['unchanged']: raise AssertionError('pre-existing source/artifact changed') write_json(output/'verification.json',verification) for p in sorted(output.rglob('*')): if p.is_file() and p.name not in ('config.yaml','metadata.json','metrics.json','manifest.json') and not p.name.endswith('.tracking.json'): logger.link_output(p,kind='metrics' if p.suffix=='.json' else 'trajectory' if p.suffix=='.npz' else 'reports') logger.log({c:dict(mean_nodes=data['conditions'][c]['counts']['selected']['mean'], reduction=data['conditions'][c]['node_reduction_fraction']) for c in CONDITIONS},prefix='eval/task03ab') logger.record(evaluated_frames=121,evaluation_device='cpu',gpu_executed=False,source_run_id=original['run_id']) print('Completed:',output,flush=True) return output
def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--preservation-before',type=Path,required=True) parser.add_argument('--tests-log',type=Path) args=parser.parse_args() evaluate(args.preservation_before,args.tests_log)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Current-observation Structural priority / Surface FPS, internal NumPy metadata.
No GT, cache, final node features, graph edges or Vision--Graph packaging. XYZremains in the source CV-camera frame. Selection roles are not semantic types."""from __future__ import annotations
from dataclasses import dataclass, fieldfrom numbers import Integralfrom time import perf_counter
import numpy as np
from visual.runtime.geometry import ( GeometryFrame, GeometryParameters, estimate_surface_normals,)from visual.runtime.pca import build_geometry, cropped_features, local_plane_optimizedfrom visual.runtime.normal_estimators import finite_differencefrom visual.runtime.edge_evidence import PairEvidence, pair_evidencefrom visual.runtime.rgbd import PEG, BOX, TrackedRGBDFrame
METHODS = ('S0', 'S1', 'S2', 'S3', 'S4')
def _integer(value, name): if not isinstance(value, Integral) or isinstance(value, (bool, np.bool_)) or value < 0: raise ValueError(f'{name} must be a nonnegative integer')
@dataclass(frozen=True)class SamplingConfig: """Experimental defaults, not adopted architecture/hyperparameters.
Reserve minimums first, then apportion remaining capacity by observed point counts (or their square roots). Largest remainder, capped by availability; exact ties use ascending object ID. Structural slots are a GLOBAL maximum floor(num_points*ratio), including independently capped S4 depth-only slots. """ num_points: int = 256 structural_ratio: float = .25 min_points: tuple[int, int] = (16, 16) allocation: str = 'observed_points' seed: int = 0 orientation_threshold_deg: float = 20. depth_priority_fraction: float = .25 sampling: str = 'fps'
def __post_init__(self): _integer(self.num_points, 'num_points'); _integer(self.seed, 'seed') if len(self.min_points) != 2: raise ValueError('min_points must contain Peg and Box minimums') for n in self.min_points: _integer(n, 'object minimum') if sum(self.min_points) > self.num_points: raise ValueError('sum of object minimums exceeds num_points') for name in ('structural_ratio', 'depth_priority_fraction'): x = getattr(self, name) if not np.isfinite(x) or not 0 <= x <= 1: raise ValueError(f'{name} must be finite in [0,1]') if not np.isfinite(self.orientation_threshold_deg) or not 0 <= self.orientation_threshold_deg <= 180: raise ValueError('orientation threshold must be in [0,180] degrees') if self.allocation not in ('observed_points', 'sqrt_observed_points'): raise ValueError('unknown allocation rule') if self.sampling != 'fps': raise ValueError('only fps sampling is supported')
def allocate_budget(total, capacities, minimums=(0, 0), weights=None): """Capped proportional integer apportionment, deterministic and availability aware.""" _integer(total, 'budget') cap = np.asarray(capacities) mins = np.asarray(minimums) if cap.shape != (2,) or mins.shape != (2,): raise ValueError('expected two object counts') for x in (*cap, *mins): _integer(x, 'capacity/minimum') if mins.sum() > total: raise ValueError('minimums exceed total budget') cap, mins = cap.astype(np.int64), mins.astype(np.int64) weight = cap.astype(float) if weights is None else np.asarray(weights, float) if weight.shape != (2,) or not np.isfinite(weight).all() or (weight < 0).any(): raise ValueError('weights must be two finite nonnegative values') out = np.minimum(cap, mins) left = min(total, int(cap.sum()))-int(out.sum()) while left: room = cap-out w = np.where(room > 0, weight, 0) if not w.any(): w = (room > 0).astype(float) quota = left*w/w.sum() take = np.minimum(room, np.floor(quota).astype(np.int64)) out += take; left -= int(take.sum()) # Largest fractional remainder; saturated objects are skipped. If a # quota exceeded capacity, the next pass redistributes the surplus. order = np.argsort(-(quota-np.floor(quota)), kind='stable') for i in order: if out[i] < cap[i] and left: out[i] += 1; left -= 1 return out
def fps_indices(points, count, *, seed=0, initial=()): """Legacy pointcloud.fps distance update, returning unique source row indices.
No random pre-reduction. Uniform seeded first row; argmax ties choose the first source row. An initial selection seeds distances for Surface coverage. All initial rows precede newly selected rows. Even coincident XYZ is never selected twice by row index. Computes squared distances in float64. """ _integer(count, 'FPS count'); _integer(seed, 'FPS seed') xyz = np.asarray(points, dtype=float) if xyz.ndim != 2 or xyz.shape[1] != 3 or not np.isfinite(xyz).all(): raise ValueError('FPS requires finite [N,3] observed coordinates') initial = np.asarray(initial, dtype=np.int64) if initial.ndim != 1 or len(np.unique(initial)) != len(initial) or ((initial < 0) | (initial >= len(xyz))).any(): raise ValueError('initial FPS rows must be distinct valid indices') count = min(count, len(xyz)) if len(initial) > count: raise ValueError('initial rows exceed FPS count') if not count: return np.empty(0, np.int64) chosen = list(initial) distance = np.full(len(xyz), np.inf) x, y, z = (np.ascontiguousarray(xyz[:, i]) for i in range(3)) def update(j): np.minimum(distance, (x-x[j])**2+(y-y[j])**2+(z-z[j])**2, out=distance) distance[j] = -np.inf for j in chosen: update(j) if not chosen: chosen.append(int(np.random.default_rng(seed).integers(len(xyz)))) update(chosen[-1]) while len(chosen) < count: j = int(distance.argmax()); chosen.append(j); update(j) return np.asarray(chosen, np.int64)
@dataclass(frozen=True)class SamplingEvidence: """Detector output before thresholding. Contains observations only.""" frame: GeometryFrame pairs: dict[int, PairEvidence] estimator: str timings_ms: dict[str, float]
@dataclass(frozen=True)class ObjectCandidates: """Only valid observed rows, in original raster order; all evidence stays aligned.""" flat_index: np.ndarray points: np.ndarray metadata: dict[str, np.ndarray]
@dataclass(frozen=True)class SampledPoints: """Internal selection, variable N; no padding, no final GNN feature encoding.
priority_selected / depth_priority_selected record selection paths, whereas metadata['structural_candidate'] records detector eligibility. Surface FPS may select more detector candidates than the structural priority slot cap. """ source_frame: int camera: str points: np.ndarray pixels_vu: np.ndarray flat_index: np.ndarray object_id: np.ndarray priority_selected: np.ndarray depth_priority_selected: np.ndarray metadata: dict[str, np.ndarray] object_budgets: dict[int, int] counts: dict[int, dict[str, int]] timings_ms: dict[str, float] = field(default_factory=dict)
def extract_sampling_evidence(frame: TrackedRGBDFrame, estimator='pca5', parameters=GeometryParameters()): """Reuse Task02 estimators and pair operator; optimized PCA5 analytic solver.""" if estimator not in ('baseline', 'fd2', 'pca5'): raise ValueError('unknown normal estimator') t0 = perf_counter(); geometry = build_geometry(frame); t1 = perf_counter() normals = {} for oid in (PEG, BOX): if estimator == 'baseline': normals[oid] = estimate_surface_normals(geometry, oid, parameters) elif estimator == 'fd2': normals[oid] = finite_difference(geometry, oid, 2, parameters) else: normals[oid] = local_plane_optimized(geometry, oid, parameters, solver='analytic') t2 = perf_counter() features = {i: cropped_features(geometry, i, *normals[i], parameters) for i in (PEG, BOX)} t3 = perf_counter() pairs = {i: pair_evidence(geometry, i, *normals[i], parameters) for i in (PEG, BOX)} t4 = perf_counter() timing = dict(geometry=(t1-t0)*1000, normals=(t2-t1)*1000, features=(t3-t2)*1000, pair_evidence=(t4-t3)*1000, extraction_total=(t4-t0)*1000) result = GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timing) return SamplingEvidence(result, pairs, estimator, timing)
def extract_candidates(evidence: SamplingEvidence, config: SamplingConfig, method='S3'): """Threshold at observed pixels; boundary flags alone never imply eligibility.""" if method not in METHODS: raise ValueError('unknown sampling method') expected = dict(S1='baseline', S2='fd2', S3='pca5', S4='pca5') if method in expected and evidence.estimator != expected[method]: raise ValueError('method and normal estimator disagree') g = evidence.frame.geometry result = {} for oid in (PEG, BOX): idx = np.flatnonzero(g.observed_mask(oid)) f = evidence.frame.objects[oid] maps = evidence.pairs[oid].candidates(config.orientation_threshold_deg) metadata = {name: getattr(f, name).reshape((-1, 3) if name == 'normals' else (-1,))[idx].copy() for name in f.__dataclass_fields__} metadata.update({f'{name}_evidence': m.ravel()[idx] for name, m in maps.items() if name != 'union'}) orientation = maps['orientation'].ravel()[idx] depth_only = maps['depth'].ravel()[idx] & ~orientation metadata.update(orientation_score_deg=np.rad2deg(f.normal_variation_rad.ravel()[idx]), orientation_candidate=orientation, depth_only_candidate=depth_only, structural_candidate=orientation | (depth_only if method == 'S4' and config.depth_priority_fraction > 0 else False)) result[oid] = ObjectCandidates(idx, g.xyz.reshape(-1, 3)[idx].copy(), metadata) return result
def sample_points(evidence: SamplingEvidence, config=SamplingConfig(), *, method='S3'): """Object budgets -> Structural FPS -> remaining-support FPS seeded by priority.""" t0 = perf_counter(); objects = extract_candidates(evidence, config, method); t1 = perf_counter() available = np.array([len(objects[i].points) for i in (PEG, BOX)]) weights = np.sqrt(available) if config.allocation == 'sqrt_observed_points' else available budgets = allocate_budget(config.num_points, available, config.min_points, weights) cap = int(np.floor(config.num_points*config.structural_ratio)) if method != 'S0' else 0 capacities = np.array([min(budgets[i], int(objects[i].metadata['structural_candidate'].sum())) for i in (PEG, BOX)]) slots = allocate_budget(cap, capacities, weights=budgets) depth_cap = int(np.floor(cap*config.depth_priority_fraction)) if method == 'S4' else 0 depth_capacity = [min(slots[i], int(objects[i].metadata['depth_only_candidate'].sum())) for i in (PEG, BOX)] depth_slots = allocate_budget(depth_cap, depth_capacity, weights=budgets) t2 = perf_counter() selections, priority_sizes, depth_sizes = {}, {}, {} for i in (PEG, BOX): obj = objects[i]; m = obj.metadata # Each object always uses its own stream, invariant to missing other objects. seed = int(np.random.SeedSequence([config.seed, i]).generate_state(1)[0]) oi = np.flatnonzero(m['orientation_candidate']) di = np.flatnonzero(m['depth_only_candidate']) # Unused depth reservation can be used by orientation, never vice versa. dn = min(int(depth_slots[i]), len(di)) on = min(int(slots[i])-dn, len(oi)) orientation = oi[fps_indices(obj.points[oi], on, seed=seed)] depth = di[fps_indices(obj.points[di], dn, seed=seed,)] selections[i] = np.concatenate((orientation, depth)) priority_sizes[i], depth_sizes[i] = on+dn, dn t3 = perf_counter() for i in (PEG, BOX): seed = int(np.random.SeedSequence([config.seed, i]).generate_state(1)[0]) selections[i] = fps_indices(objects[i].points, int(budgets[i]), seed=seed, initial=selections[i]) t4 = perf_counter() flat, xyz, ids, priority, depth_priority, metadata = [], [], [], [], [], {} counts = {} for i in (PEG, BOX): obj = objects[i]; rows = selections[i]; n = len(rows); pn = priority_sizes[i]; dn = depth_sizes[i] flat.append(obj.flat_index[rows]); xyz.append(obj.points[rows]); ids.append(np.full(n, i, np.int64)) priority.append(np.arange(n) < pn) depth_priority.append((np.arange(n) >= pn-dn) & (np.arange(n) < pn)) for name, values in obj.metadata.items(): metadata.setdefault(name, []).append(values[rows]) counts[i] = dict(observed=len(obj.points), budget=int(budgets[i]), candidates=int(obj.metadata['structural_candidate'].sum()), priority=pn, orientation_priority=pn-dn, depth_priority=dn, surface_fps=n-pn, selected_candidates=int(obj.metadata['structural_candidate'][rows].sum()), selected=n) flat = np.concatenate(flat) timing = dict(candidate_selection=(t1-t0)*1000, budget_allocation=(t2-t1)*1000, structural_sampling=(t3-t2)*1000, surface_fps=(t4-t3)*1000) result = SampledPoints(evidence.frame.source_frame, evidence.frame.camera, np.concatenate(xyz), np.column_stack(np.unravel_index(flat, evidence.frame.geometry.valid_depth.shape)), flat, np.concatenate(ids), np.concatenate(priority), np.concatenate(depth_priority), {k: np.concatenate(v) for k, v in metadata.items()}, {i: int(budgets[i]) for i in (PEG, BOX)}, counts, timing) timing['sampling_total'] = (perf_counter()-t0)*1000 timing['geometry_sampling_total'] = evidence.timings_ms['extraction_total']+timing['sampling_total'] return result123version https://git-lfs.github.com/spec/v1oid sha256:67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0bsize 126444483123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475"""Task 02-A: paired quantization and saved RGB-D normal reliability diagnostics.
CPU only, fresh UUID output directory, no inference, estimator changes or uploads.Run with WANDB_MODE=disabled for entirely local experiment tracking."""from __future__ import annotations
import argparsefrom dataclasses import fields, replaceimport htmlimport importlib.metadataimport jsonfrom pathlib import Pathimport platformimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.patches import Patchimport numpy as np
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import GeometryParameters, process_geometryfrom visual.runtime.rgbd import BOX, PEG, iter_saved_rgbdfrom visual.runtime.test.normal_diagnostics import ( angular_error, box_primitives, dilate, endpoints, erode, metrics, normal_blockers, oracle, pose_rotation, quantize, real_regions, rim_region, scale_probe, stats, synthetic_case,)
OBJECTS = {'peg': PEG, 'box': BOX}COLORS = {'plane': '#00ffcc', 'seam': '#ff8000', 'rim': '#ffdd00', 'occlusion': '#ff55cc', 'contamination': '#ff2222', 'mask_cut': '#4488ff'}
def save_json(path, value): path.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n', encoding='utf-8')
def summarize_rows(rows, values, errors=None): """Micro averages and pooled quantiles; no averaging per-frame percentiles.""" keys = ('region_pixels', 'points', 'normals', 'variation_valid', 'depth_discontinuity', 'mask_boundary', 'invalid_depth_boundary', 'incomplete_normal_neighbours', 'high_5_count', 'high_10_count', 'high_20_count', 'high_30_count', 'jump_or_high20_count') total = {k: sum(r[k] for r in rows) for k in keys} n, nv, vv = total['points'], total['normals'], total['variation_valid'] total.update(frames=len(rows), normal_valid_fraction=nv/n if n else None, variation_valid_fraction=vv/n if n else None, variation_deg=stats(np.concatenate(values))) rn = total['region_pixels'] total.update(observed_fraction_of_region=n/rn if rn else None, normal_fraction_of_region=nv/rn if rn else None, jump_or_high20_fraction_of_region=total['jump_or_high20_count']/rn if rn else None) total['variation_hist_5deg'] = np.sum([r['variation_hist_5deg'] for r in rows], axis=0).tolist() for t in (5, 10, 20, 30): total[f'high_{t}_fraction_of_valid'] = total[f'high_{t}_count']/vv if vv else None total[f'high_{t}_fraction_of_points'] = total[f'high_{t}_count']/n if n else None if errors is not None: total['angular_error_deg'] = stats(np.concatenate(errors)) return total
def synthetic_experiment(output, intrinsic): rows, primaries, scales = [], {}, [] for kind in ('front', 'tilted', 'crease', 'step'): for z in (.2, .25, .35, .6, 1.): for phase in (0., .00025, .0005, .00075): frame, truth, regions = synthetic_case(kind, intrinsic, z0=z, phase_m=phase) original = process_geometry(frame) float_feature = original.objects[PEG] runs = {'float': (frame, original)} for mode in ('floor', 'nearest'): changed = replace(frame, depth=quantize(frame.depth, mode)) runs[mode] = (changed, process_geometry(changed)) row = dict(geometry=kind, z0_m=z, phase_m=phase, conditions={}) for mode, (observation, result) in runs.items(): f = result.objects[PEG] row['conditions'][mode] = dict( regions={k: metrics(f, m, truth) for k, m in regions.items()}, all_support=metrics(f, f.valid_points, truth), depth_change_mm=stats((observation.depth-frame.depth)[frame.masks[PEG]]*1000)) rows.append(row) if z == .25 and phase == .00025: primaries[kind] = (frame, truth, regions, runs) if kind == 'tilted' and phase == .00025: qframe, qresult = runs['floor'] scales.append(dict(z0_m=z, rows=scale_probe(qframe, qresult.objects[PEG], PEG, regions['plane'], truth))) # Controls: observation cuts of an exactly flat surface do not create a corner. frame, truth, _ = synthetic_case('front', intrinsic, z0=.25025) mask = frame.masks[PEG].copy(); mask[:, 256:] = False cut = replace(frame, masks={PEG: mask}) hole_depth = frame.depth.copy(); hole_depth[240:272, 240:272] = 0 hole = replace(frame, depth=hole_depth) controls = {} for name, observation in [('mask_cut', cut), ('invalid_depth_hole', hole)]: result = process_geometry(observation) controls[name] = dict(metrics=metrics(result.objects[PEG], observation.masks[PEG], truth), blockers=normal_blockers(result, PEG)) synthetic_plot(output/'synthetic.png', primaries) return dict(primary_z0_m=.25, primary_phase_m=.00025, primary_quantization='floor', depth_sweep_m=[.2, .25, .35, .6, 1.], phase_sweep_m=[0, .00025, .0005, .00075], slope_xy=[.4, -.25], crease_slopes_xy=[[-.6, .15], [.6, .15]], step_m=.05, mask_bounds_vu=[128, 384, 128, 384], edge_band_half_width_px=3, planar_border_margin_px=3, controls=controls, cases=rows, scale_sweep=scales)
def synthetic_plot(path, primary): fig, axes = plt.subplots(4, 5, figsize=(18, 13), constrained_layout=True) for axs, (kind, (frame, truth, regions, runs)) in zip(axes, primary.items()): clean, q = runs['float'][1].objects[PEG], runs['floor'][1].objects[PEG] images = [np.where(frame.masks[PEG], frame.depth, np.nan)*1000, np.rad2deg(clean.normal_variation_rad), np.rad2deg(q.normal_variation_rad), angular_error(q.normals, truth), np.where(q.valid_points, q.normal_valid.astype(float)+2*q.depth_discontinuity, np.nan)] titles = [f'{kind}: float depth (mm)', 'Float variation (deg)', '1mm floor variation (deg)', '1mm floor normal error (deg)', 'Normal valid=1, depth jump=+2'] for j, (ax, a, title) in enumerate(zip(axs, images, titles)): im = ax.imshow(a, vmin=0 if j in (1, 2, 3, 4) else None, vmax=45 if j in (1, 2, 3) else 3 if j == 4 else None, cmap='turbo') ax.set(xlim=(122, 390), ylim=(390, 122), title=title); ax.axis('off') fig.colorbar(im, ax=ax, shrink=.7) fig.suptitle('Paired synthetic observations: same camera, masks and extractor; only depth quantized\n' 'fx=fy=256; z0=250.25mm; no noise or filtering', fontsize=14) fig.savefig(path, dpi=130); plt.close(fig)
def real_plot(path, frame, result, regions, maps, oracles): fig, axes = plt.subplots(3, 4, figsize=(18, 14), constrained_layout=True) axes = axes.ravel() axes[0].imshow(frame.rgb); axes[0].set_title('RGB with evaluation regions') plane = regions['peg']['plane_interior'] overlays = dict(plane=plane, seam=regions['peg']['face_seam_2px'], rim=regions['box']['hole_rim'], occlusion=regions['peg']['occlusion_2px']|regions['box']['occlusion_2px'], contamination=(result.objects[PEG].valid_points & regions['peg']['contamination'])| (result.objects[BOX].valid_points & regions['box']['contamination']), mask_cut=regions['peg']['same_plane_tracker_cut_2px']) for name, mask in overlays.items(): if mask.any(): axes[0].contour(mask, levels=[.5], colors=[COLORS[name]], linewidths=.65) axes[0].legend(handles=[Patch(color=COLORS[k], label=k) for k in COLORS], fontsize=8, loc='upper right') support = result.objects[PEG].valid_points | result.objects[BOX].valid_points d = np.where(support, frame.depth*1000, np.nan) im = axes[1].imshow(d, cmap='turbo', vmin=150, vmax=700) axes[1].set_title('Observed depth (mm), fixed scale'); fig.colorbar(im, ax=axes[1], shrink=.7) for name, base in [('peg', 2), ('box', 7)]: f = result.objects[OBJECTS[name]] var = np.rad2deg(f.normal_variation_rad) error = angular_error(f.normals, oracles[name]['normals']) error[~regions[name]['gt_visible']] = np.nan panel = [(var, 'normal variation (deg)', 45, 'turbo'), (np.where(f.valid_points, f.normal_valid, np.nan), 'normal validity', 1, 'viridis'), (error, 'normal error vs GT (deg)', 45, 'turbo')] for j, (a, title, vmax, cmap) in enumerate(panel): im = axes[base+j].imshow(a, cmap=cmap, vmin=0, vmax=vmax) axes[base+j].set_title(f'{name}: {title}'); fig.colorbar(im, ax=axes[base+j], shrink=.7) boundary = np.zeros((*frame.depth.shape, 3)) boundary[..., 0] = f.depth_discontinuity boundary[..., 1] = f.mask_boundary boundary[..., 2] = f.depth_validity_boundary axes[base+3].imshow(boundary) axes[base+3].set_title(f'{name}: jump / mask / invalid = R/G/B') # Peg-only zoom shows quantization terraces and selected broad planar interior. y, x = np.nonzero(plane) if len(x): lo_x, hi_x, lo_y, hi_y = max(0, x.min()-8), x.max()+8, max(0, y.min()-8), y.max()+8 else: lo_x, hi_x, lo_y, hi_y = 0, 511, 0, 511 f = result.objects[PEG] axes[6].imshow(np.where(f.valid_points, frame.depth*1000, np.nan), cmap='turbo') if plane.any(): axes[6].contour(plane, [.5], colors=['#00ffcc'], linewidths=.6) axes[6].set_title('Peg depth terraces; cyan=verified plane ROI') axes[6].set(xlim=(lo_x, hi_x), ylim=(hi_y, lo_y)) axes[11].imshow(np.rad2deg(f.normal_variation_rad), cmap='turbo', vmin=0, vmax=45) if plane.any(): axes[11].contour(plane, [.5], colors=['#00ffcc'], linewidths=.6) axes[11].set_title('Same Peg crop: variation (0-45 deg)') axes[11].set(xlim=(lo_x, hi_x), ylim=(hi_y, lo_y)) # Full panels share a fixed object viewport for comparisons between frames. for i, ax in enumerate(axes): if i not in (6, 11): ax.set(xlim=(0, 511), ylim=(511, 0)) ax.axis('off') fig.suptitle(f'Source {frame.source_frame}: observed features; GT used only to evaluate regions\n' 'Black validity=unavailable; NaN variation is missing, not zero. Scales fixed across frames.', fontsize=14) fig.savefig(path, dpi=130); plt.close(fig)
def boundary_plot(path, frame, result, regions): fig, axes = plt.subplots(2, 4, figsize=(16, 10), constrained_layout=True) for axs, (name, object_id) in zip(axes, OBJECTS.items()): f = result.objects[object_id] region = regions[name] axs[0].imshow(frame.rgb) for key, color in [('face_seam_2px', '#ff8000'), ('occlusion_2px', '#ff55cc'), ('same_plane_tracker_cut_2px', '#4488ff'), ('hole_rim', '#ffff00')]: if key in region and region[key].any(): axs[0].contour(region[key], [.5], colors=[color], linewidths=.8) axs[0].set_title(f'{name}: GT seam=orange, rim=yellow\nocclusion=pink, same-face mask cut=blue') im = axs[1].imshow(np.rad2deg(f.normal_variation_rad), cmap='turbo', vmin=0, vmax=45) axs[1].set_title('Observed normal variation (deg)'); fig.colorbar(im, ax=axs[1], shrink=.65) axs[2].imshow(np.where(f.valid_points, f.normal_valid, np.nan), cmap='viridis', vmin=0, vmax=1) axs[2].set_title('Normal valid: yellow=1, dark=0') boundary = np.stack((f.depth_discontinuity, f.mask_boundary, f.depth_validity_boundary), -1).astype(float) axs[3].imshow(boundary) axs[3].set_title('Observed jump / mask / invalid = R/G/B') contour = region.get('hole_rim', region['face_seam_2px']) if contour.any(): for ax in axs[1:]: ax.contour(contour, [.5], colors=['white'], linewidths=.65) y, x = np.nonzero(f.object_mask | region['gt_visible']) bounds = (max(0, x.min()-8), min(511, x.max()+8), min(511, y.max()+8), max(0, y.min()-8)) if len(x) else (0, 511, 511, 0) for ax in axs: ax.set(xlim=bounds[:2], ylim=bounds[2:]); ax.axis('off') fig.suptitle(f'Frame {frame.source_frame}: boundary detail; evaluation regions may overlap\n' 'White outline in feature maps: visible physical hole rim (Box) or face seam (Peg).', fontsize=13) fig.savefig(path, dpi=150); plt.close(fig)
def profile_plot(path, frame, result, regions, truth): # Dominant face and its longer image axis, selected independently of features. plane = regions['plane_interior'] if not plane.any(): return labels, counts = np.unique(truth['face'][plane], return_counts=True) face = labels[counts.argmax()] face_roi = plane & (truth['face'] == face) row_counts, col_counts = face_roi.sum(axis=1), face_roi.sum(axis=0) along_v = col_counts.max() > row_counts.max() fixed = int(np.argmax(col_counts if along_v else row_counts)) line_roi = face_roi[:, fixed] if along_v else face_roi[fixed] coords = np.flatnonzero(line_roi) lo, hi = int(coords.min()), int(coords.max()) coord = np.arange(lo, hi+1) vi, ui = (coord, fixed) if along_v else (fixed, coord) good = line_roi[coord] f = result.objects[PEG] fig, axes = plt.subplots(3, 1, figsize=(11, 7), sharex=True, constrained_layout=True) axes[0].plot(coord, frame.depth[vi, ui]*1000, '.-', label='observed 1mm depth', ms=3) axes[0].plot(coord, truth['depth'][vi, ui]*1000, label='analytic GT face, evaluation only', lw=1) axes[0].set_ylabel('Depth (mm)'); axes[0].legend(fontsize=8) for c, label in enumerate(('nx', 'ny', 'nz')): axes[1].plot(coord, np.where(good, f.normals[vi, ui, c], np.nan), label=label) axes[1].set_ylabel('CV unit normal'); axes[1].legend(fontsize=8, ncol=3) axes[2].plot(coord, np.where(good, np.rad2deg(f.normal_variation_rad[vi, ui]), np.nan), label='variation') axis_name, fixed_name = ('v', 'u') if along_v else ('u', 'v') axes[2].axhline(20, color='r', ls=':', lw=1) axes[2].set(ylabel='Variation (deg)', xlabel=f'Source {axis_name}') fig.suptitle(f'Frame {frame.source_frame}, {fixed_name}={fixed}, GT signed face {face}: verified planar pixels only') fig.savefig(path, dpi=140); plt.close(fig) return dict(varying_axis=axis_name, fixed_axis=fixed_name, fixed_index=fixed, signed_face=int(face), axis_min=lo, axis_max=hi, valid_planar_coordinates=coord[good].tolist())
def evaluate(episode_path, masks_path, *, output_root, camera='base_camera', selected=(0, 15, 45, 80, 120)): episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() # Check source identity before producing a new evaluation run. tracking_path = masks_path.with_name('tracking.json') if tracking_path.exists(): tracking = json.loads(tracking_path.read_text()) if tracking.get('camera') not in (None, camera): raise ValueError('camera differs from tracking.json') original = Path(tracking.get('input') or episode_path) if original.is_file() and original.resolve() != episode_path and digests(original)[1] != digests(episode_path)[1]: raise ValueError('episode differs from tracking.json') with np.load(episode_path, allow_pickle=False) as archive: required = [f'{camera}/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed'] missing = set(required)-set(archive.files) if missing: raise ValueError(f'evaluation GT missing: {sorted(missing)}') gt = {k: archive[k] for k in required} with np.load(masks_path, allow_pickle=False) as archive: sources = archive['source_frame'] if sources.ndim != 1 or not len(sources) or len(np.unique(sources)) != len(sources): raise ValueError('source_frame must be unique and nonempty') if set(selected)-set(sources.tolist()): raise ValueError('selected sources absent from tracking archive') iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) first = next(iterator) from itertools import chain config = dict(task='02-A', input=str(episode_path), masks=str(masks_path), camera=camera, input_sha256=digests(episode_path)[1], masks_sha256=digests(masks_path)[1], baseline_geometry_sha256=digests(REPO/'visual/runtime/geometry.py')[1], selected_sources=list(selected), intrinsic=first.intrinsic.tolist(), parameters=vars(GeometryParameters()), device='cpu', gpu_executed=False, python=platform.python_version(), numpy=np.__version__, platform=platform.platform(), scipy=importlib.metadata.version('scipy'), matplotlib=matplotlib.__version__, roi_depth_residual_m=.0015, roi_metric_edge_margin_m=.004, roi_raster_erosion_px=3, rim_metric_radius_m=.004, rim_raster_radius_px=2, high_variation_degrees=[5, 10, 20, 30], actual_feature_inputs='recorded depth, intrinsic and original tracker masks only', gt_use='evaluation regions, oriented angular truth, analytic depth residuals only') config['diagnostic_source_sha256'] = {str(p.relative_to(REPO)): digests(p)[1] for p in (Path(__file__), Path(__file__).with_name('normal_diagnostics.py'), Path(__file__).with_name('test_normal_diagnostics.py'))} with ExperimentLogger(team='visual', config=config, seed=int(gt['seed']), model='task02a_unchanged_organized_geometry', job_type='evaluate') as logger: output = Path(output_root).resolve()/logger.run_id output.mkdir(parents=True, exist_ok=False) print(f'Output: {output}', flush=True) synthetic = synthetic_experiment(output, first.intrinsic) records, pooled, pooled_errors = [], {}, {} for frame in chain((first,), iterator): s = frame.source_frame result = process_geometry(frame) # Actual feature computation: no GT. half = gt['peg_half_sizes'] box_rotation = pose_rotation(gt['box_pose'][s]) hole_centre = ((gt['box_hole_pose'][s, :3]-gt['box_pose'][s, :3]) @ box_rotation)[1:] boxes = box_primitives(float(half[0]), float(gt['box_hole_radii']), hole_centre) truths = dict(peg=oracle(frame, gt['peg_pose'][s], [(np.zeros(3), half)]), box=oracle(frame, gt['box_pose'][s], boxes)) record = dict(source_frame=s, frame_idx=frame.frame_idx, timestamp=frame.timestamp, overlap_pixels=int(result.geometry.overlap_mask.sum()), objects={}) selected_regions, maps, plane_base = {}, {}, None for name, object_id in OBJECTS.items(): f = result.objects[object_id] seg = gt[f'{camera}/seg'][s] == int(gt[f'{name}_id']) regions, base, boundary_maps = real_regions(frame, result, seg, truths[name], object_id, half=half if name == 'peg' else None) if name == 'peg': plane_base = base if name == 'box': rim, projected = rim_region(frame, truths[name], regions['gt_visible'], gt['box_pose'][s], float(half[0]), float(gt['box_hole_radii']), hole_centre) regions['hole_rim'] = rim regions['hole_rim_normal_valid'] = rim & f.normal_valid regions['hole_rim_normal_invalid'] = rim & ~f.normal_valid boundary_maps['rim_projection'] = projected selected_regions[name], maps[name] = regions, boundary_maps rows = {k: metrics(f, m, truths[name]['normals'] if k.startswith('plane_') else None) for k, m in regions.items()} visible = regions['gt_visible'] residual = (frame.depth-truths[name]['depth'])*1000 observed_z, analytic_z = frame.depth[visible], truths[name]['depth'][visible] expected_floor = (np.floor(truths[name]['depth']*1000)/1000).astype(np.float32) floor_agree_map = visible & (frame.depth == expected_floor) floor_agree = floor_agree_map[visible] row = dict(mask_pixels=int(f.object_mask.sum()), gt_pixels=int(seg.sum()), analytic_hit_gt_fraction=float(np.mean(np.isfinite(truths[name]['depth'][seg]))) if seg.any() else None, depth_consistent_gt_fraction=float(visible.sum()/seg.sum()) if seg.any() else None, depth_residual_mm=stats(residual[visible]), mm_grid_residual_m=stats(np.abs(observed_z-np.rint(observed_z.astype(float)*1000)/1000)), analytic_floor_match_fraction=float(floor_agree.mean()) if visible.any() else None, analytic_floor_match_count=int(floor_agree.sum()), regions=rows, blockers=normal_blockers(result, object_id)) if name == 'peg': plane = regions['plane_interior'] # Derivative geometry: 1-pixel lateral spacing at the same z. row['plane_depth_m'] = stats(frame.depth[plane]) row['plane_lateral_pixel_spacing_mm'] = stats(frame.depth[plane]/frame.intrinsic[0, 0]*1000) row['q_over_2pixel_lateral_span'] = stats(.001/(2*frame.depth[plane]/frame.intrinsic[0, 0])) vv = plane & f.normal_variation_valid matched = vv & erode(floor_agree_map, 2) high = vv & (np.rad2deg(f.normal_variation_rad) > 20) row['plane_floor_dependency_match'] = dict( variation_valid=int(vv.sum()), matched=int(matched.sum()), fraction=float(matched.sum()/vv.sum()) if vv.any() else None, high20=int(high.sum()), high20_matched=int((high & matched).sum()), high20_matched_fraction=float((high & matched).sum()/high.sum()) if high.any() else None) # Same-plane mask cuts and occlusions are evaluated separately. record['objects'][name] = row for region_name, roi in regions.items(): key = f'{name}/{region_name}' vv = roi & f.normal_variation_valid & f.valid_points pooled.setdefault(key, []).append(np.rad2deg(f.normal_variation_rad[vv])) if region_name.startswith('plane_'): nv = roi & f.normal_valid & f.valid_points pooled_errors.setdefault(key, []).append(angular_error(f.normals[nv], truths[name]['normals'][nv])) if s in selected: record['scale_probe'] = scale_probe(frame, result.objects[PEG], PEG, plane_base, truths['peg']['normals']) record['profile'] = profile_plot(output/f'f{s:04d}_profile.png', frame, result, selected_regions['peg'], truths['peg']) real_plot(output/f'f{s:04d}.png', frame, result, selected_regions, maps, truths) boundary_plot(output/f'f{s:04d}_boundaries.png', frame, result, selected_regions) arrays = dict(source_frame=np.array(s), depth_m=frame.depth, intrinsic=frame.intrinsic) for name, object_id in OBJECTS.items(): f = result.objects[object_id] arrays.update({f'{name}/{field.name}': getattr(f, field.name) for field in fields(f)}) arrays.update({f'evaluation/{name}/{k}': v for k, v in selected_regions[name].items()}) arrays[f'evaluation/{name}/analytic_depth_m'] = truths[name]['depth'] arrays[f'evaluation/{name}/face_id'] = truths[name]['face'] np.savez_compressed(output/f'f{s:04d}.npz', **arrays) records.append(record) if len(records) == 1 or len(records) % 20 == 0: print(f'Real frames: {len(records)}/{len(sources)}', flush=True) summary = {} for key, values in pooled.items(): name, region = key.split('/') summary[key] = summarize_rows([r['objects'][name]['regions'][region] for r in records], values, pooled_errors.get(key)) data = dict(run_id=logger.run_id, config=config, git_commit=logger.metadata['git_commit'], git_dirty=logger.metadata['git_dirty'], synthetic=synthetic, evaluated_frames=len(records), selected_source_frames=list(selected), summary=summary, frames=records) save_json(output/'diagnostics.json', data) distribution_plot(output/'distributions.png', data) scale_plot(output/'scale_probe.png', data) write_html(output/'diagnostics.html', data) for path in sorted(output.iterdir()): logger.link_output(path, kind='metrics' if path.suffix == '.json' else None) logger.log(summary, prefix='eval/task02a') logger.record(dataset_sha256=config['input_sha256'], masks_sha256=config['masks_sha256'], evaluation_device='cpu', evaluated_frames=len(records), gpu_executed=False) return output
def distribution_plot(path, data): fig, axes = plt.subplots(2, 2, figsize=(13, 9), constrained_layout=True) xs = np.arange(2.5, 180, 5) for name, ax in zip(('peg', 'box'), axes[0]): keys = ['all', 'plane_interior', 'contamination', 'face_seam_2px', 'occlusion_2px', 'hole_rim'] for key in keys: r = data['summary'].get(f'{name}/{key}') if r and r['variation_valid']: ax.plot(xs, np.array(r['variation_hist_5deg'])/r['variation_valid'], label=f'{key} (n={r["variation_valid"]})') ax.set(xlim=(0, 90), xlabel='Normal variation (deg)', ylabel='Fraction per 5 deg bin', title=f'{name}: pooled 121 frames') ax.legend(fontsize=7) sources = [r['source_frame'] for r in data['frames']] for key in ('all', 'plane_interior', 'contamination', 'face_seam_2px', 'occlusion_2px'): ys = [r['objects']['peg']['regions'][key]['high_20_fraction_of_valid'] for r in data['frames']] axes[1, 0].plot(sources, [np.nan if v is None else v for v in ys], label=key, lw=1) axes[1, 0].set(xlabel='Source frame', ylabel='Fraction >20 deg / valid variation', title='Peg: time distribution') axes[1, 0].legend(fontsize=7) for name, key in [('peg', 'all'), ('box', 'all'), ('box', 'hole_rim')]: ys = [r['objects'][name]['regions'][key]['normal_valid_fraction'] for r in data['frames']] axes[1, 1].plot(sources, [np.nan if v is None else v for v in ys], label=f'{name}/{key}') axes[1, 1].set(xlabel='Source frame', ylabel='Normals / observed points', title='Coverage (missing remains missing)', ylim=(-.05, 1.05)) axes[1, 1].legend(fontsize=8) fig.savefig(path, dpi=140); plt.close(fig)
def scale_plot(path, data): fig, axes = plt.subplots(1, 3, figsize=(15, 5), constrained_layout=True) for r in data['frames']: if 'scale_probe' not in r: continue rows = r['scale_probe'] x = [v['stride_px'] for v in rows] for ax, key in zip(axes[:2], ('angular_error_deg', 'variation_deg')): y = [v['larger_spacing'][key]['p95'] for v in rows] ax.plot(x, y, 'o-', label=f'f{r["source_frame"]}') axes[0].set(ylabel='p95 normal error (deg)', xlabel='Neighbour spacing (px)', title='Verified flat Peg ROI, shared safe region') axes[1].set(ylabel='p95 variation (deg)', xlabel='Neighbour spacing (px)', title='No averaging; same baseline extractor') for s in (1, 2, 4): rows = data['synthetic']['scale_sweep'] axes[2].plot([r['z0_m'] for r in rows], [next(v for v in r['rows'] if v['stride_px']==s)['larger_spacing']['variation_deg']['p95'] for r in rows], 'o-', label=f'synthetic stride={s}') axes[2].set(xlabel='Central depth (m)', ylabel='p95 variation (deg)', title='Tilted plane, fixed K and 1mm quantization') for ax in axes: ax.legend(fontsize=8); ax.grid(alpha=.2) fig.savefig(path, dpi=140); plt.close(fig)
def write_html(path, data): images = ['synthetic.png', 'distributions.png', 'scale_probe.png'] images += [f'f{s:04d}{suffix}.png' for s in data['selected_source_frames'] for suffix in ('', '_boundaries', '_profile')] body = ''.join(f'<p><a href="{p}"><img src="{p}" alt="{p}"></a></p>' for p in images if (path.parent/p).exists()) path.write_text(f'''<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task 02-A</title><style>body{{font:15px system-ui;max-width:1600px;margin:24px auto;padding:16px}}img{{width:100%}}pre{{white-space:pre-wrap}}</style><h1>Task 02-A — normal reliability and depth quantization</h1><p>Run {data['run_id']}; all {data['evaluated_frames']} saved frames; unchanged CPU NumPy extractor.<a href="diagnostics.json">Full numeric metrics, counts, histograms and parameters</a>.</p><p>Actual feature inputs are recorded depth, intrinsic and tracker masks only. GT defines evaluation regionsand oriented normal truth. Plane ROI: visible cuboid face, depth residual ≤1.5mm, 4mm from other faces,then 3px erosion independently per signed face. No selection by measured normal or variation.Hole rim requires analytic physical line proximity (4mm, 2px), not just a segmentation contour.</p><p>20° is a diagnostic threshold, not an edge class. All 5/10/20/30° rates and missing support are reported.Boundary ROIs can overlap; counts are not additive. Pooled values are pixel-frame weighted.Subsampling probes preserve pixel centres and compare baseline values on the same centres; they changeboth stencil span and normal-comparison separation. Only verified planar regions are compared.</p><p>GT annotations and analytic depth in NPZ are under evaluation/. They never replace observed depth.No smoothing, PCL, new production estimator, structural classification, sampling or Graph changes.</p>{body}<details><summary>Configuration</summary><pre>{html.escape(json.dumps(data['config'], indent=2))}</pre></details></html>''', encoding='utf-8')
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, default=REPO/'visual/data/step2/ep000.npz') parser.add_argument('--masks', type=Path, default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') parser.add_argument('--camera', default='base_camera') parser.add_argument('--out', type=Path, default=REPO/'visual/results/normal_diagnostics') args = parser.parse_args() print(evaluate(args.input, args.masks, output_root=args.out, camera=args.camera))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258"""Independent PCA5 implementation optimizations; Task 01/02-B stay unchanged.
Same observed 5x5 patch-local connected component, minimum six points, cameraorientation and rank gates. Complete patches use reusable box moments; partialpatches retain explicit connectivity. Float64 is retained throughout PCA."""from __future__ import annotations
from time import perf_counterfrom concurrent.futures import ThreadPoolExecutorfrom functools import lru_cacheimport numpy as npfrom scipy.ndimage import minimum_filter, uniform_filter
from visual.runtime.geometry import ( GeometricFeatures, GeometryFrame, GeometryParameters, OrganizedGeometry, compute_geometric_features,)from visual.runtime.rgbd import BOX, PEGfrom visual.runtime.normal_estimators import _assign, _empty, _jump
def build_geometry(frame): """Dense broadcasting of the original backprojection, same operation order.""" depth = np.asarray(frame.depth) k = np.asarray(frame.intrinsic, dtype=np.float64) if depth.ndim != 2 or not min(depth.shape) or not np.issubdtype(depth.dtype, np.floating): raise ValueError('depth must be a nonempty floating point (H,W) array') if (k.shape != (3, 3) or not np.isfinite(k).all() or k[0, 0] <= 0 or k[1, 1] <= 0 or not np.allclose(k[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1])): raise ValueError('invalid zero-skew CV intrinsic') if set(frame.masks)-{PEG, BOX}: raise ValueError('unknown object ID') masks = {} for oid in (PEG, BOX): mask = np.asarray(frame.masks.get(oid, np.zeros(depth.shape, bool))) if mask.shape != depth.shape or mask.dtype != np.bool_: raise ValueError('object masks must be boolean (H,W)') masks[oid] = mask.copy() valid = np.isfinite(depth) & (depth > 0) z = np.where(valid, depth, 0) xyz = np.empty((*depth.shape, 3), np.float32) xyz[..., 0] = (np.arange(depth.shape[1])[None, :]+.5-k[0, 2])*z/k[0, 0] xyz[..., 1] = (np.arange(depth.shape[0])[:, None]+.5-k[1, 2])*z/k[1, 1] xyz[..., 2] = z if not np.isfinite(xyz).all(): raise ValueError('depth/intrinsic must yield representable float32 XYZ') xyz[~valid] = np.nan return OrganizedGeometry(xyz, valid, masks, masks[PEG] & masks[BOX])
def _bounds(mask, halo): v, u = np.nonzero(mask) if not len(v): return None return (slice(max(0, v.min()-halo), min(mask.shape[0], v.max()+halo+1)), slice(max(0, u.min()-halo), min(mask.shape[1], u.max()+halo+1)))
def covariance_patches(xyz, support, centres, parameters, *, batch_size=4096): """Original partial-patch covariance, using globally precomputed unit links.""" n = len(centres) covariance = np.zeros((n, 3, 3), float) enough = np.zeros(n, bool) if not n: return covariance, enough h, w = support.shape z = np.where(support, xyz[..., 2], 0) horizontal = support[:, :-1] & support[:, 1:] & ~_jump(z[:, :-1], z[:, 1:], parameters) vertical = support[:-1] & support[1:] & ~_jump(z[:-1], z[1:], parameters) horizontal = np.pad(horizontal, ((0, 0), (0, 1))) vertical = np.pad(vertical, ((0, 1), (0, 0))) dv, du = np.meshgrid(np.arange(-2, 3), np.arange(-2, 3), indexing='ij') for start in range(0, n, batch_size): vu = centres[start:start+batch_size] v, u = vu[:, 0, None, None]+dv, vu[:, 1, None, None]+du inside = (v >= 0) & (v < h) & (u >= 0) & (u < w) v, u = np.clip(v, 0, h-1), np.clip(u, 0, w-1) available = inside & support[v, u] hl = horizontal[v[:, :, :-1], u[:, :, :-1]] & available[:, :, :-1] & available[:, :, 1:] vl = vertical[v[:, :-1], u[:, :-1]] & available[:, :-1] & available[:, 1:] # 25 patch vertices fit in one uint32. Links encode their source bit; # no horizontal wrap because a row's last source bit is always zero. bit = np.left_shift(np.uint32(1), np.arange(25, dtype=np.uint32)).reshape(5, 5) right = np.sum(hl.astype(np.uint32)*bit[:, :-1], axis=(1, 2), dtype=np.uint32) down = np.sum(vl.astype(np.uint32)*bit[:-1], axis=(1, 2), dtype=np.uint32) reached_bits = np.full(len(vu), np.uint32(1 << 12)) for _ in range(24): nxt = (reached_bits | ((reached_bits & right) << np.uint32(1)) | ((reached_bits >> np.uint32(1)) & right) | ((reached_bits & down) << np.uint32(5)) | ((reached_bits >> np.uint32(5)) & down)) if np.array_equal(nxt, reached_bits): break reached_bits = nxt reached = ((reached_bits[:, None, None] & bit) != 0) count = reached.sum((1, 2)) good = count >= 6 enough[start:start+len(vu)] = good chosen = np.flatnonzero(good) if not len(chosen): continue delta = np.where(reached[good, ..., None], xyz[v[good], u[good]]-xyz[vu[good, 0], vu[good, 1]][:, None, None], 0) mean = delta.sum((1, 2))/count[good, None] c = np.einsum('nijk,nijl->nkl', delta, delta)/count[good, None, None] c -= mean[:, :, None]*mean[:, None, :] covariance[start+chosen] = c return covariance, enough
def smallest_eigenvector(covariance): """Closed-form symmetric 3x3 eigensystem with residual/degeneracy fallback.
Solves the same eigenproblem, not z=f(x,y) regression. Near a repeated eigenvalue or an inaccurate residual, use the original LAPACK eigensolver. """ n = len(covariance) if not n: return np.empty((0, 3)), np.empty((0, 3)), 0 scale = np.max(np.abs(covariance), axis=(1, 2)) a = covariance/np.where(scale > 0, scale, 1)[:, None, None] q = np.trace(a, axis1=1, axis2=2)/3 b = a-q[:, None, None]*np.eye(3) p = np.sqrt(np.sum(b*b, axis=(1, 2))/6) c = b/np.where(p > 0, p, 1)[:, None, None] determinant = (c[:, 0, 0]*(c[:, 1, 1]*c[:, 2, 2]-c[:, 1, 2]**2) -c[:, 0, 1]*(c[:, 0, 1]*c[:, 2, 2]-c[:, 1, 2]*c[:, 0, 2]) +c[:, 0, 2]*(c[:, 0, 1]*c[:, 1, 2]-c[:, 1, 1]*c[:, 0, 2])) phi = np.arccos(np.clip(determinant/2, -1, 1))/3 largest = q+2*p*np.cos(phi) smallest = q+2*p*np.cos(phi+2*np.pi/3) middle = 3*q-smallest-largest eigenvalues = np.column_stack((smallest, middle, largest))*scale[:, None] rows = a-smallest[:, None, None]*np.eye(3) crosses = np.stack((np.cross(rows[:, 0], rows[:, 1]), np.cross(rows[:, 0], rows[:, 2]), np.cross(rows[:, 1], rows[:, 2])), axis=1) norms = np.sum(crosses*crosses, axis=2) vectors = crosses[np.arange(n), norms.argmax(1)] lengths = np.linalg.norm(vectors, axis=1) vectors /= np.where(lengths > 0, lengths, 1)[:, None] residual = np.linalg.norm(np.einsum('nij,nj->ni', a, vectors)-smallest[:, None]*vectors, axis=1) threshold = np.maximum(1e-16, eigenvalues[:, 2]*1e-8) # Preserve delicate original rank decisions with LAPACK, too. delicate = ((eigenvalues[:, 1] <= threshold*100) | (eigenvalues[:, 1]-eigenvalues[:, 0] <= threshold*100)) fallback = (lengths < 1e-10) | (residual > 1e-10) | delicate | ~np.isfinite(residual) if fallback.any(): values, basis = np.linalg.eigh(covariance[fallback]) eigenvalues[fallback], vectors[fallback] = values, basis[:, :, 0] return eigenvalues, vectors, int(fallback.sum())
def local_plane_optimized(geometry, object_id, parameters=GeometryParameters(), *, solver='eigh', profile=None): if solver not in ('eigh', 'analytic'): raise ValueError('solver must be eigh or analytic') t0 = perf_counter() normals, valid = _empty(geometry) support_full = geometry.observed_mask(object_id) bounds = _bounds(support_full, 2) if bounds is None: if profile is not None: profile.update(points=0, fast_points=0, partial_points=0) return normals, valid support = support_full[bounds] xyz = geometry.xyz[bounds].astype(float) v, u = np.nonzero(support); vu = np.column_stack((v, u)) z = np.where(support, xyz[..., 2], 0) hl = np.zeros_like(support); vl = np.zeros_like(support) hl[:, :-1] = support[:, :-1] & support[:, 1:] & ~_jump(z[:, :-1], z[:, 1:], parameters) vl[:-1] = support[:-1] & support[1:] & ~_jump(z[:-1], z[1:], parameters) fast_map = (minimum_filter(support, size=5, mode='constant', cval=0) & minimum_filter(hl, size=(5, 4), mode='constant', cval=0) & minimum_filter(vl, size=(4, 5), mode='constant', cval=0)) fast = fast_map[v, u] t1 = perf_counter() covariance = np.zeros((len(v), 3, 3), float) enough = fast.copy() if fast.any(): # A constant translation limits cancellation in second-moment sums. shifted = np.where(support[..., None], xyz-xyz[v[0], u[0]], 0) means = [uniform_filter(shifted[..., axis], size=5, mode='constant')[v[fast], u[fast]] for axis in range(3)] for i in range(3): for j in range(i, 3): value = uniform_filter(shifted[..., i]*shifted[..., j], size=5, mode='constant')[v[fast], u[fast]]-means[i]*means[j] covariance[fast, i, j] = value; covariance[fast, j, i] = value t2 = perf_counter() slow = ~fast if slow.any(): c, ok = covariance_patches(xyz, support, vu[slow], parameters) covariance[slow], enough[slow] = c, ok t3 = perf_counter() idx = np.flatnonzero(enough) fallback = 0 if solver == 'eigh': values, vectors = np.linalg.eigh(covariance[idx]); vectors = vectors[:, :, 0] else: values, vectors, fallback = smallest_eigenvector(covariance[idx]) rank2 = values[:, 1] > np.maximum(1e-16, values[:, 2]*1e-8) unique = values[:, 1]-values[:, 0] > np.maximum(1e-16, values[:, 2]*1e-8) good = rank2 & unique & np.isfinite(values).all(1) global_vu = vu[idx[good]]+np.array([bounds[0].start, bounds[1].start]) _assign(geometry, global_vu, vectors[good], normals, valid) t4 = perf_counter() if profile is not None: profile.update(points=len(v), fast_points=int(fast.sum()), partial_points=int(slow.sum()), eigen_fallback=fallback, prepare_ms=(t1-t0)*1000, box_moments_ms=(t2-t1)*1000, partial_connectivity_covariance_ms=(t3-t2)*1000, eigensystem_scatter_ms=(t4-t3)*1000) return normals, valid
def cropped_features(geometry, oid, normals, normal_valid, parameters=GeometryParameters()): """Same feature operator on all raw mask pixels + one neighbour halo.
This is computational cropping, never an evaluation ROI or point sampling. Outputs remain full-resolution and all true image boundaries are retained. """ mask = geometry.object_masks[oid] shape = mask.shape bounds = _bounds(mask, 1) arrays = dict(object_mask=mask, valid_points=geometry.observed_mask(oid), normals=normals, normal_valid=normal_valid) floating = {'depth_jump_m', 'normal_variation_rad'} for key in GeometricFeatures.__dataclass_fields__: if key in arrays: continue arrays[key] = (np.full(shape, np.nan, np.float32) if key in floating else np.zeros(shape, np.uint8 if key=='normal_neighbor_count' else bool)) if bounds is not None: cropped = OrganizedGeometry(geometry.xyz[bounds], geometry.valid_depth[bounds], {i: m[bounds] for i, m in geometry.object_masks.items()}, geometry.overlap_mask[bounds]) result = compute_geometric_features(cropped, oid, normals[bounds], normal_valid[bounds], parameters) for key in arrays: if key not in ('object_mask', 'valid_points', 'normals', 'normal_valid'): arrays[key][bounds] = getattr(result, key) return GeometricFeatures(**arrays)
@lru_cache(maxsize=1)def _two_object_executor(): return ThreadPoolExecutor(max_workers=2, thread_name_prefix='pca5-object')
def process_optimized(frame, parameters=GeometryParameters(), *, solver='eigh', profile=None, parallel=False): start = perf_counter(); geometry = build_geometry(frame); after_geometry = perf_counter() profiles = {i: {} for i in geometry.object_masks} if parallel: executor=_two_object_executor() futures={i:executor.submit(local_plane_optimized,geometry,i,parameters,solver=solver,profile=profiles[i]) for i in geometry.object_masks} normals={i:f.result() for i,f in futures.items()} else: normals = {i: local_plane_optimized(geometry, i, parameters, solver=solver, profile=profiles[i]) for i in geometry.object_masks} after_normals = perf_counter() if parallel: futures={i:executor.submit(cropped_features,geometry,i,*normals[i],parameters) for i in geometry.object_masks} objects={i:f.result() for i,f in futures.items()} else: objects = {i: cropped_features(geometry, i, *normals[i], parameters) for i in geometry.object_masks} end = perf_counter() if profile is not None: profile.update(profiles) return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, objects, dict(geometry=(after_geometry-start)*1000, normals=(after_normals-after_geometry)*1000, discontinuity_features=(end-after_normals)*1000, total=(end-start)*1000))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990<!doctype html><html lang="en"><meta charset="utf-8"><title>Task03-AB adaptive total node budget</title><style>body{font:15px system-ui;max-width:1500px;margin:28px auto;padding:0 16px;color:#17212b}img{width:100%;margin:15px 0}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{padding:7px;border:1px solid #ccd3da;text-align:right}th:first-child,td:first-child{text-align:left}pre{white-space:pre-wrap}a{color:#146cb2}</style><h1>Task03-AB — Adaptive Total Node Budget</h1><p>Run f68c59f210b5499dadc7e962c7f64492. CPU only; ep000 source 0–120. All 121-frame gates passed before adaptive geometry evaluation.</p><p>First positive valid support fixes the causal reference. Pixel area is projected area, not physical 3D surface area. FixedMatched uses episode counts offline. Same S3 / 20° / .25 / seed0 / 3D FPS; Priority cap changes with requested budget.</p><p>Joint matcher: the same pair within 2px AND 3mm. Retention denominator is tracker-observable references. N/A is preserved. Gray bands mark recorded Box support loss, not independently proven occlusion. Sampling latency excludes PCA5 extraction, GT and I/O; aliases have no invented FPS calls. No GNN/BC, stale-cache integration, GPU or end-to-end 20Hz claim.</p><p><a href="adaptive_node_budget.json">Summary/config</a> · <a href="frame_metrics.json">All frame metrics</a> · <a href="latency.json">Raw/aggregated timing</a> · <a href="verification.json">Gates/preservation</a> · <a href="tests.log">Tests</a> · <a href="implementation.patch">Implementation diff</a></p><table><tr><th>Condition</th><th>Mean N</th><th>Median N</th><th>Reduction %</th><th>Peg retention %</th><th>Box retention %</th><th>Peg surface p95 mm</th><th>Box surface p95 mm</th></tr><tr><td>Fixed256</td><td>256.000</td><td>256.000</td><td>0.000</td><td>61.285</td><td>11.429</td><td>7.019</td><td>16.277</td></tr><tr><td>Adaptive</td><td>94.893</td><td>78.000</td><td>62.933</td><td>28.161</td><td>7.766</td><td>11.701</td><td>22.244</td></tr><tr><td>FixedMatched</td><td>95.000</td><td>95.000</td><td>62.891</td><td>25.909</td><td>6.227</td><td>12.050</td><td>34.515</td></tr></table><a href="plots/budget_timeseries.png"><img src="plots/budget_timeseries.png" alt="budget_timeseries"></a><a href="plots/latency_depth.png"><img src="plots/latency_depth.png" alt="latency_depth"></a><a href="plots/preservation_temporal.png"><img src="plots/preservation_temporal.png" alt="preservation_temporal"></a><h2>Representative frames</h2><a href="frames/f0000_overlay.png"><img src="frames/f0000_overlay.png" alt="Source 0"></a><a href="frames/f0015_overlay.png"><img src="frames/f0015_overlay.png" alt="Source 15"></a><a href="frames/f0018_overlay.png"><img src="frames/f0018_overlay.png" alt="Source 18"></a><a href="frames/f0045_overlay.png"><img src="frames/f0045_overlay.png" alt="Source 45"></a><a href="frames/f0080_overlay.png"><img src="frames/f0080_overlay.png" alt="Source 80"></a><a href="frames/f0120_overlay.png"><img src="frames/f0120_overlay.png" alt="Source 120"></a><h2>All frame artifacts</h2><table><tr><th>Source</th><th>Peg raw</th><th>Peg valid</th><th>Box raw</th><th>Box valid</th><th>Fixed256</th><th>Adaptive</th><th>FixedMatched</th><th>Files</th></tr><tr><td>0</td><td>11780</td><td>11780</td><td>11665</td><td>11665</td><td>256</td><td>256</td><td>95</td><td><a href="frames/f0000_samples.npz">NPZ</a> <a href="frames/f0000_overlay.png">overlay</a></td></tr><tr><td>1</td><td>11805</td><td>11805</td><td>11755</td><td>11755</td><td>256</td><td>256</td><td>95</td><td><a href="frames/f0001_samples.npz">NPZ</a></td></tr><tr><td>2</td><td>11803</td><td>11803</td><td>11665</td><td>11665</td><td>256</td><td>256</td><td>95</td><td><a href="frames/f0002_samples.npz">NPZ</a></td></tr><tr><td>3</td><td>11798</td><td>11798</td><td>11184</td><td>11184</td><td>256</td><td>251</td><td>95</td><td><a href="frames/f0003_samples.npz">NPZ</a></td></tr><tr><td>4</td><td>11796</td><td>11796</td><td>10557</td><td>10557</td><td>256</td><td>244</td><td>95</td><td><a href="frames/f0004_samples.npz">NPZ</a></td></tr><tr><td>5</td><td>11794</td><td>11794</td><td>10010</td><td>10010</td><td>256</td><td>238</td><td>95</td><td><a href="frames/f0005_samples.npz">NPZ</a></td></tr><tr><td>6</td><td>11792</td><td>11792</td><td>9415</td><td>9415</td><td>256</td><td>232</td><td>95</td><td><a href="frames/f0006_samples.npz">NPZ</a></td></tr><tr><td>7</td><td>11789</td><td>11789</td><td>8664</td><td>8664</td><td>256</td><td>223</td><td>95</td><td><a href="frames/f0007_samples.npz">NPZ</a></td></tr><tr><td>8</td><td>11789</td><td>11789</td><td>7878</td><td>7878</td><td>256</td><td>215</td><td>95</td><td><a href="frames/f0008_samples.npz">NPZ</a></td></tr><tr><td>9</td><td>11789</td><td>11789</td><td>7135</td><td>7135</td><td>256</td><td>207</td><td>95</td><td><a href="frames/f0009_samples.npz">NPZ</a></td></tr><tr><td>10</td><td>11786</td><td>11786</td><td>6395</td><td>6395</td><td>256</td><td>199</td><td>95</td><td><a href="frames/f0010_samples.npz">NPZ</a></td></tr><tr><td>11</td><td>11779</td><td>11779</td><td>5598</td><td>5598</td><td>256</td><td>190</td><td>95</td><td><a href="frames/f0011_samples.npz">NPZ</a></td></tr><tr><td>12</td><td>11781</td><td>11781</td><td>4710</td><td>4710</td><td>256</td><td>180</td><td>95</td><td><a href="frames/f0012_samples.npz">NPZ</a></td></tr><tr><td>13</td><td>11771</td><td>11771</td><td>3690</td><td>3690</td><td>256</td><td>169</td><td>95</td><td><a href="frames/f0013_samples.npz">NPZ</a></td></tr><tr><td>14</td><td>11706</td><td>11706</td><td>2855</td><td>2855</td><td>256</td><td>159</td><td>95</td><td><a href="frames/f0014_samples.npz">NPZ</a></td></tr><tr><td>15</td><td>11479</td><td>11479</td><td>2038</td><td>2038</td><td>256</td><td>148</td><td>95</td><td><a href="frames/f0015_samples.npz">NPZ</a> <a href="frames/f0015_overlay.png">overlay</a></td></tr><tr><td>16</td><td>11224</td><td>11224</td><td>1112</td><td>1112</td><td>256</td><td>135</td><td>95</td><td><a href="frames/f0016_samples.npz">NPZ</a></td></tr><tr><td>17</td><td>11057</td><td>11057</td><td>290</td><td>290</td><td>256</td><td>124</td><td>95</td><td><a href="frames/f0017_samples.npz">NPZ</a></td></tr><tr><td>18</td><td>10913</td><td>10913</td><td>0</td><td>0</td><td>256</td><td>119</td><td>95</td><td><a href="frames/f0018_samples.npz">NPZ</a> <a href="frames/f0018_overlay.png">overlay</a></td></tr><tr><td>19</td><td>10451</td><td>10451</td><td>0</td><td>0</td><td>256</td><td>114</td><td>95</td><td><a href="frames/f0019_samples.npz">NPZ</a></td></tr><tr><td>20</td><td>10045</td><td>10045</td><td>0</td><td>0</td><td>256</td><td>110</td><td>95</td><td><a href="frames/f0020_samples.npz">NPZ</a></td></tr><tr><td>21</td><td>9780</td><td>9780</td><td>0</td><td>0</td><td>256</td><td>107</td><td>95</td><td><a href="frames/f0021_samples.npz">NPZ</a></td></tr><tr><td>22</td><td>9643</td><td>9643</td><td>0</td><td>0</td><td>256</td><td>105</td><td>95</td><td><a href="frames/f0022_samples.npz">NPZ</a></td></tr><tr><td>23</td><td>9587</td><td>9587</td><td>0</td><td>0</td><td>256</td><td>105</td><td>95</td><td><a href="frames/f0023_samples.npz">NPZ</a></td></tr><tr><td>24</td><td>9592</td><td>9592</td><td>0</td><td>0</td><td>256</td><td>105</td><td>95</td><td><a href="frames/f0024_samples.npz">NPZ</a></td></tr><tr><td>25</td><td>9589</td><td>9589</td><td>0</td><td>0</td><td>256</td><td>105</td><td>95</td><td><a href="frames/f0025_samples.npz">NPZ</a></td></tr><tr><td>26</td><td>9417</td><td>9417</td><td>0</td><td>0</td><td>256</td><td>103</td><td>95</td><td><a href="frames/f0026_samples.npz">NPZ</a></td></tr><tr><td>27</td><td>9013</td><td>9013</td><td>209</td><td>208</td><td>256</td><td>101</td><td>95</td><td><a href="frames/f0027_samples.npz">NPZ</a></td></tr><tr><td>28</td><td>8474</td><td>8474</td><td>793</td><td>793</td><td>256</td><td>101</td><td>95</td><td><a href="frames/f0028_samples.npz">NPZ</a></td></tr><tr><td>29</td><td>7771</td><td>7771</td><td>1407</td><td>1406</td><td>256</td><td>100</td><td>95</td><td><a href="frames/f0029_samples.npz">NPZ</a></td></tr><tr><td>30</td><td>7146</td><td>7146</td><td>1983</td><td>1983</td><td>256</td><td>100</td><td>95</td><td><a href="frames/f0030_samples.npz">NPZ</a></td></tr><tr><td>31</td><td>6798</td><td>6798</td><td>2334</td><td>2333</td><td>256</td><td>100</td><td>95</td><td><a href="frames/f0031_samples.npz">NPZ</a></td></tr><tr><td>32</td><td>6656</td><td>6656</td><td>2486</td><td>2485</td><td>256</td><td>100</td><td>95</td><td><a href="frames/f0032_samples.npz">NPZ</a></td></tr><tr><td>33</td><td>6603</td><td>6603</td><td>2530</td><td>2529</td><td>256</td><td>100</td><td>95</td><td><a href="frames/f0033_samples.npz">NPZ</a></td></tr><tr><td>34</td><td>6601</td><td>6601</td><td>2530</td><td>2529</td><td>256</td><td>100</td><td>95</td><td><a href="frames/f0034_samples.npz">NPZ</a></td></tr><tr><td>35</td><td>6169</td><td>6169</td><td>2527</td><td>2526</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0035_samples.npz">NPZ</a></td></tr><tr><td>36</td><td>6162</td><td>6162</td><td>2537</td><td>2536</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0036_samples.npz">NPZ</a></td></tr><tr><td>37</td><td>6155</td><td>6155</td><td>2537</td><td>2536</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0037_samples.npz">NPZ</a></td></tr><tr><td>38</td><td>6156</td><td>6156</td><td>2537</td><td>2536</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0038_samples.npz">NPZ</a></td></tr><tr><td>39</td><td>6163</td><td>6163</td><td>2537</td><td>2536</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0039_samples.npz">NPZ</a></td></tr><tr><td>40</td><td>6152</td><td>6152</td><td>2539</td><td>2537</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0040_samples.npz">NPZ</a></td></tr><tr><td>41</td><td>6203</td><td>6203</td><td>2539</td><td>2537</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0041_samples.npz">NPZ</a></td></tr><tr><td>42</td><td>6201</td><td>6201</td><td>2539</td><td>2537</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0042_samples.npz">NPZ</a></td></tr><tr><td>43</td><td>6201</td><td>6201</td><td>2540</td><td>2538</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0043_samples.npz">NPZ</a></td></tr><tr><td>44</td><td>6202</td><td>6202</td><td>2540</td><td>2538</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0044_samples.npz">NPZ</a></td></tr><tr><td>45</td><td>6204</td><td>6204</td><td>2541</td><td>2539</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0045_samples.npz">NPZ</a> <a href="frames/f0045_overlay.png">overlay</a></td></tr><tr><td>46</td><td>6202</td><td>6202</td><td>2541</td><td>2539</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0046_samples.npz">NPZ</a></td></tr><tr><td>47</td><td>6194</td><td>6194</td><td>2542</td><td>2540</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0047_samples.npz">NPZ</a></td></tr><tr><td>48</td><td>6234</td><td>6234</td><td>2542</td><td>2540</td><td>256</td><td>96</td><td>95</td><td><a href="frames/f0048_samples.npz">NPZ</a></td></tr><tr><td>49</td><td>6200</td><td>6200</td><td>2542</td><td>2540</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0049_samples.npz">NPZ</a></td></tr><tr><td>50</td><td>6227</td><td>6227</td><td>2502</td><td>2500</td><td>256</td><td>95</td><td>95</td><td><a href="frames/f0050_samples.npz">NPZ</a></td></tr><tr><td>51</td><td>6303</td><td>6303</td><td>2262</td><td>2260</td><td>256</td><td>94</td><td>95</td><td><a href="frames/f0051_samples.npz">NPZ</a></td></tr><tr><td>52</td><td>6480</td><td>6480</td><td>1803</td><td>1797</td><td>256</td><td>90</td><td>95</td><td><a href="frames/f0052_samples.npz">NPZ</a></td></tr><tr><td>53</td><td>6688</td><td>6688</td><td>1180</td><td>1174</td><td>256</td><td>86</td><td>95</td><td><a href="frames/f0053_samples.npz">NPZ</a></td></tr><tr><td>54</td><td>6930</td><td>6930</td><td>493</td><td>486</td><td>256</td><td>81</td><td>95</td><td><a href="frames/f0054_samples.npz">NPZ</a></td></tr><tr><td>55</td><td>7102</td><td>7102</td><td>35</td><td>35</td><td>256</td><td>78</td><td>95</td><td><a href="frames/f0055_samples.npz">NPZ</a></td></tr><tr><td>56</td><td>7212</td><td>7212</td><td>0</td><td>0</td><td>256</td><td>79</td><td>95</td><td><a href="frames/f0056_samples.npz">NPZ</a></td></tr><tr><td>57</td><td>7213</td><td>7213</td><td>0</td><td>0</td><td>256</td><td>79</td><td>95</td><td><a href="frames/f0057_samples.npz">NPZ</a></td></tr><tr><td>58</td><td>7259</td><td>7259</td><td>0</td><td>0</td><td>256</td><td>79</td><td>95</td><td><a href="frames/f0058_samples.npz">NPZ</a></td></tr><tr><td>59</td><td>7253</td><td>7253</td><td>0</td><td>0</td><td>256</td><td>79</td><td>95</td><td><a href="frames/f0059_samples.npz">NPZ</a></td></tr><tr><td>60</td><td>7134</td><td>7134</td><td>0</td><td>0</td><td>256</td><td>78</td><td>95</td><td><a href="frames/f0060_samples.npz">NPZ</a></td></tr><tr><td>61</td><td>6825</td><td>6825</td><td>0</td><td>0</td><td>256</td><td>75</td><td>95</td><td><a href="frames/f0061_samples.npz">NPZ</a></td></tr><tr><td>62</td><td>6420</td><td>6420</td><td>0</td><td>0</td><td>256</td><td>70</td><td>95</td><td><a href="frames/f0062_samples.npz">NPZ</a></td></tr><tr><td>63</td><td>5957</td><td>5957</td><td>0</td><td>0</td><td>256</td><td>65</td><td>95</td><td><a href="frames/f0063_samples.npz">NPZ</a></td></tr><tr><td>64</td><td>5459</td><td>5459</td><td>0</td><td>0</td><td>256</td><td>60</td><td>95</td><td><a href="frames/f0064_samples.npz">NPZ</a></td></tr><tr><td>65</td><td>5043</td><td>5043</td><td>0</td><td>0</td><td>256</td><td>55</td><td>95</td><td><a href="frames/f0065_samples.npz">NPZ</a></td></tr><tr><td>66</td><td>4650</td><td>4649</td><td>126</td><td>125</td><td>256</td><td>52</td><td>95</td><td><a href="frames/f0066_samples.npz">NPZ</a></td></tr><tr><td>67</td><td>4244</td><td>4240</td><td>208</td><td>204</td><td>256</td><td>49</td><td>95</td><td><a href="frames/f0067_samples.npz">NPZ</a></td></tr><tr><td>68</td><td>3861</td><td>3855</td><td>409</td><td>403</td><td>256</td><td>46</td><td>95</td><td><a href="frames/f0068_samples.npz">NPZ</a></td></tr><tr><td>69</td><td>3544</td><td>3537</td><td>624</td><td>617</td><td>256</td><td>45</td><td>95</td><td><a href="frames/f0069_samples.npz">NPZ</a></td></tr><tr><td>70</td><td>3268</td><td>3260</td><td>855</td><td>847</td><td>256</td><td>45</td><td>95</td><td><a href="frames/f0070_samples.npz">NPZ</a></td></tr><tr><td>71</td><td>3075</td><td>3065</td><td>1134</td><td>1124</td><td>256</td><td>46</td><td>95</td><td><a href="frames/f0071_samples.npz">NPZ</a></td></tr><tr><td>72</td><td>2903</td><td>2897</td><td>1417</td><td>1411</td><td>256</td><td>47</td><td>95</td><td><a href="frames/f0072_samples.npz">NPZ</a></td></tr><tr><td>73</td><td>2794</td><td>2782</td><td>1720</td><td>1708</td><td>256</td><td>49</td><td>95</td><td><a href="frames/f0073_samples.npz">NPZ</a></td></tr><tr><td>74</td><td>2662</td><td>2654</td><td>2032</td><td>2024</td><td>256</td><td>51</td><td>95</td><td><a href="frames/f0074_samples.npz">NPZ</a></td></tr><tr><td>75</td><td>2568</td><td>2562</td><td>2252</td><td>2246</td><td>256</td><td>52</td><td>95</td><td><a href="frames/f0075_samples.npz">NPZ</a></td></tr><tr><td>76</td><td>2596</td><td>2574</td><td>2500</td><td>2478</td><td>256</td><td>55</td><td>95</td><td><a href="frames/f0076_samples.npz">NPZ</a></td></tr><tr><td>77</td><td>2525</td><td>2499</td><td>2652</td><td>2626</td><td>256</td><td>56</td><td>95</td><td><a href="frames/f0077_samples.npz">NPZ</a></td></tr><tr><td>78</td><td>2505</td><td>2471</td><td>2727</td><td>2693</td><td>256</td><td>56</td><td>95</td><td><a href="frames/f0078_samples.npz">NPZ</a></td></tr><tr><td>79</td><td>2528</td><td>2492</td><td>2730</td><td>2694</td><td>256</td><td>57</td><td>95</td><td><a href="frames/f0079_samples.npz">NPZ</a></td></tr><tr><td>80</td><td>2525</td><td>2491</td><td>2742</td><td>2708</td><td>256</td><td>57</td><td>95</td><td><a href="frames/f0080_samples.npz">NPZ</a> <a href="frames/f0080_overlay.png">overlay</a></td></tr><tr><td>81</td><td>2551</td><td>2515</td><td>2746</td><td>2710</td><td>256</td><td>57</td><td>95</td><td><a href="frames/f0081_samples.npz">NPZ</a></td></tr><tr><td>82</td><td>2575</td><td>2548</td><td>2787</td><td>2760</td><td>256</td><td>58</td><td>95</td><td><a href="frames/f0082_samples.npz">NPZ</a></td></tr><tr><td>83</td><td>2521</td><td>2504</td><td>2797</td><td>2780</td><td>256</td><td>58</td><td>95</td><td><a href="frames/f0083_samples.npz">NPZ</a></td></tr><tr><td>84</td><td>2628</td><td>2598</td><td>2735</td><td>2705</td><td>256</td><td>58</td><td>95</td><td><a href="frames/f0084_samples.npz">NPZ</a></td></tr><tr><td>85</td><td>2642</td><td>2612</td><td>2806</td><td>2776</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0085_samples.npz">NPZ</a></td></tr><tr><td>86</td><td>2648</td><td>2617</td><td>2800</td><td>2769</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0086_samples.npz">NPZ</a></td></tr><tr><td>87</td><td>2636</td><td>2601</td><td>2814</td><td>2779</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0087_samples.npz">NPZ</a></td></tr><tr><td>88</td><td>2616</td><td>2578</td><td>2827</td><td>2789</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0088_samples.npz">NPZ</a></td></tr><tr><td>89</td><td>2608</td><td>2567</td><td>2832</td><td>2791</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0089_samples.npz">NPZ</a></td></tr><tr><td>90</td><td>2598</td><td>2560</td><td>2834</td><td>2796</td><td>256</td><td>58</td><td>95</td><td><a href="frames/f0090_samples.npz">NPZ</a></td></tr><tr><td>91</td><td>2598</td><td>2558</td><td>2845</td><td>2805</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0091_samples.npz">NPZ</a></td></tr><tr><td>92</td><td>2599</td><td>2558</td><td>2847</td><td>2806</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0092_samples.npz">NPZ</a></td></tr><tr><td>93</td><td>2600</td><td>2557</td><td>2848</td><td>2805</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0093_samples.npz">NPZ</a></td></tr><tr><td>94</td><td>2606</td><td>2565</td><td>2847</td><td>2806</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0094_samples.npz">NPZ</a></td></tr><tr><td>95</td><td>2605</td><td>2564</td><td>2844</td><td>2803</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0095_samples.npz">NPZ</a></td></tr><tr><td>96</td><td>2605</td><td>2562</td><td>2844</td><td>2801</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0096_samples.npz">NPZ</a></td></tr><tr><td>97</td><td>2605</td><td>2560</td><td>2844</td><td>2799</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0097_samples.npz">NPZ</a></td></tr><tr><td>98</td><td>2610</td><td>2564</td><td>2842</td><td>2796</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0098_samples.npz">NPZ</a></td></tr><tr><td>99</td><td>2583</td><td>2537</td><td>2868</td><td>2822</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0099_samples.npz">NPZ</a></td></tr><tr><td>100</td><td>2507</td><td>2460</td><td>2935</td><td>2888</td><td>256</td><td>58</td><td>95</td><td><a href="frames/f0100_samples.npz">NPZ</a></td></tr><tr><td>101</td><td>2445</td><td>2395</td><td>3025</td><td>2975</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0101_samples.npz">NPZ</a></td></tr><tr><td>102</td><td>2322</td><td>2251</td><td>3252</td><td>3181</td><td>256</td><td>59</td><td>95</td><td><a href="frames/f0102_samples.npz">NPZ</a></td></tr><tr><td>103</td><td>2135</td><td>2083</td><td>3583</td><td>3531</td><td>256</td><td>61</td><td>95</td><td><a href="frames/f0103_samples.npz">NPZ</a></td></tr><tr><td>104</td><td>2022</td><td>1982</td><td>3920</td><td>3880</td><td>256</td><td>64</td><td>95</td><td><a href="frames/f0104_samples.npz">NPZ</a></td></tr><tr><td>105</td><td>1890</td><td>1822</td><td>4231</td><td>4163</td><td>256</td><td>65</td><td>95</td><td><a href="frames/f0105_samples.npz">NPZ</a></td></tr><tr><td>106</td><td>1786</td><td>1720</td><td>4495</td><td>4429</td><td>256</td><td>67</td><td>95</td><td><a href="frames/f0106_samples.npz">NPZ</a></td></tr><tr><td>107</td><td>1714</td><td>1647</td><td>4741</td><td>4674</td><td>256</td><td>69</td><td>95</td><td><a href="frames/f0107_samples.npz">NPZ</a></td></tr><tr><td>108</td><td>1709</td><td>1634</td><td>4938</td><td>4863</td><td>256</td><td>71</td><td>95</td><td><a href="frames/f0108_samples.npz">NPZ</a></td></tr><tr><td>109</td><td>1585</td><td>1529</td><td>5138</td><td>5082</td><td>256</td><td>72</td><td>95</td><td><a href="frames/f0109_samples.npz">NPZ</a></td></tr><tr><td>110</td><td>1480</td><td>1439</td><td>5345</td><td>5304</td><td>256</td><td>74</td><td>95</td><td><a href="frames/f0110_samples.npz">NPZ</a></td></tr><tr><td>111</td><td>1414</td><td>1354</td><td>5560</td><td>5500</td><td>256</td><td>75</td><td>95</td><td><a href="frames/f0111_samples.npz">NPZ</a></td></tr><tr><td>112</td><td>1329</td><td>1279</td><td>5719</td><td>5669</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0112_samples.npz">NPZ</a></td></tr><tr><td>113</td><td>1295</td><td>1249</td><td>5760</td><td>5714</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0113_samples.npz">NPZ</a></td></tr><tr><td>114</td><td>1307</td><td>1261</td><td>5743</td><td>5697</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0114_samples.npz">NPZ</a></td></tr><tr><td>115</td><td>1311</td><td>1273</td><td>5690</td><td>5652</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0115_samples.npz">NPZ</a></td></tr><tr><td>116</td><td>1389</td><td>1348</td><td>5683</td><td>5642</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0116_samples.npz">NPZ</a></td></tr><tr><td>117</td><td>1391</td><td>1339</td><td>5692</td><td>5640</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0117_samples.npz">NPZ</a></td></tr><tr><td>118</td><td>1400</td><td>1343</td><td>5697</td><td>5640</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0118_samples.npz">NPZ</a></td></tr><tr><td>119</td><td>1404</td><td>1348</td><td>5691</td><td>5635</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0119_samples.npz">NPZ</a></td></tr><tr><td>120</td><td>1413</td><td>1353</td><td>5678</td><td>5618</td><td>256</td><td>76</td><td>95</td><td><a href="frames/f0120_samples.npz">NPZ</a> <a href="frames/f0120_overlay.png">overlay</a></td></tr></table><h2>Original read-only dependencies</h2><ul><li><a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json">original_comparison</a></li><li><a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.html">original_html</a></li><li><a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz">original_samples_frame0</a></li><li><a href="../../visual/data/step2/ep000.npz">rgbd</a></li><li><a href="../../visual/results/runtime_tracking/ep000/masks.npz">tracker_masks</a></li></ul><details><summary>Policy / reference / matched control</summary><pre>{ "policy": { "alpha": 1, "reference": 23445, "reference_source": 0, "rounding": "integer half-up", "maximum": 256, "minimum": "sum min(16, current object support)" }, "reference": { "source_frame": 0, "frame_idx": 0, "timestamp": 0.0, "shape": [ 512, 512 ], "camera": "base_camera", "intrinsic": [ [ 256.0, 0.0, 256.0 ], [ 0.0, 256.0, 256.0 ], [ 0.0, 0.0, 1.0 ] ], "cam2world": [ [ 1.0, 0.0, 0.0, -3.725290298461914e-09 ], [ 0.0, -0.3162277638912201, 0.9486833214759827, -0.30000004172325134 ], [ -0.0, -0.9486832618713379, -0.3162277638912201, 0.20000000298023224 ], [ 0.0, 0.0, 0.0, 1.0 ] ], "areas": { "peg": { "raw": 11780, "valid": 11780, "invalid_depth": 0, "positive_depth_overlap": 0, "minimum": 16 }, "box": { "raw": 11665, "valid": 11665, "invalid_depth": 0, "positive_depth_overlap": 0, "minimum": 16 } }, "unit": "projected pixel count" }, "matched": { "budget": 95, "adaptive_selected_sum": 11482, "fixed_selected_sum": 11495, "mean_error_nodes": 0.10743801652892562, "causal_online": false, "selection": "count-only absolute total difference; smaller integer on ties" }}</pre></details></html>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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""Task03 observation provenance, budgets, geometry and regression contracts."""from dataclasses import replace, fieldsimport unittestimport numpy as np
from visual.runtime.geometry import build_organized_geometry, compute_geometric_features, process_geometry, GeometryParametersfrom visual.runtime.rgbd import PEG, BOXfrom visual.runtime.sampling import (SamplingConfig, allocate_budget, fps_indices, extract_sampling_evidence, extract_candidates, sample_points)from visual.runtime.test.normal_diagnostics import synthetic_frame, synthetic_case, quantizefrom visual.runtime.test.normal_estimators import local_planefrom visual.runtime.test.structural_edges import compare
K = np.array([[256., 0, 32], [0, 256., 32], [0, 0, 1]])
class SamplingTests(unittest.TestCase): def frame(self, n=64): depth = np.full((n, n), .25, np.float32) peg = np.zeros((n, n), bool); peg[2:n//2-1, 2:-2] = True box = np.zeros_like(peg); box[n//2+1:-2, 2:-2] = True return replace(synthetic_frame(depth, K, peg), masks={PEG: peg, BOX: box})
def evidence(self, frame=None, method='pca5'): return extract_sampling_evidence(self.frame() if frame is None else frame, method)
def test_budget_ratio_observed_uniqueness_alignment_and_reproducibility(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) e = self.evidence(f) for budget in (64, 128, 256, 512): for ratio in (0., .125, .25, .5, 1.): cfg = SamplingConfig(num_points=budget, structural_ratio=ratio) a = sample_points(e, cfg); b = sample_points(e, cfg) self.assertLessEqual(len(a.points), budget) self.assertLessEqual(int(a.priority_selected.sum()), int(budget*ratio)) self.assertEqual(len(np.unique(a.flat_index)), len(a.points)) np.testing.assert_array_equal(a.flat_index, b.flat_index) v, u = a.pixels_vu.T np.testing.assert_array_equal(a.flat_index, v*f.depth.shape[1]+u) np.testing.assert_array_equal(a.points, e.frame.geometry.xyz[v, u]) c = extract_candidates(e, cfg) for oid in (PEG, BOX): chosen = a.object_id == oid rows = np.searchsorted(c[oid].flat_index, a.flat_index[chosen]) self.assertTrue(e.frame.geometry.observed_mask(oid)[v[chosen], u[chosen]].all()) for name, values in a.metadata.items(): np.testing.assert_array_equal(values[chosen], c[oid].metadata[name][rows], err_msg=name) for field in fields(a): if field.name not in ('timings_ms', 'metadata'): if isinstance(getattr(a, field.name), np.ndarray): np.testing.assert_array_equal(getattr(a, field.name), getattr(b, field.name))
def test_zero_ratio_matches_general_fps_for_every_method(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) cfg = SamplingConfig(structural_ratio=0) baseline = sample_points(self.evidence(f), cfg, method='S0') for method, est in [('S1', 'baseline'), ('S2', 'fd2'), ('S3', 'pca5'), ('S4', 'pca5')]: a = sample_points(self.evidence(f, est), cfg, method=method) np.testing.assert_array_equal(a.flat_index, baseline.flat_index) self.assertFalse(a.priority_selected.any())
def test_plane_has_no_invented_structural_and_equals_fps(self): e = self.evidence() for method in ('S3', 'S4'): a = sample_points(e, method=method); b = sample_points(e, method='S0') self.assertFalse(a.priority_selected.any()); self.assertFalse(a.metadata['structural_candidate'].any()) np.testing.assert_array_equal(a.flat_index, b.flat_index)
def test_minimums_and_configurable_observation_allocation(self): for counts in ((1000, 1000), (3, 1000), (1000, 3), (0, 1000), (1000, 0), (0, 0), (3, 4)): a = allocate_budget(64, counts, (16, 16)) self.assertEqual(int(a.sum()), min(64, sum(counts))) self.assertTrue((a <= counts).all()) self.assertTrue((a >= np.minimum(counts, [16, 16])).all()) np.testing.assert_array_equal(allocate_budget(64, (1000, 1000), (16, 16)), [32, 32]) a = allocate_budget(64, (100, 900), (8, 8)) np.testing.assert_array_equal(a, [13, 51]) e = self.evidence(); cfg = SamplingConfig(allocation='sqrt_observed_points', min_points=(8, 8)) self.assertEqual(len(sample_points(e, cfg).points), 256)
def test_one_object_empty_current_observation_no_cache(self): for absent in (PEG, BOX): f = self.frame(); masks = {i:m.copy() for i,m in f.masks.items()}; masks[absent][:] = False a = sample_points(self.evidence(replace(f, masks=masks))) self.assertEqual(a.counts[absent]['selected'], 0) self.assertEqual(a.counts[1-absent]['selected'], 256)
def test_insufficient_both_empty_and_zero_budget(self): f = self.frame(); masks = {i:np.zeros_like(m) for i,m in f.masks.items()} for empty in (True, False): if not empty: masks[PEG][4, 4] = True; masks[BOX][40, 40] = True e = self.evidence(replace(f, masks=masks)); a = sample_points(e) self.assertEqual(len(a.points), 0 if empty else 2) self.assertEqual(a.points.shape[1:], (3,)); self.assertEqual(a.pixels_vu.shape[1:], (2,)) for values in a.metadata.values(): self.assertEqual(len(values), len(a.points)) a = sample_points(self.evidence(), SamplingConfig(num_points=0, min_points=(0, 0))) self.assertEqual(len(a.points), 0)
def test_invalid_config_is_explicit(self): cases = [dict(num_points=-1), dict(num_points=1.5), dict(num_points=True), dict(num_points=16), dict(structural_ratio=-.1), dict(structural_ratio=1.1), dict(structural_ratio=np.nan), dict(depth_priority_fraction=np.inf), dict(min_points=(-1, 1)), dict(min_points=(1,)), dict(orientation_threshold_deg=-1), dict(orientation_threshold_deg=181), dict(seed=-1), dict(allocation='random'), dict(sampling='random')] for case in cases: with self.subTest(case=case), self.assertRaises(ValueError): SamplingConfig(**case) with self.assertRaises(ValueError): allocate_budget(5, [4, 4], [3, 3]) with self.assertRaises(ValueError): allocate_budget(5, [-1, 4])
def test_sparse_candidates_surface_fills_without_duplicates(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) a = sample_points(self.evidence(f), SamplingConfig(structural_ratio=1., orientation_threshold_deg=40)) self.assertEqual(len(a.points), min(256, int(f.masks[PEG].sum()))) self.assertEqual(a.counts[PEG]['priority'], a.counts[PEG]['candidates']) self.assertGreater(a.counts[PEG]['surface_fps'], 0)
def test_real_crease_priority_hits_visible_edge_and_spreads(self): f, _, _ = synthetic_case('crease', K, shape=(64, 64)) e = self.evidence(f); a = sample_points(e, SamplingConfig(num_points=64, structural_ratio=.5)) self.assertGreater(a.priority_selected.sum(), 0) vu = a.pixels_vu[a.priority_selected] # Compare to the actual two-face transition in observed synthetic geometry. self.assertLessEqual(np.max(np.abs(vu[:, 1]-31.5)), 4) candidates = extract_candidates(e, SamplingConfig())[PEG] cp = candidates.points[candidates.metadata['orientation_candidate']] chosen = a.points[a.priority_selected] self.assertGreater(np.ptp(chosen[:, 1]), .8*np.ptp(cp[:, 1]))
def test_mask_cut_and_invalid_hole_not_structural_but_depth_step_separate(self): f = self.frame(); mask = f.masks[PEG].copy(); mask[10:17, 20:28] = False e = self.evidence(replace(f, masks={PEG:mask})); a = sample_points(e, method='S4') self.assertTrue(a.metadata['mask_evidence'].any()); self.assertFalse(a.priority_selected.any()) d = f.depth.copy(); d[10:17, 20:28] = 0 e = self.evidence(replace(f, depth=d)); c = extract_candidates(e, SamplingConfig(), 'S4') self.assertTrue(c[PEG].metadata['invalid_evidence'].any()) self.assertFalse(c[PEG].metadata['depth_evidence'].any()); self.assertFalse(sample_points(e, method='S4').priority_selected.any()) d = f.depth.copy(); d[:, 32:] = .5 e = self.evidence(replace(f, depth=d)); c = extract_candidates(e, SamplingConfig(), 'S4') self.assertTrue(c[PEG].metadata['depth_evidence'].any()) self.assertTrue(c[PEG].metadata['occluding_evidence'].any()); self.assertTrue(c[PEG].metadata['occluded_evidence'].any()) self.assertFalse(sample_points(e, method='S3').priority_selected.any()) a = sample_points(e, method='S4'); self.assertGreater(a.depth_priority_selected.sum(), 0) self.assertLessEqual(a.depth_priority_selected.sum(), int(256*.25*.25))
def test_all_false_candidates_still_respect_contract_and_roles(self): f, _, _ = synthetic_case('tilted', K, shape=(64, 64), phase_m=.00025) e = self.evidence(replace(f, depth=quantize(f.depth)), 'baseline') cfg = SamplingConfig(num_points=64, structural_ratio=.125, orientation_threshold_deg=0) a = sample_points(e, cfg, method='S1') self.assertLessEqual(a.priority_selected.sum(), 8) self.assertEqual(len(a.flat_index), len(np.unique(a.flat_index))) self.assertGreater(a.metadata['structural_candidate'].sum(), a.priority_selected.sum()) self.assertTrue(a.metadata['structural_candidate'][a.priority_selected].all())
def test_overlap_invalid_depth_and_input_immutability(self): f = self.frame(); d = f.depth.copy(); d[5, 5:10] = [0, -1, np.nan, np.inf, -np.inf] box = f.masks[BOX].copy(); box[4:9, 4:9] = True f = replace(f, depth=d, masks={PEG:f.masks[PEG], BOX:box}) before = d.copy(); masks = {i:m.copy() for i,m in f.masks.items()} a = sample_points(self.evidence(f)) self.assertTrue(np.isfinite(a.points).all()); v,u = a.pixels_vu.T self.assertFalse((f.masks[PEG]&f.masks[BOX])[v,u].any()) np.testing.assert_array_equal(d, before) for i in masks: np.testing.assert_array_equal(masks[i], f.masks[i])
def test_fps_seed_ties_initial_and_coincident_rows(self): points = np.zeros((20, 3)); points[:, 0] = np.arange(20) a = fps_indices(points, 10, seed=12) np.testing.assert_array_equal(a, fps_indices(points, 10, seed=12)) b = fps_indices(points, 20, initial=a) np.testing.assert_array_equal(b[:10], a); self.assertEqual(len(np.unique(b)), 20) self.assertEqual(len(np.unique(fps_indices(np.zeros((20, 3)), 20))), 20) for bad in ([1, 1], [-1], [20]): with self.assertRaises(ValueError): fps_indices(points, 5, initial=bad)
def test_normal_and_candidate_regression_against_task02_all_fields(self): for kind in ('front', 'tilted', 'crease', 'step'): f, _, _ = synthetic_case(kind, K, shape=(64, 64), phase_m=.00025) f = replace(f, depth=quantize(f.depth)); original, pairs = compare(f) for estimator in ('baseline', 'fd2', 'pca5'): actual = self.evidence(f, estimator) for oid in (PEG, BOX): ef = original[estimator].objects[oid]; af = actual.frame.objects[oid] for name in ef.__dataclass_fields__: if name in ('normals', 'normal_variation_rad'): np.testing.assert_allclose(getattr(af,name), getattr(ef,name), atol=2e-5, rtol=0) else: np.testing.assert_array_equal(getattr(af,name),getattr(ef,name)) for t in (10, 20, 30, 40): for name, arr in pairs[estimator][oid].candidates(t).items(): np.testing.assert_array_equal(actual.pairs[oid].candidates(t)[name], arr) f = self.frame(); baseline = process_geometry(f) actual = self.evidence(f, 'baseline') for oid in (PEG,BOX): for name in baseline.objects[oid].__dataclass_fields__: np.testing.assert_array_equal(getattr(baseline.objects[oid],name),getattr(actual.frame.objects[oid],name))
def test_gt_not_accepted_and_rgb_cannot_change_selection(self): f = self.frame(); a = sample_points(self.evidence(f)) altered = replace(f, rgb=255-f.rgb, cam2world=np.full((4,4),np.nan), tcp_pose=np.full(7,np.nan)) b = sample_points(self.evidence(altered)) np.testing.assert_array_equal(a.flat_index,b.flat_index) with self.assertRaises(TypeError): sample_points(self.evidence(), gt={}) with self.assertRaises(ValueError): sample_points(self.evidence(), method='S1')
if __name__ == '__main__': unittest.main()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()12345678910111213141516171819202122232425262728293031323334353637383940414243"""Cuboid edge and clustered-candidate spatial-dispersion tests."""from dataclasses import replaceimport unittestimport numpy as npfrom scipy.spatial import cKDTreefrom scipy.spatial.transform import Rotationfrom visual.runtime.sampling import SamplingConfig, extract_sampling_evidence, sample_points, fps_indicesfrom visual.runtime.test.normal_diagnostics import synthetic_frame, oracle, real_regions
class SamplingGeometryTests(unittest.TestCase): def test_cuboid_visible_seam_is_preserved_by_priority(self): k=np.array([[160.,0,48],[0,160.,48],[0,0,1]]) frame=synthetic_frame(np.ones((96,96),np.float32),k,np.ones((96,96),bool)) q=Rotation.from_euler('xy',[15,40],degrees=True).as_quat() pose=np.r_[0.,0.,.5,q[3],q[:3]];half=np.array([.08,.06,.05]) truth=oracle(frame,pose,[(np.zeros(3),half)]) visible=np.isfinite(truth['depth']) frame=replace(frame,depth=np.where(visible,truth['depth'],0).astype(np.float32),masks={0:visible}) evidence=extract_sampling_evidence(frame) # Pose/size are used only by the synthetic renderer and expected metrics. _,_,maps=real_regions(frame,evidence.frame,visible,truth,0,half) cfg=SamplingConfig(num_points=64,structural_ratio=.5) a=sample_points(evidence,cfg);b=sample_points(evidence,cfg,method='S0') reference=np.column_stack(np.nonzero(maps['seam'])) self.assertGreater(len(reference),0);self.assertGreater(a.priority_selected.sum(),0) priority=a.pixels_vu[a.priority_selected] self.assertGreater(np.mean(cKDTree(reference).query(priority)[0]<=3),.8) def coverage(result):return np.mean(cKDTree(result.pixels_vu).query(reference)[0]<=2) self.assertGreater(coverage(a),coverage(b))
def test_clustered_candidates_fps_covers_small_remote_region(self): rng=np.random.default_rng(7) dense=rng.normal(0,.001,(900,3));remote=rng.normal([.1,0,0],.001,(100,3)) candidates=np.concatenate([dense,remote]) rows=fps_indices(candidates,16,seed=0) self.assertTrue((rows<900).any());self.assertTrue((rows>=900).any()) distances=cKDTree(candidates[rows]).query(candidates)[0] # Test a coverage outcome, not only the implementation's output length. self.assertLess(np.percentile(distances[900:],95),.003)
if __name__=='__main__':unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453"""Task 02-B: fixed full-resolution normal comparison, CPU/offline diagnostics.
WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_normal_comparison"""from __future__ import annotations
import argparsefrom dataclasses import fields, replaceimport htmlimport importlib.metadatafrom itertools import chainimport jsonfrom pathlib import Pathimport platformimport sysfrom time import perf_counter
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.patches import Patchimport numpy as npfrom scipy.ndimage import distance_transform_edt
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import ( GeometryFrame, GeometryParameters, build_organized_geometry, compute_geometric_features, estimate_surface_normals, process_geometry,)from visual.runtime.rgbd import BOX, PEG, iter_saved_rgbdfrom visual.runtime.test.normal_diagnostics import ( THRESHOLDS, angular_error, box_primitives, dilate, metrics, oracle, pose_rotation, quantize, rays, real_regions, rim_region, stats, synthetic_case, synthetic_frame,)from visual.runtime.test.normal_estimators import METHODS, finite_difference, local_planefrom visual.runtime.test.run_normal_diagnostics import save_json, summarize_rows
OBJECTS = {'peg': PEG, 'box': BOX}PARAMETERS = GeometryParameters()
def compare(frame, rotation=0): """Shared observed backprojection; separately timed normal + feature passes.
Rotate execution order to reduce fixed ordering effects. Baseline uses the exact existing functions; the standard process_geometry is checked in tests. Timers exclude GT, loading, plotting, saving, metrics and the other methods. """ start = perf_counter() geometry = build_organized_geometry(frame) geometry_ms = (perf_counter()-start)*1000 results = {} order = METHODS[rotation % len(METHODS):]+METHODS[:rotation % len(METHODS)] for method in order: start = perf_counter() if method == 'baseline': normals = {i: estimate_surface_normals(geometry, i, PARAMETERS) for i in geometry.object_masks} elif method.startswith('fd'): normals = {i: finite_difference(geometry, i, int(method[2:]), PARAMETERS) for i in geometry.object_masks} else: normals = {i: local_plane(geometry, i, int(method[3:]), PARAMETERS) for i in geometry.object_masks} after_normals = perf_counter() features = {i: compute_geometric_features(geometry, i, *normals[i], PARAMETERS) for i in geometry.object_masks} end = perf_counter() timings = dict(geometry=geometry_ms, normals=(after_normals-start)*1000, discontinuity_features=(end-after_normals)*1000, total=geometry_ms+(end-start)*1000) results[method] = GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timings) return results
def response_metrics(feature, region, truth=None): row = metrics(feature, region, truth) point = region & feature.valid_points jump = point & feature.depth_discontinuity row['jump_without_normal'] = int((jump & ~feature.normal_valid).sum()) for t in THRESHOLDS: high = point & feature.normal_variation_valid & (np.rad2deg(feature.normal_variation_rad) > t) row[f'union_{t}'] = int((jump | high).sum()) row[f'variation_only_{t}'] = int((high & ~jump).sum()) row[f'both_{t}'] = int((high & jump).sum()) row[f'jump_only_{t}'] = int((jump & ~high).sum()) return row
class Pool: def __init__(self): self.items = {}
def add(self, key, feature, region, truth=None): item = self.items.setdefault(key, dict(rows=[], variation=[], errors=[])) row = response_metrics(feature, region, truth) item['rows'].append(row) vv = region & feature.valid_points & feature.normal_variation_valid item['variation'].append(np.rad2deg(feature.normal_variation_rad[vv])) if truth is not None: nv = region & feature.valid_points & feature.normal_valid item['errors'].append(angular_error(feature.normals[nv], truth[nv])) return row
def summary(self): result = {} for key, item in self.items.items(): rows = item['rows'] r = summarize_rows(rows, item['variation'], item['errors'] or None) extras = ['jump_without_normal']+[f'{k}_{t}' for t in THRESHOLDS for k in ('union', 'variation_only', 'both', 'jump_only')] for k in extras: r[k] = sum(v[k] for v in rows) r[k+'_fraction_of_region'] = r[k]/r['region_pixels'] if r['region_pixels'] else None r[k+'_fraction_of_points'] = r[k]/r['points'] if r['points'] else None result[key] = r return result
def localization(feature, reference, visible, threshold): """Raster seam endpoint matching, fixed 6px search corridor, no GT input.
Report both directions: nearest-response distance alone can reward planar noise. Precision is deliberately not claimed in this restricted corridor. Missing predictions give zero coverage and no finite distance statistic. """ n = int(reference.sum()) if not n: return dict(reference=0, predictions=0, hit_1=0, hit_2=0, hit_3=0), np.array([]), np.array([]) to_ref = distance_transform_edt(~reference) prediction = (to_ref <= 6) & visible & feature.valid_points & feature.normal_variation_valid prediction &= np.rad2deg(feature.normal_variation_rad) > threshold p = int(prediction.sum()) a = to_ref[prediction] b = distance_transform_edt(~prediction)[reference] if p else np.array([]) row = dict(reference=n, predictions=p, **{f'hit_{t}': int((b <= t).sum()) for t in (1, 2, 3)}) return row, a, b
def localization_summary(items): result = {} for key, values in items.items(): total = {k: sum(v[0][k] for v in values) for k in values[0][0]} total['response_to_seam_px'] = stats(np.concatenate([v[1] for v in values])) total['seam_to_response_px_when_any_prediction'] = stats(np.concatenate([v[2] for v in values])) for t in (1, 2, 3): total[f'coverage_{t}px'] = total[f'hit_{t}']/total['reference'] if total['reference'] else None result[key] = total return result
def real_truth(frame, baseline, gt, camera): s, half = frame.source_frame, gt['peg_half_sizes'] centre = ((gt['box_hole_pose'][s, :3]-gt['box_pose'][s, :3]) @ pose_rotation(gt['box_pose'][s]))[1:] truths = dict(peg=oracle(frame, gt['peg_pose'][s], [(np.zeros(3), half)]), box=oracle(frame, gt['box_pose'][s], box_primitives(float(half[0]), float(gt['box_hole_radii']), centre))) regions, maps = {}, {} for name, object_id in OBJECTS.items(): seg = gt[f'{camera}/seg'][s] == int(gt[f'{name}_id']) regions[name], _, maps[name] = real_regions(frame, baseline, seg, truths[name], object_id, half=half if name == 'peg' else None) if name == 'box': regions[name]['hole_rim'], maps[name]['rim_projection'] = rim_region( frame, truths[name], regions[name]['gt_visible'], gt['box_pose'][s], float(half[0]), float(gt['box_hole_radii']), centre) return truths, regions, maps
def profile(frame, results, seam): """A horizontal cross-section selected from GT seam alone, never responses.""" # Prefer seams with horizontal face transitions to make a horizontal profile. v, u = np.nonzero(seam) if not len(v): return None h, w = seam.shape idx = np.argmin((v-np.median(v))**2+(u-np.median(u))**2) v, u = int(v[idx]), int(u[idx]) x = np.arange(max(0, u-12), min(w, u+13)) row = dict(v=v, reference_u=u, u=x.tolist(), methods={}) for method, result in results.items(): f = result.objects[PEG] a = np.rad2deg(f.normal_variation_rad[v, x]) values = [float(t) if np.isfinite(t) else None for t in a] peak = int(x[np.nanargmax(a)]) if np.isfinite(a).any() else None row['methods'][method] = dict(variation_deg=values, peak_u=peak, peak_offset_px=abs(peak-u) if peak is not None else None, widths_above_deg={str(t): int(np.count_nonzero(a > t)) for t in THRESHOLDS}) return row
def bounds(mask, fallback, margin=8): y, x = np.nonzero(mask if mask.any() else fallback) if not len(x): return (0, mask.shape[1]-1, mask.shape[0]-1, 0) return (max(0, x.min()-margin), min(mask.shape[1]-1, x.max()+margin), min(mask.shape[0]-1, y.max()+margin), max(0, y.min()-margin))
def comparison_plot(output, frame, results, regions, maps): base = results['baseline'] union = base.objects[PEG].valid_points | base.objects[BOX].valid_points views = [('Full view', None, (0, 511, 511, 0)), ('Peg planes / actual seam', PEG, bounds(regions['peg']['gt_visible'], union)), ('Box physical hole rim', BOX, bounds(regions['box']['hole_rim'], regions['box']['gt_visible'], 12))] colors = [('peg', 'plane_interior', '#00ffcc'), ('peg', 'face_seam_2px', '#ff8000'), ('box', 'hole_rim', '#ffff00'), ('peg', 'occlusion_2px', '#ff55cc'), ('peg', 'same_plane_tracker_cut_2px', '#4488ff')] for validity in (False, True): fig, axes = plt.subplots(3, 6, figsize=(22, 12), constrained_layout=True) for axs, (title, oid, extent) in zip(axes, views): axs[0].imshow(frame.rgb) for name, key, color in colors: if regions[name][key].any(): axs[0].contour(regions[name][key], [.5], colors=[color], linewidths=.6) axs[0].set_title(title+'\nGT evaluation regions') for ax, method in zip(axs[1:], METHODS): image = np.full(frame.depth.shape, np.nan) for object_id in OBJECTS.values() if oid is None else (oid,): f = results[method].objects[object_id] if validity: image[f.valid_points] = f.normal_valid[f.valid_points].astype(float) else: image[f.normal_variation_valid] = np.rad2deg(f.normal_variation_rad[f.normal_variation_valid]) cmap = plt.get_cmap('viridis' if validity else 'turbo').with_extremes(bad='#cccccc') im = ax.imshow(image, cmap=cmap, vmin=0, vmax=1 if validity else 45) ax.set_facecolor('#cccccc') ax.set_title(method+(' normal validity' if validity else ' variation (deg)')) for name, key, color in colors[:3]: if (oid is None or oid == OBJECTS[name]) and regions[name][key].any(): ax.contour(regions[name][key], [.5], colors=[color], linewidths=.5) for ax in axs: ax.set(xlim=extent[:2], ylim=extent[2:]); ax.axis('off') fig.colorbar(im, ax=axes[:, 1:], shrink=.6, label='Normal valid (0/1)' if validity else 'Degrees, clipped at 45') fig.suptitle(f'Source {frame.source_frame}: identical source pixels / masks; fixed scales\n' 'Cyan=plane ROI, orange=face seam, yellow=visible physical rim, pink=occlusion, blue=tracker cut. ' + ('Dark=invalid, gray=unobserved.' if validity else 'Gray=unavailable variation; see separate validity panels.')) fig.savefig(output/f'f{frame.source_frame:04d}_{"validity" if validity else "comparison"}.png', dpi=120) plt.close(fig) p = profile(frame, results, maps['peg']['seam']) if p: fig, ax = plt.subplots(figsize=(10, 4), constrained_layout=True) for method, row in p['methods'].items(): ax.plot(np.array(p['u'])-p['reference_u'], row['variation_deg'], '.-', label=method) ax.axvline(0, color='k', ls=':'); ax.legend(ncol=5, fontsize=8) ax.set(xlabel='u offset from selected GT seam pixel', ylabel='Variation (deg)', title=f'Source {frame.source_frame}, v={p["v"]}: same horizontal cross-section') fig.savefig(output/f'f{frame.source_frame:04d}_profile.png', dpi=140); plt.close(fig) return p
def synthetic_experiment(output, intrinsic): rows, primary = [], {} for kind in ('front', 'tilted', 'crease', 'step'): for z in (.2, .25, .35, .6, 1.): for phase in (0., .00025, .0005, .00075): frame, truth, regions = synthetic_case(kind, intrinsic, z0=z, phase_m=phase) for mode in ('float', 'floor', 'nearest'): obs = frame if mode == 'float' else replace(frame, depth=quantize(frame.depth, mode)) results = compare(obs, len(rows)) row = dict(geometry=kind, z0_m=z, phase_m=phase, quantization=mode, methods={}) for method in METHODS: f = results[method].objects[PEG] row['methods'][method] = {k: response_metrics(f, m, truth) for k, m in regions.items()} if kind in ('crease', 'step'): ref = np.zeros(frame.depth.shape, bool); ref[131:381, 255:257] = True row['methods'][method]['localization'] = {} for t in THRESHOLDS: a, b, c = localization(f, ref, frame.masks[PEG], t) row['methods'][method]['localization'][str(t)] = dict( **a, response_to_seam_px=stats(b), seam_to_response_px=stats(c)) rows.append(row) if z == .25 and phase == .00025 and mode in ('float', 'floor'): # Keep only cropped maps for the figure, not dense results. primary[f'{kind}/{mode}'] = {m: np.rad2deg(results[m].objects[PEG].normal_variation_rad[126:386, 226:286]).copy() for m in METHODS} print(f'Synthetic geometry complete: {kind}', flush=True) # Supplementary surface-direction sweep; keep original Task 02-A ROIs above. directions = [] for z in (.25, .6): for slope in (.2, .8): for azimuth in (0, 45, 90, 135): frame, _, regions = synthetic_case('tilted', intrinsic, z0=z, phase_m=.00025) a, b = slope*np.cos(np.deg2rad(azimuth)), slope*np.sin(np.deg2rad(azimuth)) ray = rays(frame.depth.shape, intrinsic) depth = (z+.00025)/(1-a*ray[..., 0]-b*ray[..., 1]) frame = replace(frame, depth=depth.astype(np.float32)) truth = np.broadcast_to(np.array([a, b, -1.])/np.sqrt(a*a+b*b+1), (*depth.shape, 3)) for mode in ('float', 'floor', 'nearest'): obs = frame if mode == 'float' else replace(frame, depth=quantize(frame.depth, mode)) results = compare(obs) directions.append(dict(z0_m=z, slope=slope, azimuth_deg=azimuth, quantization=mode, methods={m: response_metrics(results[m].objects[PEG], regions['plane'], truth) for m in METHODS})) controls = {} frame, truth, _ = synthetic_case('front', intrinsic, z0=.25025) mask = frame.masks[PEG].copy(); mask[:, 256:] = False depth = frame.depth.copy(); depth[240:272, 240:272] = 0 for label, obs in [('mask_cut', replace(frame, masks={PEG: mask})), ('invalid_depth_hole', replace(frame, depth=depth))]: results = compare(obs) controls[label] = {m: response_metrics(results[m].objects[PEG], obs.masks[PEG], truth) for m in METHODS} fig, axes = plt.subplots(len(primary), 5, figsize=(17, 20), constrained_layout=True) for axs, (label, images) in zip(axes, primary.items()): for ax, method in zip(axs, METHODS): ax.imshow(images[method], cmap='turbo', vmin=0, vmax=45) ax.set_title(label+' '+method, fontsize=9); ax.axis('off') fig.suptitle('Same crop: flat false responses and preservation of crease / depth step. Gray/white=missing variation.') fig.savefig(output/'synthetic.png', dpi=120); plt.close(fig) return dict(cases=rows, direction_sweep=directions, controls=controls, original_task02a_conditions=240, supplementary_direction_conditions=len(directions))
def summary_plot(output, summary, local, synthetic): fig, axes = plt.subplots(2, 3, figsize=(16, 9), constrained_layout=True) for method in METHODS: for ax, region in zip(axes[0, :2], ('peg/plane_interior', 'box/hole_rim')): r = summary[f'{method}/{region}'] ax.plot(THRESHOLDS, [r[f'high_{t}_fraction_of_points'] for t in THRESHOLDS], 'o-', label=method) ax.set(title=region, xlabel='Variation threshold (deg)', ylabel='Response / observed points') r = summary[f'{method}/peg/plane_interior'] axes[0, 2].plot(np.arange(2.5, 180, 5), np.array(r['variation_hist_5deg'])/r['variation_valid'], label=method) axes[0, 2].set(title='Plane variation distribution', xlim=(0, 60), xlabel='Degrees', ylabel='Fraction / 5deg bin') for ax, key in zip(axes[1, :2], ('coverage_2px', 'response_to_seam_px')): ys = [local[f'{method}/{t}'][key] for t in THRESHOLDS] if key == 'response_to_seam_px': ys = [v['p95'] for v in ys] ax.plot(THRESHOLDS, ys, 'o-', label=method) ax.set(title='Peg seam '+key, xlabel='Threshold (deg)') cases = [r for r in synthetic['cases'] if r['geometry']=='crease' and r['z0_m']==.25 and r['phase_m']==.00025 and r['quantization']=='float'] r = cases[0]['methods'][method]['edge_band'] axes[1, 2].plot(THRESHOLDS, [r[f'high_{t}_fraction_of_points'] for t in THRESHOLDS], 'o-', label=method) axes[1, 2].set(title='Unquantized synthetic crease (same 6px band)', xlabel='Threshold (deg)', ylabel='Response / observed points') for ax in axes.ravel(): ax.legend(fontsize=8); ax.grid(alpha=.2) fig.savefig(output/'tradeoffs.png', dpi=140); plt.close(fig)
def evaluate(episode_path, masks_path, *, output_root, camera='base_camera', selected=(0, 15, 45, 80, 120), synthetic=True): episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() tracking_path = masks_path.with_name('tracking.json') if tracking_path.exists(): tracking = json.loads(tracking_path.read_text()) if tracking.get('camera') not in (None, camera): raise ValueError('camera differs from tracker') original = Path(tracking.get('input') or episode_path) if original.is_file() and original.resolve() != episode_path and digests(original)[1] != digests(episode_path)[1]: raise ValueError('episode differs from tracker') with np.load(episode_path, allow_pickle=False) as archive: required = [f'{camera}/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed'] missing = set(required)-set(archive.files) if missing: raise ValueError(f'GT missing: {sorted(missing)}') gt = {k: archive[k] for k in required} with np.load(masks_path, allow_pickle=False) as archive: sources = archive['source_frame'] if sources.ndim != 1 or not len(sources) or len(np.unique(sources)) != len(sources): raise ValueError('source_frame must be unique/nonempty') if set(selected)-set(sources.tolist()): raise ValueError('selected frames absent') iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) first = next(iterator) config = dict(task='02-B', input=str(episode_path), masks=str(masks_path), camera=camera, input_sha256=digests(episode_path)[1], masks_sha256=digests(masks_path)[1], baseline_geometry_sha256=digests(REPO/'visual/runtime/geometry.py')[1], methods=list(METHODS), intrinsic=first.intrinsic.tolist(), parameters=vars(PARAMETERS), selected_sources=list(selected), full_resolution=True, variation_neighbour_spacing_px=1, pca_min_points_including_centre=6, pca_batch_size=4096, pca_rank_relative_tolerance=1e-8, pca_rank_absolute_tolerance_m2=1e-16, gate='original unit-pixel adjacent gate; FD complete axis paths; PCA patch-local centre component', roi_source='Task 02-A unchanged real_regions / rim_region and original synthetic_case', roi_depth_residual_m=.0015, roi_metric_edge_margin_m=.004, roi_raster_erosion_px=3, rim_metric_radius_m=.004, rim_raster_radius_px=2, seam_search_corridor_px=6, high_variation_degrees=list(THRESHOLDS), device='cpu', gpu_executed=False, python=platform.python_version(), numpy=np.__version__, scipy=importlib.metadata.version('scipy'), matplotlib=matplotlib.__version__, platform=platform.platform(), synthetic_executed=synthetic, timing='two objects; one warmup per method; rotated order; shared backprojection charged to every total; no I/O/GT/metrics', feature_inputs='recorded depth/intrinsic/original tracker masks; GT strictly after extraction') config['source_sha256'] = {str(p.relative_to(REPO)): digests(p)[1] for p in ( Path(__file__), Path(__file__).with_name('normal_estimators.py'), Path(__file__).with_name('normal_diagnostics.py'))} with ExperimentLogger(team='visual', config=config, seed=int(gt['seed']), model='task02b_normal_comparison', job_type='evaluate') as logger: output = Path(output_root).resolve()/logger.run_id; output.mkdir(parents=True, exist_ok=False) print(f'Output: {output}', flush=True) synthetic_data = synthetic_experiment(output, first.intrinsic) if synthetic else None compare(first) # Warmup excluded from every reported real latency. pool, records, local = Pool(), [], {} for frame in chain((first,), iterator): results = compare(frame, len(records)) # GT unavailable to estimators. truths, regions, maps = real_truth(frame, results['baseline'], gt, camera) record = dict(source_frame=frame.source_frame, methods={}, paired={}) plane = regions['peg']['plane_interior'] common_n = np.logical_and.reduce([results[m].objects[PEG].normal_valid for m in METHODS]) & plane common_v = np.logical_and.reduce([results[m].objects[PEG].normal_variation_valid for m in METHODS]) & plane for method in METHODS: result = results[method] mr = dict(timings_ms=result.timings_ms, regions={}, seam_localization={}) for name, object_id in OBJECTS.items(): f = result.objects[object_id] for key, region in regions[name].items(): mr['regions'][f'{name}/{key}'] = pool.add(f'{method}/{name}/{key}', f, region, truths[name]['normals'] if key.startswith('plane_') else None) f = result.objects[PEG] for label, region in [('common_normal', common_n), ('common_variation', common_v)]: pool.add(f'{method}/paired/{label}', f, region, truths['peg']['normals']) pair = plane & f.normal_valid & results['baseline'].objects[PEG].normal_valid for which in ('baseline', method) if method != 'baseline' else ('baseline',): pool.add(f'{method}/paired_with_baseline/{which}', results[which].objects[PEG], pair, truths['peg']['normals']) for t in THRESHOLDS: values = localization(f, maps['peg']['seam'], regions['peg']['gt_visible'], t) local.setdefault(f'{method}/{t}', []).append(values) mr['seam_localization'][str(t)] = dict(**values[0], response_to_seam_px=stats(values[1]), seam_to_response_px=stats(values[2])) record['methods'][method] = mr if frame.source_frame in selected: record['profile'] = comparison_plot(output, frame, results, regions, maps) arrays = dict(source_frame=np.array(frame.source_frame), depth_m=frame.depth, intrinsic=frame.intrinsic) for method in METHODS: for name, object_id in OBJECTS.items(): f = results[method].objects[object_id] for field in fields(f): arrays[f'{method}/{name}/{field.name}'] = getattr(f, field.name) for name in OBJECTS: arrays.update({f'evaluation/{name}/{k}': v for k, v in regions[name].items()}) for k in ('face', 'normals'): arrays[f'evaluation/{name}/{k}'] = truths[name][k] arrays['evaluation/peg/seam_endpoints'] = maps['peg']['seam'] np.savez_compressed(output/f'f{frame.source_frame:04d}.npz', **arrays) records.append(record) if len(records) == 1 or len(records) % 20 == 0: print(f'Real frames: {len(records)}/{len(sources)}', flush=True) summary, ls = pool.summary(), localization_summary(local) latency = {m: {k: stats([r['methods'][m]['timings_ms'][k] for r in records]) for k in ('geometry', 'normals', 'discontinuity_features', 'total')} for m in METHODS} data = dict(run_id=logger.run_id, config=config, git_commit=logger.metadata['git_commit'], git_dirty=logger.metadata['git_dirty'], evaluated_frames=len(records), summary=summary, seam_localization=ls, latency_ms=latency, synthetic=synthetic_data, frames=records) save_json(output/'comparison.json', data) if synthetic: summary_plot(output, summary, ls, synthetic_data) images = ['tradeoffs.png', 'synthetic.png']+[f'f{s:04d}_{k}.png' for s in selected for k in ('comparison', 'validity', 'profile')] body = ''.join(f'<p><a href="{p}"><img src="{p}" alt="{p}"></a></p>' for p in images if (output/p).exists()) (output/'comparison.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><title>Task 02-B</title><style>body{{font:15px system-ui;max-width:1800px;margin:24px auto}}img{{width:100%}}pre{{white-space:pre-wrap}}</style><h1>Task 02-B — quantization-robust normals</h1><p>Run {logger.run_id}; {len(records)} ep000 frames. CPU NumPy.<a href="comparison.json">Complete counts, distributions, paired metrics, threshold sweeps and latency</a>.</p><p>Baseline unchanged. FD2/FD4 and PCA5/PCA7 preserve original resolution and use the same 1px variation comparison.GT is evaluation-only. Fixed Task 02-A regions and 5/10/20/30 degree thresholds. Boundary bands may overlap.Seam distance statistics use a fixed 6px corridor, alongside 1/2/3px coverage and planar false responses.Pooled pixel-frame statistics are temporally dependent. No final estimator/threshold adopted.</p>{body}<details><summary>Configuration</summary><pre>{html.escape(json.dumps(config, indent=2))}</pre></details></html>''', encoding='utf-8') for p in sorted(output.iterdir()): logger.link_output(p, kind='metrics' if p.suffix=='.json' else None) logger.log(summary, prefix='eval/task02b'); logger.log(latency, prefix='eval/task02b/latency_ms') logger.record(dataset_sha256=config['input_sha256'], masks_sha256=config['masks_sha256'], evaluation_device='cpu', evaluated_frames=len(records), gpu_executed=False) return output
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, default=REPO/'visual/data/step2/ep000.npz') parser.add_argument('--masks', type=Path, default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') parser.add_argument('--camera', default='base_camera') parser.add_argument('--out', type=Path, default=REPO/'visual/results/normal_comparison') args = parser.parse_args() print(evaluate(args.input, args.masks, output_root=args.out, camera=args.camera))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Join Visual tracker masks with their recorded RGB-D observations.
Only camera observations and TCP kinematics are read. Object GT, simulatorsegmentation IDs, point sampling, and graph construction are outside this adapter."""
from __future__ import annotations
from collections.abc import Iterable, Iterator, Mapping, Sequencefrom dataclasses import dataclassfrom operator import indexfrom pathlib import Path
import numpy as np
# Visual output object IDs consumed by Graph, distinct from graph node types.PEG = 0BOX = 1TRACKER_TO_GRAPH_ID = {1: PEG, 2: BOX}MASK_NAME_TO_TRACKER_ID = {"peg": 1, "box": 2}
@dataclass(frozen=True)class TrackedRGBDFrame: """One source observation with masks keyed by Visual output object ID.
Arrays are CPU NumPy arrays. Depth is recorded CV-camera z in metres; ``cam2world`` maps CV-camera coordinates to world. ``tcp_pose`` is the world pose ``[x, y, z, qw, qx, qy, qz]``. ``source_frame`` is the episode array row, while ``frame_idx`` is the recorded simulator step, if present. Missing tracked objects have empty boolean masks. Arrays may share storage with the input; consumers should not modify them in place. """
source_frame: int camera: str rgb: np.ndarray depth: np.ndarray intrinsic: np.ndarray cam2world: np.ndarray tcp_pose: np.ndarray masks: dict[int, np.ndarray] frame_idx: int | None timestamp: float | None
def _observations(episode: Mapping[str, object], camera: str) -> dict[str, np.ndarray]: keys = { name: f"{camera}/{name}" for name in ("rgb", "depth", "intrinsic", "cam2world") } keys["tcp_pose"] = "tcp_pose" missing = [key for key in keys.values() if key not in episode] if missing: raise ValueError( f"episode is missing required observations: {', '.join(missing)}" ) arrays = {name: np.asarray(episode[key]) for name, key in keys.items()} rgb = arrays["rgb"] if rgb.ndim != 4 or rgb.shape[-1] != 3: raise ValueError(f"{camera}/rgb must have shape (T,H,W,3), got {rgb.shape}") count, height, width = rgb.shape[:3] shapes = { "depth": (count, height, width), "intrinsic": (count, 3, 3), "cam2world": (count, 4, 4), "tcp_pose": (count, 7), } for name, shape in shapes.items(): if arrays[name].shape != shape: raise ValueError( f"{keys[name]} must have shape {shape}, got {arrays[name].shape}" ) if not np.issubdtype(arrays["depth"].dtype, np.floating): raise ValueError( "recorded depth must be floating point metres, not raw millimetres" ) for name in ("frame_idx", "timestamp"): if name in episode: arrays[name] = np.asarray(episode[name]) if arrays[name].shape != (count,): raise ValueError( f"{name} must have shape ({count},), got {arrays[name].shape}" ) return arrays
def _source_frames(values: Sequence[int] | np.ndarray, count: int) -> np.ndarray: frames = np.asarray(values) if frames.ndim != 1 or not np.issubdtype(frames.dtype, np.integer): raise ValueError("source_frame must be a one-dimensional integer array") if np.any(frames < 0) or np.any(frames >= count): raise ValueError(f"source_frame indices must be in [0, {count})") return frames
def attach_rgbd( tracking: Iterable[tuple[int, Mapping[int, object]]], episode: Mapping[str, object], *, camera: str = "base_camera", source_frames: Sequence[int] | np.ndarray | None = None,) -> Iterator[TrackedRGBDFrame]: """Attach recorded observations to the existing ``SAM2Tracker.track`` output.
Tracker indices address its processed video. If that video was subsampled, pass the exact source row for every processed frame in ``source_frames``. Direct full-episode tracking uses the tracker index as the source row. Torch masks are detached and copied to CPU without importing SAM2 or Torch. Unknown tracker IDs and mismatched image sizes raise instead of being guessed or resized. Empty masks and invalid recorded depth values are preserved. """ arrays = _observations(episode, camera) count, height, width = arrays["rgb"].shape[:3] selected = None if source_frames is None else _source_frames(source_frames, count) tracker_count = count if selected is None else len(selected) for local_frame, tracker_masks in tracking: try: local_frame = index(local_frame) except TypeError as exc: raise ValueError("tracker frame index must be an integer") from exc if not 0 <= local_frame < tracker_count: raise ValueError( f"tracker frame index {local_frame} must be in [0, {tracker_count})" ) source = local_frame if selected is None else int(selected[local_frame]) masks = { graph_id: np.zeros((height, width), dtype=bool) for graph_id in TRACKER_TO_GRAPH_ID.values() } for tracker_id, mask in tracker_masks.items(): if tracker_id not in TRACKER_TO_GRAPH_ID: raise ValueError( f"unknown tracker object ID {tracker_id}; expected 1 (peg) or 2 (box)" ) if hasattr(mask, "detach"): mask = mask.detach().cpu().numpy() mask = np.asarray(mask) if mask.dtype != np.bool_ or mask.shape != (height, width): raise ValueError( f"tracker mask {tracker_id} must be boolean with shape " f"{(height, width)}, got {mask.dtype} {mask.shape}" ) masks[TRACKER_TO_GRAPH_ID[tracker_id]] = mask yield TrackedRGBDFrame( source_frame=source, camera=camera, rgb=arrays["rgb"][source], depth=arrays["depth"][source], intrinsic=arrays["intrinsic"][source], cam2world=arrays["cam2world"][source], tcp_pose=arrays["tcp_pose"][source], masks=masks, frame_idx=( int(arrays["frame_idx"][source]) if "frame_idx" in arrays else None ), timestamp=( float(arrays["timestamp"][source]) if "timestamp" in arrays else None ), )
def iter_saved_rgbd( episode_path: str | Path, masks_path: str | Path, *, camera: str = "base_camera",) -> Iterator[TrackedRGBDFrame]: """Join runtime ``masks.npz`` with its original episode using ``source_frame``.
Pass the original episode and camera used by ``run_tracking.py`` (recorded in its ``tracking.json``). Frame rows are never inferred from array lengths or timestamps. No detector, tracker checkpoint, or simulator is required. """ with np.load(episode_path, allow_pickle=False) as episode, np.load( masks_path, allow_pickle=False ) as saved: required = ["source_frame", *MASK_NAME_TO_TRACKER_ID] missing = [name for name in required if name not in saved] if missing: raise ValueError( f"mask archive is missing required arrays: {', '.join(missing)}" ) source_frames = saved["source_frame"] if source_frames.ndim != 1: raise ValueError("source_frame must be a one-dimensional integer array") masks = { tracker_id: saved[name] for name, tracker_id in MASK_NAME_TO_TRACKER_ID.items() } for tracker_id, values in masks.items(): if values.ndim != 3 or len(values) != len(source_frames): raise ValueError( f"saved masks for tracker {tracker_id} must have shape " "(len(source_frame), H, W)" ) tracking = ( (row, {tracker_id: values[row] for tracker_id, values in masks.items()}) for row in range(len(source_frames)) ) yield from attach_rgbd( tracking, episode, camera=camera, source_frames=source_frames )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Observation-only normal estimators promoted unchanged from Task 02-B.
Inputs are Task 01 organized observed XYZ and tracker support only. Unit normalsface the CV camera. The original estimator and variation implementation remainin geometry.py. No GT, RGB, resampling, smoothing or imputation is used here."""from __future__ import annotations
import numpy as np
from visual.runtime.geometry import GeometryParameters, OrganizedGeometry
METHODS = ('baseline', 'fd2', 'fd4', 'pca5', 'pca7')
def _jump(a, b, parameters): return np.abs(a-b) > parameters.depth_jump_abs_m + parameters.depth_jump_rel*np.minimum(a, b)
def _empty(geometry): return np.full_like(geometry.xyz, np.nan), np.zeros(geometry.valid_depth.shape, bool)
def _assign(geometry, vu, vectors, normals, valid): lengths = np.linalg.norm(vectors, axis=1) good = np.isfinite(lengths) & (lengths > 0) vu, vectors = vu[good], vectors[good]/lengths[good, None] if not len(vu): return xyz = geometry.xyz[vu[:, 0], vu[:, 1]] vectors[np.einsum('ij,ij->i', vectors, xyz) > 0] *= -1 normals[vu[:, 0], vu[:, 1]] = vectors.astype(np.float32) valid[vu[:, 0], vu[:, 1]] = True
def finite_difference(geometry: OrganizedGeometry, object_id: int, spacing: int, parameters: GeometryParameters = GeometryParameters()): """Full-resolution central secants with complete, gated axis paths.
Every intermediate pixel from centre to each of four endpoints must be observed for this object; EVERY adjacent pair must pass the original jump gate. Thus even an endpoint beyond a narrow gap cannot bridge it. The gate is on unit pixel steps, not multiplied by spacing or applied to longer secants. No one-sided fallback: incomplete stencils are invalid. """ if not isinstance(spacing, int) or isinstance(spacing, bool) or spacing < 1: raise ValueError('spacing must be a positive integer') normals, valid = _empty(geometry) h, w = valid.shape if min(h, w) <= 2*spacing: return normals, valid support = geometry.observed_mask(object_id) v, u = np.nonzero(support) inside = (v >= spacing) & (v < h-spacing) & (u >= spacing) & (u < w-spacing) v, u = v[inside], u[inside] good = np.ones(len(v), bool) z = np.where(geometry.valid_depth, geometry.xyz[..., 2], 0) for dv, du in ((0, -1), (0, 1), (-1, 0), (1, 0)): for step in range(1, spacing+1): a = (v+dv*(step-1), u+du*(step-1)) b = (v+dv*step, u+du*step) good &= support[b] & ~_jump(z[a], z[b], parameters) v, u = v[good], u[good] dx = geometry.xyz[v, u+spacing].astype(float)-geometry.xyz[v, u-spacing] dy = geometry.xyz[v+spacing, u].astype(float)-geometry.xyz[v-spacing, u] _assign(geometry, np.column_stack((v, u)), np.cross(dx, dy), normals, valid) return normals, valid
def local_plane(geometry: OrganizedGeometry, object_id: int, window: int, parameters: GeometryParameters = GeometryParameters(), *, min_points: int = 6, batch_size: int = 4096): """PCA of the centre-connected component inside an odd square patch.
Four-connected links require same-object finite positive depth and the original adjacent z-jump gate. Flood fill is confined to this patch, so disconnected islands/holes cannot be bridged via remote connections. All accepted points have equal weight, with no fitted residual trimming. True continuous creases below the gate CAN mix and blur: measured by this task. At least six points (including centre), rank >=2 and a unique smallest covariance eigenvector are required. Partial square patches are permitted. """ if not isinstance(window, int) or isinstance(window, bool) or window < 3 or window % 2 != 1: raise ValueError('window must be an odd integer >=3') if not isinstance(min_points, int) or min_points < 3 or batch_size < 1: raise ValueError('min_points must be >=3 and batch_size positive') normals, valid = _empty(geometry) support = geometry.observed_mask(object_id) centres = np.column_stack(np.nonzero(support)) h, w = support.shape radius = window//2 dv, du = np.meshgrid(np.arange(-radius, radius+1), np.arange(-radius, radius+1), indexing='ij') for start in range(0, len(centres), batch_size): vu = centres[start:start+batch_size] v, u = vu[:, 0, None, None]+dv, vu[:, 1, None, None]+du inside = (v >= 0) & (v < h) & (u >= 0) & (u < w) v, u = np.clip(v, 0, h-1), np.clip(u, 0, w-1) available = inside & support[v, u] xyz = geometry.xyz[v, u].astype(float) z = np.where(available, xyz[..., 2], 0) horizontal = available[:, :, :-1] & available[:, :, 1:] & ~_jump(z[:, :, :-1], z[:, :, 1:], parameters) vertical = available[:, :-1, :] & available[:, 1:, :] & ~_jump(z[:, :-1, :], z[:, 1:, :], parameters) reached = np.zeros(available.shape, bool) reached[:, radius, radius] = True for _ in range(window*window-1): nxt = reached.copy() nxt[:, :, 1:] |= reached[:, :, :-1] & horizontal nxt[:, :, :-1] |= reached[:, :, 1:] & horizontal nxt[:, 1:, :] |= reached[:, :-1, :] & vertical nxt[:, :-1, :] |= reached[:, 1:, :] & vertical if np.array_equal(nxt, reached): break reached = nxt count = reached.sum((1, 2)) enough = count >= min_points if not enough.any(): continue vu, count, reached, xyz = vu[enough], count[enough], reached[enough], xyz[enough] # Centre-relative coordinates and float64 covariance avoid cancellation # from metre-scale absolute positions and millimetre-scale support. delta = np.where(reached[..., None], xyz-geometry.xyz[vu[:, 0], vu[:, 1]][:, None, None, :], 0) mean = delta.sum((1, 2))/count[:, None] covariance = np.einsum('nijk,nijl->nkl', delta, delta)/count[:, None, None] covariance -= mean[:, :, None]*mean[:, None, :] eigenvalues, eigenvectors = np.linalg.eigh(covariance) rank2 = eigenvalues[:, 1] > np.maximum(1e-16, eigenvalues[:, 2]*1e-8) unique = eigenvalues[:, 1]-eigenvalues[:, 0] > np.maximum(1e-16, eigenvalues[:, 2]*1e-8) good = rank2 & unique & np.isfinite(eigenvalues).all(1) _assign(geometry, vu[good], eigenvectors[good, :, 0], normals, valid) return normals, valid123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303"""Task 02-A evaluation helpers. No runtime estimator or predicted classes.
Analytic geometry is evaluation truth only. Actual features always come from theunchanged Task 01 extractor and recorded depth/tracker masks. Raster subsamplingis a diagnostic scale intervention without averaging or a replacement estimator."""from __future__ import annotations
from dataclasses import replaceimport numpy as npfrom scipy.ndimage import binary_dilation, binary_erosionfrom scipy.spatial.transform import Rotation
from visual.runtime.geometry import process_geometryfrom visual.runtime.rgbd import PEG, TrackedRGBDFrame
CROSS = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], bool)THRESHOLDS = (5, 10, 20, 30)
def erode(mask, radius): return binary_erosion(mask, CROSS, iterations=radius, border_value=0) if radius else mask.copy()
def dilate(mask, radius): return binary_dilation(mask, CROSS, iterations=radius) if radius else mask.copy()
def pairs(): yield (slice(None), slice(None, -1)), (slice(None), slice(1, None)) yield (slice(None, -1), slice(None)), (slice(1, None), slice(None))
def endpoints(mask, other): """Pixels in mask with an in-image four-neighbour in other.""" result = np.zeros_like(mask) for a, b in pairs(): result[a] |= mask[a] & other[b] result[b] |= mask[b] & other[a] return result
def stats(values): a = np.asarray(values, float) a = a[np.isfinite(a)] if not a.size: return dict(count=0, mean=None, p50=None, p95=None, p99=None, max=None) return dict(count=int(a.size), mean=float(a.mean()), p50=float(np.median(a)), p95=float(np.percentile(a, 95)), p99=float(np.percentile(a, 99)), max=float(a.max()))
def angular_error(normals, truth): """Oriented angle in degrees, stable for identical rounded unit normals.""" return np.rad2deg(np.arctan2(np.linalg.norm(np.cross(normals, truth), axis=-1), np.sum(normals * truth, axis=-1)))
def metrics(feature, region, truth=None): points = region & feature.valid_points nv = points & feature.normal_valid vv = points & feature.normal_variation_valid variation = np.rad2deg(feature.normal_variation_rad[vv]) n, nn, vn = int(points.sum()), int(nv.sum()), int(vv.sum()) row = dict(region_pixels=int(region.sum()), points=n, normals=nn, variation_valid=vn, observed_fraction_of_region=n/int(region.sum()) if region.any() else None, normal_fraction_of_region=nn/int(region.sum()) if region.any() else None, normal_valid_fraction=nn/n if n else None, variation_valid_fraction=vn/n if n else None, variation_deg=stats(variation), variation_hist_5deg=np.histogram(variation, bins=np.arange(0, 185, 5))[0].tolist(), depth_discontinuity=int((points & feature.depth_discontinuity).sum()), mask_boundary=int((points & feature.mask_boundary).sum()), invalid_depth_boundary=int((points & feature.depth_validity_boundary).sum()), incomplete_normal_neighbours=int((nv & (feature.normal_neighbor_count < 4)).sum())) response = points & (feature.depth_discontinuity | (feature.normal_variation_valid & (np.rad2deg(feature.normal_variation_rad) > 20))) row['jump_or_high20_count'] = int(response.sum()) row['jump_or_high20_fraction_of_region'] = int(response.sum())/int(region.sum()) if region.any() else None for t in THRESHOLDS: count = int(np.count_nonzero(variation > t)) row[f'high_{t}_count'] = count row[f'high_{t}_fraction_of_valid'] = count/vn if vn else None row[f'high_{t}_fraction_of_points'] = count/n if n else None if truth is not None: row['angular_error_deg'] = stats(angular_error(feature.normals[nv], truth[nv])) return row
def rays(shape, intrinsic): v, u = np.indices(shape, dtype=float) return np.stack(((u+.5-intrinsic[0, 2])/intrinsic[0, 0], (v+.5-intrinsic[1, 2])/intrinsic[1, 1], np.ones(shape)), axis=-1)
def synthetic_frame(depth, intrinsic, mask): return TrackedRGBDFrame(0, 'synthetic', np.zeros((*depth.shape, 3), np.uint8), np.asarray(depth, np.float32), np.asarray(intrinsic), np.eye(4), np.array([0, 0, 0, 1, 0, 0, 0.]), {PEG: mask.copy()}, 0, 0.)
def quantize(depth, mode='floor'): # Use float64 arithmetic on the same unquantized float32 input in A and B. scaled = np.asarray(depth, np.float64) * 1000 return ((np.floor(scaled) if mode == 'floor' else np.rint(scaled)) / 1000).astype(np.float32)
def synthetic_case(kind, intrinsic, shape=(512, 512), z0=.25, phase_m=0.): ray = rays(shape, intrinsic) x, y = ray[..., 0], ray[..., 1] a = np.zeros(shape) b = np.zeros(shape) if kind == 'tilted': a.fill(.4); b.fill(-.25) elif kind == 'crease': a[:] = np.where(x < 0, -.6, .6); b.fill(.15) elif kind not in ('front', 'step'): raise ValueError('unknown synthetic geometry') depth = (z0 + phase_m) / (1 - a*x - b*y) if kind == 'step': depth = depth + np.where(x >= 0, .05, 0.) truth = np.stack((a, b, -np.ones(shape)), axis=-1) truth /= np.linalg.norm(truth, axis=-1, keepdims=True) h, w = shape mask = np.zeros(shape, bool) mask[h//4:3*h//4, w//4:3*w//4] = True inner = erode(mask, 3) # Variation's complete dependency has Manhattan radius 2. edge = inner & (np.abs(np.indices(shape)[1] + .5 - intrinsic[0, 2]) <= 3) planar = inner & ~edge if kind in ('crease', 'step') else inner return synthetic_frame(depth, intrinsic, mask), truth, {'plane': planar, 'edge_band': edge}
def subframe(frame, stride): """Exact lattice [::s,::s], preserving pixel-centre CV projection, no filter.""" k = frame.intrinsic.astype(float).copy() k[0, 0] /= stride; k[1, 1] /= stride k[0, 2] = (k[0, 2]-.5)/stride+.5 k[1, 2] = (k[1, 2]-.5)/stride+.5 return replace(frame, depth=frame.depth[::stride, ::stride], rgb=frame.rgb[::stride, ::stride], masks={i: m[::stride, ::stride] for i, m in frame.masks.items()}, intrinsic=k)
def scale_probe(frame, baseline, object_id, plane_base, truth): """Compare each stride with stride 1 on IDENTICAL centres and safe flat support.
Larger strides change both stencil span and normal-comparison separation. Only analytic planar ROIs are used, so the ideal variation remains zero. """ common = erode(plane_base, 8) # Covers radius 2*s for the largest stride, s=4. rows = [] for stride in (1, 2, 4): sub = subframe(frame, stride) feature = baseline if stride == 1 else process_geometry(sub).objects[object_id] roi = common[::stride, ::stride] t = truth[::stride, ::stride] base_region = np.zeros_like(common) base_region[::stride, ::stride] = roi rows.append(dict(stride_px=stride, normal_span_px=2*stride, sample_origin_uv=[0, 0], baseline_same_centres=metrics(baseline, base_region, truth), larger_spacing=metrics(feature, roi, t))) return rows
def pose_rotation(pose): return Rotation.from_quat(np.asarray(pose)[[4, 5, 6, 3]]).as_matrix()
def ray_box(origin, direction, centre, half): """First positive ray/AABB hit, with CV-z parameter and signed face ID.""" delta_lo, delta_hi = centre-half-origin, centre+half-origin moving = np.abs(direction) > 1e-14 lo = np.divide(delta_lo, direction, out=np.full_like(direction, -np.inf), where=moving) hi = np.divide(delta_hi, direction, out=np.full_like(direction, np.inf), where=moving) near_axis, far_axis = np.minimum(lo, hi), np.maximum(lo, hi) parallel_outside = (~moving) & ((origin < centre-half) | (origin > centre+half)) near, far = near_axis.max(-1), far_axis.min(-1) hit = (near > 0) & (near <= far) & ~parallel_outside.any(-1) axis = near_axis.argmax(-1) chosen_dir = np.take_along_axis(direction, axis[..., None], -1)[..., 0] face = axis*2 + (chosen_dir < 0).astype(int) # 0=-x, 1=+x, etc. return np.where(hit, near, np.nan), np.where(hit, face, -1)
def oracle(frame, pose, boxes): """Analytic cuboid-union truth, never passed to actual feature extraction.""" rotation = pose_rotation(pose) cv_to_local = frame.cam2world[:3, :3].T @ rotation origin = (frame.cam2world[:3, 3]-pose[:3]) @ rotation direction = rays(frame.depth.shape, frame.intrinsic) @ cv_to_local depth = np.full(frame.depth.shape, np.nan) face = np.full(frame.depth.shape, -1, np.int8) for centre, half in boxes: z, f = ray_box(origin, direction, np.asarray(centre), np.asarray(half)) use = np.isfinite(z) & (~np.isfinite(depth) | (z < depth)) depth[use], face[use] = z[use], f[use] local = origin + np.nan_to_num(depth)[..., None]*direction axes = np.eye(3)[np.maximum(face, 0)//2] local_n = axes * np.where(face % 2, 1., -1.)[..., None] normals = local_n @ cv_to_local.T normals[face < 0] = np.nan return dict(depth=depth, face=face, local=local, normals=normals, origin=origin)
def box_primitives(half_length, hole_radius, hole_centre): """Installed ManiSkill _build_box_with_hole: four boxes, local x hole axis.""" t = (half_length-hole_radius)/2 cy, cz = hole_centre offset = t + hole_radius return [(np.array([0, offset+cy/2, 0]), np.array([half_length, t-cy/2, half_length])), (np.array([0, -offset+cy/2, 0]), np.array([half_length, t+cy/2, half_length])), (np.array([0, 0, offset+cz/2]), np.array([half_length, half_length, t-cz/2])), (np.array([0, 0, -offset+cz/2]), np.array([half_length, half_length, t+cz/2]))]
def real_regions(frame, result, gt, obj_oracle, object_id, half=None): feature = result.objects[object_id] valid = result.geometry.valid_depth hit = np.isfinite(obj_oracle['depth']) consistent = hit & valid & (np.abs(frame.depth-obj_oracle['depth']) <= .0015) visible = gt & consistent face = obj_oracle['face'] seam = np.zeros_like(gt) cut = np.zeros_like(gt) for a, b in pairs(): both = visible[a] & visible[b] different = both & (face[a] != face[b]) seam[a] |= different; seam[b] |= different same = both & (face[a] == face[b]) cut[a] |= same & feature.object_mask[a] & ~feature.object_mask[b] cut[b] |= same & feature.object_mask[b] & ~feature.object_mask[a] silhouette = endpoints(hit, ~hit) & visible occluder = hit & ~gt & valid & (frame.depth < obj_oracle['depth']-.0015) occlusion = endpoints(visible, occluder) regions = dict(all=np.ones_like(gt), gt_visible=visible, contamination=~gt, face_seam_2px=dilate(seam, 2) & visible, silhouette_2px=dilate(silhouette, 2) & visible, occlusion_2px=dilate(occlusion, 2) & visible, same_plane_tracker_cut_2px=dilate(cut, 2) & visible, invalid_depth_2px=dilate(feature.depth_validity_boundary, 2)) plane_base = np.zeros_like(gt) if half is not None: # Metric margin from all OTHER cuboid faces; separate signed-face ROIs. margin = half - np.abs(obj_oracle['local']) for f in range(6): axis = f//2 other = [i for i in range(3) if i != axis] candidate = visible & (face == f) & np.all(margin[..., other] > .004, axis=-1) plane_base |= candidate regions[f'plane_face_{f}'] = erode(candidate, 3) regions['plane_interior'] = np.logical_or.reduce([regions[f'plane_face_{f}'] for f in range(6)]) return regions, plane_base, dict(seam=seam, silhouette=silhouette, occlusion=occlusion, cut=cut)
def rim_region(frame, obj_oracle, visible, pose, half_length, radius, centre): """Visible entrance rim: analytic 3D distance <=4mm and raster band <=2px.
Geometry truth identifies a physical line. A GT segmentation contour alone is never treated as a rim. Hidden rim projections fail the 3D-distance test. """ local = obj_oracle['local'] x = np.sign(obj_oracle['origin'][0])*half_length cy, cz = centre distance2 = np.full(frame.depth.shape, np.inf) for axis, other, c, oc in ((1, 2, cy, cz), (2, 1, cz, cy)): for sign in (-1, 1): distance2 = np.minimum(distance2, (local[..., 0]-x)**2 +(local[..., axis]-(c+sign*radius))**2 +np.maximum(np.abs(local[..., other]-oc)-radius, 0)**2) raster = np.zeros(frame.depth.shape, bool) rotation = pose_rotation(pose) world_to_cv = np.linalg.inv(frame.cam2world) for axis, other, c, oc in ((1, 2, cy, cz), (2, 1, cz, cy)): for sign in (-1, 1): points = np.zeros((2001, 3)); points[:, 0] = x points[:, axis] = c+sign*radius points[:, other] = np.linspace(oc-radius, oc+radius, len(points)) cv = (points @ rotation.T + pose[:3]) @ world_to_cv[:3, :3].T + world_to_cv[:3, 3] uv = cv[:, :2]/cv[:, 2:3] * np.array([frame.intrinsic[0, 0], frame.intrinsic[1, 1]]) uv += frame.intrinsic[:2, 2] - .5 uv = np.rint(uv[cv[:, 2] > 0]).astype(int) ok = (uv[:, 0] >= 0) & (uv[:, 0] < raster.shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < raster.shape[0]) uv = uv[ok]; raster[uv[:, 1], uv[:, 0]] = True projected_band = dilate(raster, 2) return visible & (distance2 <= .004**2) & projected_band, projected_band
def normal_blockers(result, object_id): """Nonexclusive reasons for unavailable normals on observed points.""" g, f = result.geometry, result.objects[object_id] support = f.valid_points masks = dict(mask=np.zeros_like(support), invalid_depth=np.zeros_like(support), overlap=np.zeros_like(support)) for a, b in pairs(): for p, q in ((a, b), (b, a)): masks['mask'][p] |= support[p] & ~f.object_mask[q] masks['invalid_depth'][p] |= support[p] & ~g.valid_depth[q] masks['overlap'][p] |= support[p] & g.overlap_mask[q] masks['depth_jump'] = support & f.depth_discontinuity masks['image'] = support & f.image_boundary invalid = support & ~f.normal_valid union = np.logical_or.reduce(list(masks.values())) return dict(unavailable=int(invalid.sum()), reasons_nonexclusive={k: int((invalid & v).sum()) for k, v in masks.items()}, unexplained=int((invalid & ~union).sum()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182"""Adaptive total-budget contracts; shared sampler/evaluator remain unchanged."""from dataclasses import replaceimport jsonfrom pathlib import Pathimport tempfileimport unittest
import numpy as np
from visual.runtime.geometry import build_organized_geometryfrom visual.runtime.rgbd import PEG, BOXfrom visual.runtime.sampling import SamplingConfig, extract_candidates, extract_sampling_evidence, sample_pointsfrom visual.runtime.test.normal_diagnostics import synthetic_frame, synthetic_casefrom visual.runtime.test.sampling_evaluation import CoverageMatcherfrom visual.runtime.test.run_adaptive_node_budget import ( AreaBudget, requested_budget, matched_budget, measure_areas, exact_result, exact_saved, validate_selection, save_evidence, load_evidence, distance_summary, nearest, distribution, latency_summary, sampling_timing, preserve_check,)
K = np.array([[100.,0,16.],[0,100.,16.],[0,0,1.]])
class AdaptiveBudgetTests(unittest.TestCase): def frame(self, counts=(200,200)): a,b=counts masks={PEG:np.zeros((32,32),bool),BOX:np.zeros((32,32),bool)} masks[PEG].ravel()[:a]=True masks[BOX].ravel()[512:512+b]=True return replace(synthetic_frame(np.full((32,32),.4,np.float32),K,masks[PEG]),masks=masks)
def test_first_positive_reference_never_resets(self): p=AreaBudget() self.assertEqual(p.step((0,0),0),(0,(0,0))) self.assertIsNone(p.reference) self.assertEqual(p.step((100,100),1)[0],256) self.assertEqual(p.step((50,50),2)[0],128) self.assertEqual(p.step((0,0),3)[0],0) self.assertEqual(p.step((0,200),4)[0],256) self.assertEqual((p.reference,p.reference_source),(200,1))
def test_half_up_minimum_maximum_and_invalid_inputs(self): # 256*81/512 = 40.5 -> 41, rather than ties-to-even 40. self.assertEqual(requested_budget((40,41),512)[0],41) self.assertEqual(requested_budget((16,16),100000)[0],32) self.assertEqual(requested_budget((0,20),100000),(16,(0,16))) self.assertEqual(requested_budget((2,3),100000),(5,(2,3))) self.assertEqual(requested_budget((1000,1000),100)[0],256) for counts in ((-1,0),(True,0),(1.2,0),(1,)): with self.assertRaises(ValueError):requested_budget(counts,10) with self.assertRaises(ValueError):requested_budget((1,0),None) with self.assertRaises(ValueError):requested_budget((0,0),0) with self.assertRaises(ValueError):SamplingConfig(num_points=16)
def test_causal_prefix_and_future_independence(self): prefix=[(0,0),(100,200),(60,50),(0,0)] def run(sequence): p=AreaBudget() return [p.step(c,i) for i,c in enumerate(sequence)] self.assertEqual(run(prefix),run(prefix+[(100000,100000),(1,1)])[:len(prefix)]) self.assertEqual(run(prefix),run(prefix+[(0,0),(0,4)])[:len(prefix)]) values=[requested_budget((i,0),500)[0] for i in range(1000)] self.assertEqual(values,sorted(values))
def test_raw_valid_partition_invalid_and_overlap(self): f=self.frame((200,100));m={k:v.copy() for k,v in f.masks.items()} m[BOX].ravel()[0:5]=True d=f.depth.copy();d.ravel()[5:10]=[0,-1,np.nan,np.inf,-np.inf] f=replace(f,depth=d,masks=m) e=extract_sampling_evidence(f) areas,count_ms,raw_ms=measure_areas(f,e.frame.geometry) self.assertEqual(areas['peg']['raw'],200) self.assertEqual(areas['peg']['valid'],190) self.assertEqual(areas['peg']['invalid_depth'],5) self.assertEqual(areas['peg']['positive_depth_overlap'],5) self.assertEqual(areas['box']['valid'],100) self.assertGreaterEqual(count_ms,0);self.assertGreaterEqual(raw_ms,0) c=extract_candidates(e,SamplingConfig()) self.assertEqual(len(c[PEG].points),areas['peg']['valid'])
def test_sampler_empty_sparse_capacity_and_alignment(self): for counts in ((0,0),(3,4),(0,5),(100,0),(200,200)): f=self.frame(counts);e=extract_sampling_evidence(f) n,mins=requested_budget(counts,100000) cfg=SamplingConfig(num_points=n,min_points=mins) s=sample_points(e,cfg) c=extract_candidates(e,cfg) validate_selection(s,e,cfg,c) self.assertEqual(len(s.points),min(n,sum(counts))) self.assertEqual(s.points.shape,(len(s.points),3)) self.assertEqual(len(np.unique(s.flat_index)),len(s.flat_index)) self.assertLessEqual(s.priority_selected.sum(),n//4) self.assertTrue(all(s.counts[o]['selected']>=min(16,counts[o]) for o in (PEG,BOX))) np.testing.assert_array_equal(f.depth,np.full((32,32),.4,np.float32))
def test_256_reproduction_including_support_shortfall(self): for counts in ((200,200),(0,100),(3,4),(0,0)): e=extract_sampling_evidence(self.frame(counts)) a=sample_points(e,SamplingConfig()) b=sample_points(e,SamplingConfig(num_points=256,min_points=tuple(min(16,c) for c in counts))) exact_result(a,b) archive={f'baseline/{field}':getattr(a,field) for field in ( 'points','pixels_vu','flat_index','object_id','priority_selected','depth_priority_selected')} archive.update({f'baseline/metadata/{k}':v for k,v in a.metadata.items()}) class Archive(dict): @property def files(self):return list(self) exact_saved(b,Archive(archive),'baseline') archive['baseline/points']=a.points+1 if len(a.points): with self.assertRaises(AssertionError):exact_saved(b,Archive(archive),'baseline')
def test_requested_priority_cap_and_roles(self): f,_,_=synthetic_case('crease',K,shape=(32,32)) e=extract_sampling_evidence(f) for n in (16,41,64,256): cfg=SamplingConfig(num_points=n,min_points=(16,0)) s=sample_points(e,cfg) validate_selection(s,e,cfg,extract_candidates(e,cfg)) capacity=sum(int(c.metadata['structural_candidate'].sum()) for c in extract_candidates(e,cfg).values()) self.assertEqual(int(s.priority_selected.sum()),min(n//4,capacity)) self.assertEqual(s.counts[PEG]['selected'],s.counts[PEG]['priority']+s.counts[PEG]['surface_fps'])
def test_gt_annotation_and_reference_cannot_affect_selection(self): f=self.frame();e=extract_sampling_evidence(f) p=AreaBudget();n,mins=p.step((200,200),0) cfg=SamplingConfig(num_points=n,min_points=mins) before=sample_points(e,cfg) g=e.frame.geometry for shift in (0.,100.): reference=(np.array([[0.,0.]]),g.xyz[0,0][None]+shift) CoverageMatcher(g,PEG,reference).score(before.flat_index[before.object_id==PEG]) after=sample_points(e,cfg) exact_result(before,after) self.assertEqual(p.reference,400) with self.assertRaises(TypeError):sample_points(e,cfg,gt={})
def test_lossless_evidence_cache_and_source_preservation(self): e=extract_sampling_evidence(self.frame());a=sample_points(e) with tempfile.TemporaryDirectory() as tmp: path=Path(tmp)/'e.npz';save_evidence(path,e);loaded=load_evidence(path) exact_result(a,sample_points(loaded)) np.testing.assert_array_equal(e.frame.geometry.xyz,loaded.frame.geometry.xyz) from visual.runtime.test.run_adaptive_node_budget import REPO relative='visual/runtime/sampling.py' from utils.experiment_artifacts import digests self.assertTrue(preserve_check({'sha256':{relative:digests(REPO/relative)[1]}})['unchanged']) self.assertFalse(preserve_check({'sha256':{relative:'incorrect'}})['unchanged'])
def test_fixedmatched_capacity_tie_and_count_only(self): m=matched_budget([1000,1000],[100,101]) self.assertEqual(m['budget'],100) self.assertEqual(m['mean_error_nodes'],-.5) self.assertFalse(m['causal_online']) self.assertEqual(matched_budget([5,1000],[5,100])['budget'],100) self.assertEqual(matched_budget([5,5],[5,5])['budget'],32) self.assertEqual(matched_budget([1000],[16])['mean_error_nodes'],16)
def test_missing_distance_ratios_distributions_and_timer_aliases(self): a=distance_summary(nearest(np.ones((3,3)),np.empty((0,3)))) self.assertEqual(a['missing_count'],3);self.assertEqual(a['coverage_3mm'],0) self.assertIsNone(distance_summary(np.empty(0))['coverage_3mm']) self.assertEqual(distribution([1,2,3,None,np.nan])['mean'],2) self.assertEqual(distribution([1,2,3])['min'],1) raw=[] for frame in range(2): for repeat in range(3): for c in ('Fixed256','Adaptive','FixedMatched'): alias='Fixed256' if c=='Adaptive' else None raw.append(dict(source_frame=frame,repeat=repeat,condition=c,executed=alias is None, alias_of=alias,timings_ms=None if alias else {'sampling_total':float(frame+repeat+1)})) s=latency_summary(raw) self.assertEqual(s['Adaptive']['executed_calls'],0) self.assertEqual(s['Adaptive']['alias_calls'],6) self.assertEqual(s['Fixed256']['frame_median_then_distribution']['sampling_total']['mean'],2.5) self.assertEqual(s['Adaptive']['frame_median_then_distribution'],s['Fixed256']['frame_median_then_distribution']) t=sampling_timing(sample_points(extract_sampling_evidence(self.frame()))) self.assertGreaterEqual(t['gather_packaging_and_other_overhead'],0)
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248"""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 result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""Task03 offline observation sampling / GT preservation evaluation (CPU only).
Run from repository root with WANDB_MODE=disabled. No simulator/tracker rerun,no remote publication, final classification, graph output or stale cache."""from __future__ import annotationsimport argparsefrom dataclasses import asdict, replaceimport htmlimport jsonfrom pathlib import Pathimport platformimport shutilimport sys
import numpy as np
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0,str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.rgbd import PEG, BOX, iter_saved_rgbdfrom visual.runtime.geometry import build_organized_geometry, compute_geometric_features, GeometryParametersfrom visual.runtime.normal_estimators import local_planefrom visual.runtime.sampling import (METHODS, SamplingConfig, extract_sampling_evidence, sample_points)from visual.runtime.test.normal_diagnostics import stats, angular_errorfrom visual.runtime.test.run_normal_diagnostics import save_jsonfrom visual.runtime.test.sampling_evaluation import evaluation_context, score_selection, summarize, TOLERANCESfrom visual.runtime.test.sampling_plots import overlays, clouds, quantitative
def conditions(seeds=(0,1,2)): """Staged sweeps rather than a full factorial. Every condition uses all frames.""" out={} for method in METHODS: rows=[(n,.25,20,0) for n in (64,128,256,512)] if method!='S0': rows += [(256,r,20,0) for r in (0.,.125,.5)] rows += [(256,.25,t,0) for t in (10,30,40)] rows += [(256,.25,20,s) for s in seeds if s!=0] for n,r,t,s in rows: r=0. if method=='S0' else r key=f'{method}_n{n}_r{r:g}_t{t}_s{s}' out[key]=dict(method=method,num_points=n,structural_ratio=r,orientation_threshold_deg=t,seed=s) return out
def check_fidelity(evidence, frame): """Full real-frame PCA5 candidate/validity alignment against unchanged reference.""" g=build_organized_geometry(frame) np.testing.assert_array_equal(g.xyz,evidence.frame.geometry.xyz) row=dict(max_normal_error_deg=0.,max_variation_error_deg=0.,validity_differences=0,candidate_differences=0) for oid in (PEG,BOX): expected=compute_geometric_features(g,oid,*local_plane(g,oid,5),GeometryParameters()) actual=evidence.frame.objects[oid] for field in expected.__dataclass_fields__: a,b=getattr(actual,field),getattr(expected,field) if field=='normals': if actual.normal_valid.any(): row['max_normal_error_deg']=max(row['max_normal_error_deg'],float(angular_error(a[actual.normal_valid],b[actual.normal_valid]).max())) np.testing.assert_allclose(a,b,atol=2e-5,rtol=0) elif field=='normal_variation_rad': ok=actual.normal_variation_valid if ok.any():row['max_variation_error_deg']=max(row['max_variation_error_deg'],float(np.rad2deg(np.abs(a[ok]-b[ok])).max())) np.testing.assert_allclose(a,b,atol=2e-5,rtol=0) else:np.testing.assert_array_equal(a,b,err_msg=field) for t in (10,20,30,40): expected_map=expected.valid_points & expected.normal_variation_valid & (np.rad2deg(expected.normal_variation_rad)>t) np.testing.assert_array_equal(evidence.pairs[oid].candidates(t)['orientation'],expected_map) return row
def validate_result(result,evidence,cfg): if len(result.points)>cfg.num_points:raise AssertionError('total node budget') if result.priority_selected.sum()>int(cfg.num_points*cfg.structural_ratio):raise AssertionError('structural ratio') if result.depth_priority_selected.sum()>int(int(cfg.num_points*cfg.structural_ratio)*cfg.depth_priority_fraction):raise AssertionError('depth reservation') if len(np.unique(result.flat_index))!=len(result.points):raise AssertionError('duplicate source pixels') v,u=result.pixels_vu.T np.testing.assert_array_equal(result.points,evidence.frame.geometry.xyz[v,u]) if not np.isfinite(result.points).all():raise AssertionError('invalid point') for oid in (PEG,BOX): keep=result.object_id==oid if not evidence.frame.geometry.observed_mask(oid)[v[keep],u[keep]].all():raise AssertionError('object support') if keep.sum()!=result.object_budgets[oid]:raise AssertionError('object budget') for arr in result.metadata.values(): if len(arr)!=len(result.points):raise AssertionError('metadata alignment')
def evaluate(episode_path,masks_path,output_root,camera='base_camera',selected=(0,15,18,45,80,120),seeds=(0,1,2),make_plots=True): episode_path,masks_path=Path(episode_path).resolve(),Path(masks_path).resolve() with np.load(episode_path,allow_pickle=False) as ar: required=[f'{camera}/seg','peg_id','box_id','peg_pose','box_pose','box_hole_pose','peg_half_sizes','box_hole_radii','seed'] if set(required)-set(ar.files):raise ValueError('GT evaluation fields missing') gt={k:ar[k] for k in required} with np.load(masks_path,allow_pickle=False) as ar:sources=ar['source_frame'] if not np.array_equal(sources,np.arange(len(gt[f'{camera}/seg']))):raise ValueError('every source frame exactly once in order is required') if set(selected)-set(sources.tolist()):raise ValueError('representative source frame missing') track_path=masks_path.with_name('tracking.json') if track_path.exists(): tracking=json.loads(track_path.read_text()) if tracking.get('camera',camera)!=camera:raise ValueError('tracker camera mismatch') original=Path(tracking.get('input') or episode_path) if original.is_file() and digests(original)[1]!=digests(episode_path)[1]:raise ValueError('tracker input mismatch') segmap_path=episode_path.with_name('segmentation_id_map.json') segmap=json.loads(segmap_path.read_text()) if segmap_path.exists() else {} robot_ids=[int(k) for k,v in segmap.items() if v.startswith('panda_')] configs=conditions(seeds) source_paths=[REPO/'visual/runtime'/p for p in ('rgbd.py','geometry.py','normal_estimators.py','pca.py','edge_evidence.py','sampling.py', 'test/run_sampling.py','test/sampling_evaluation.py','test/sampling_plots.py','test/test_sampling.py', 'test/test_sampling_evaluation.py','test/test_sampling_geometry.py', 'test/normal_diagnostics.py','test/run_normal_comparison.py','test/run_structural_edges.py','test/run_normal_diagnostics.py')] config=dict(task='03',input=str(episode_path),masks=str(masks_path),camera=camera, input_sha256=digests(episode_path)[1],masks_sha256=digests(masks_path)[1],conditions=configs, defaults=asdict(SamplingConfig()),tolerances_px_m=TOLERANCES,selected_sources=selected, robot_ids=robot_ids,segmentation_map_sha256=digests(segmap_path)[1] if segmap else None, device='cpu',gpu_executed=False,python=platform.python_version(),numpy=np.__version__,platform=platform.platform(), gt_sampling_input=False,independent_episode=False,source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in source_paths}, timing='one warmup per estimator, rotated order; no GT/I/O/metrics/plots; S0 charged PCA diagnostic evidence too; CPU arrays, no H2D/D2H', fps='source raster order, uniform first row per SeedSequence([seed,object_id]); argmax first-row ties; surface distances seeded by priority rows', sweep='four budgets at .25/20/seed0; four ratios at 256/20/seed0; four angles at 256/.25/seed0; three seeds at 256/.25/20, all frames', single_episode_note='Only this saved RGB-D episode has matching tracker masks; no independent RGB-D episode in visual/data') with ExperimentLogger(team='visual',config=config,seed=0,model='task03_sampling',job_type='evaluate') as logger: output=Path(output_root).resolve()/logger.run_id;output.mkdir(parents=True,exist_ok=False) print('Output:',output,flush=True) for source in source_paths: dest=output/'evaluated_source'/source.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source,dest) pools={k:[] for k in configs};arrays={k:{} for k in configs};fidelity=[];extraction=[] for index,frame in enumerate(iter_saved_rgbd(episode_path,masks_path,camera=camera)): order=['baseline','fd2','pca5'];order=order[index%3:]+order[:index%3] if index==0: for method in order:sample_points(extract_sampling_evidence(frame,method),method={'baseline':'S1','fd2':'S2','pca5':'S3'}[method]) evidence={m:extract_sampling_evidence(frame,m) for m in order} fidelity.append(dict(source_frame=frame.source_frame,**check_fidelity(evidence['pca5'],frame))) extraction.append({m:e.timings_ms for m,e in evidence.items()}) # Everything above accepts current observations only. GT begins here. context=evaluation_context(frame,evidence['pca5'],gt,camera,robot_ids) mapping=dict(S0=evidence['pca5'],S1=evidence['baseline'],S2=evidence['fd2'],S3=evidence['pca5'],S4=evidence['pca5']) archive=dict(source_frame=np.array(frame.source_frame),shape=np.array(frame.depth.shape)) results={};frame_rows={} for key,condition in configs.items(): method=condition['method'];cfg=SamplingConfig(**{k:v for k,v in condition.items() if k!='method'}) result=sample_points(mapping[method],cfg,method=method);validate_result(result,mapping[method],cfg) results[key]=result row,dist=score_selection(result,context);row['source_frame']=frame.source_frame pools[key].append(row);frame_rows[key]=row for k,v in dist.items():arrays[key].setdefault(k,[]).append(v.astype(np.float32)) for field in ('points','pixels_vu','flat_index','object_id','priority_selected','depth_priority_selected'): archive[f'{key}/{field}']=getattr(result,field) for name,values in result.metadata.items():archive[f'{key}/metadata/{name}']=values for method in METHODS[1:]: np.testing.assert_array_equal(results[f'{method}_n256_r0_t20_s0'].flat_index,results['S0_n256_r0_t20_s0'].flat_index) for method,e in evidence.items(): for oid in (PEG,BOX): pair=e.pairs[oid] for t in (10,20,30,40): c=pair.candidates(t) for channel in ('orientation','depth','mask','invalid','occluding','occluded'): archive[f'evidence/{method}/{oid}/{t}/{channel}_flat']=np.flatnonzero(c[channel]) for name,ref in context['references'].items(): archive[f'evaluation/{name}/reference_uv']=ref[0];archive[f'evaluation/{name}/reference_xyz']=ref[1] np.savez_compressed(output/f'f{frame.source_frame:04d}_samples.npz',**archive) save_json(output/f'f{frame.source_frame:04d}_metrics.json',frame_rows) if frame.source_frame in selected and make_plots: primary={m:results[f'{m}_n256_r{0 if m=="S0" else .25:g}_t20_s0'] for m in METHODS} overlays(output,frame,context,primary,mapping);clouds(output,frame,context,primary,mapping) if index%10==0:print(f'Frames {index+1}/{len(sources)}; {len(configs)} conditions each',flush=True) summary={key:summarize(rows,arrays[key]) for key,rows in pools.items()} latency={m:{k:stats([v[m][k] for v in extraction]) for k in extraction[0][m]} for m in ('baseline','fd2','pca5')} data=dict(run_id=logger.run_id,config=config,git_commit=logger.metadata['git_commit'],git_dirty=logger.metadata['git_dirty'], evaluated_frames=len(sources),conditions=len(configs),summary=summary,extraction_latency_ms=latency,fidelity=fidelity) save_json(output/'comparison.json',data) if make_plots:quantitative(output,summary,configs) image_names=['tradeoffs.png','sensitivity.png']+[f'f{s:04d}_{kind}.png' for s in selected for kind in ('overlay','clouds')] body=''.join(f'<p><a href="{p}"><img src="{p}" alt="{p}"></a></p>' for p in image_names if (output/p).exists()) (output/'comparison.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><title>Task03 sampling</title><style>body{{font:15px system-ui;max-width:1800px;margin:24px auto}}img{{width:100%}}pre{{white-space:pre-wrap}}</style><h1>Task03 — current-observation point sampling</h1><p>Run {logger.run_id}; {len(sources)} frames; {len(configs)} conditions; CPU only.<a href="comparison.json">Full summary, source hashes, fidelity, configuration and latency</a>.</p><p>GT is evaluation only. No final structural class, node feature, graph, cache or end-to-end 20Hz validation.Joint matching uses the same pair within 2px AND 3mm; sensitivity 1px/2mm and 3px/5mm. Visible GT, tracker-observed references and sampled referencesare separate denominators. Retention excludes structures already lost to tracking. Surface distances retain all observed points, including contamination.Known-negative ROIs overlap; union is counted once. Priority role differs from detector candidate flag. S4 depth-only maximum is 25% of priority slots,not a raw OR policy. S0 includes PCA diagnostic extraction in its reported total even though its selection ignores candidates.</p><p>Single saved ep000; frames are temporally dependent. Thresholds are diagnostics, no generalization claim or adopted final setting.Every frame has a metrics JSON and selected coordinates/provenance/evidence NPZ; pixels are (v,u), coordinates CV-camera metres.Absent predictions have zero coverage and missing distance counts. 3D viewports clip display only; raw support is not filtered.</p>{body}<details><summary>Configuration</summary><pre>{html.escape(json.dumps(config,indent=2))}</pre></details></html>''',encoding='utf-8') for p in sorted(p for p in output.rglob('*') if p.is_file()): logger.link_output(p,kind='metrics' if p.suffix=='.json' else 'trajectory' if p.suffix=='.npz' else 'reports') logger.log({m:summary[f'{m}_n256_r{0 if m=="S0" else .25:g}_t20_s0']['objects'] for m in METHODS},prefix='eval/task03') logger.record(evaluated_frames=len(sources),evaluation_device='cpu',gpu_executed=False,dataset_sha256=config['input_sha256'],masks_sha256=config['masks_sha256']) return output
def main(): parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') parser.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') parser.add_argument('--out',type=Path,default=REPO/'visual/results/sampling') parser.add_argument('--camera',default='base_camera') args=parser.parse_args();print(evaluate(args.input,args.masks,args.out,args.camera))
if __name__=='__main__':main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343diff --git a/visual/runtime/test/run_adaptive_node_budget.py b/visual/runtime/test/run_adaptive_node_budget.pynew file mode 100644index 0000000..9f02595--- /dev/null+++ b/visual/runtime/test/run_adaptive_node_budget.py@@ -0,0 +1,745 @@+"""Task03-AB: gated CPU offline total-budget ablation; no production changes.++WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03ab-mpl .venv/bin/python -m \+ visual.runtime.test.run_adaptive_node_budget --preservation-before PATH+"""+from __future__ import annotations++import argparse+from dataclasses import dataclass+import html+import json+from numbers import Integral+from pathlib import Path+import platform+import shutil+import subprocess+from time import perf_counter++import numpy as np+from scipy.ndimage import label+from scipy.spatial import cKDTree++from utils.experiment_artifacts import digests+from utils.experiment_logger import ExperimentLogger+from visual.runtime.edge_evidence import PairEvidence+from visual.runtime.geometry import GeometricFeatures, GeometryFrame, OrganizedGeometry+from visual.runtime.rgbd import PEG, BOX, iter_saved_rgbd+from visual.runtime.sampling import (+ SamplingConfig, SamplingEvidence, allocate_budget, extract_candidates,+ extract_sampling_evidence, sample_points,+)+from visual.runtime.test.normal_diagnostics import stats+from visual.runtime.test.run_rim_bottleneck import source_contract, occupancy+from visual.runtime.test.run_sampling import validate_result+from visual.runtime.test.sampling_evaluation import (+ CoverageMatcher, TOLERANCES, evaluation_context, score_selection,+ staged_reference_coverage, summarize,+)++REPO = Path(__file__).resolve().parents[3]+SOURCE = REPO / 'visual/results/sampling/2551448b0fae4c6bbce3caf48774275f'+KEY = 'S3_n256_r0.25_t20_s0'+CONDITIONS = ('Fixed256', 'Adaptive', 'FixedMatched')+OBJECTS = (('peg', PEG), ('box', BOX))+REPRESENTATIVE = (0, 15, 18, 45, 80, 120)+FIELDS = ('points', 'pixels_vu', 'flat_index', 'object_id',+ 'priority_selected', 'depth_priority_selected')+TIMERS = ('candidate_selection', 'budget_allocation', 'structural_sampling', 'surface_fps')+++def write_json(path, value):+ Path(path).write_text(json.dumps(value, indent=2, allow_nan=False) + '\n', encoding='utf-8')+++def distribution(values):+ a = np.asarray([x for x in values if x is not None], float)+ a = a[np.isfinite(a)]+ return dict(stats(a), min=float(a.min()) if len(a) else None)+++def ratio(n, d):+ return n / d if d else None+++def support_counts(counts):+ if len(counts) != 2 or any(not isinstance(x, Integral) or isinstance(x, (bool, np.bool_))+ or x < 0 for x in counts):+ raise ValueError('two nonnegative integer support counts required')+ return tuple(int(x) for x in counts)+++def requested_budget(counts, reference):+ """Only current support counts and an immutable past/current reference."""+ counts = support_counts(counts)+ area = sum(counts)+ minimums = tuple(min(16, x) for x in counts)+ if reference is None:+ if area:+ raise ValueError('positive support requires initialized reference')+ return 0, minimums+ if not isinstance(reference, Integral) or reference <= 0:+ raise ValueError('reference must be a positive integer')+ rounded = (512 * area + int(reference)) // (2 * int(reference))+ return min(256, max(sum(minimums), rounded)), minimums+++@dataclass+class AreaBudget:+ reference: int | None = None+ reference_source: int | None = None++ def step(self, counts, source):+ counts = support_counts(counts)+ if self.reference is None and sum(counts):+ self.reference, self.reference_source = sum(counts), int(source)+ return requested_budget(counts, self.reference)+++def matched_budget(areas, requests):+ """One offline matched-count control, selected without geometry scores."""+ if len(areas) != len(requests) or not len(areas):+ raise ValueError('aligned nonempty counts required')+ target = sum(min(int(a), int(n)) for a, n in zip(areas, requests))+ b = min(range(32, 257), key=lambda n: (abs(sum(min(n, int(a)) for a in areas) - target), n))+ actual = sum(min(b, int(a)) for a in areas)+ return dict(budget=b, adaptive_selected_sum=target, fixed_selected_sum=actual,+ mean_error_nodes=(actual-target)/len(areas), causal_online=False,+ selection='count-only absolute total difference; smaller integer on ties')+++def measure_areas(frame, geometry):+ """Validity count cost and diagnostic raw-mask scans are separate."""+ t0 = perf_counter()+ counts = tuple(int(np.count_nonzero(geometry.observed_mask(oid))) for _, oid in OBJECTS)+ count_ms = (perf_counter()-t0)*1000+ t0 = perf_counter()+ result = {}+ for (name, oid), valid in zip(OBJECTS, counts):+ mask = frame.masks[oid]+ raw = int(np.count_nonzero(mask))+ invalid = int(np.count_nonzero(mask & ~geometry.valid_depth))+ overlap = int(np.count_nonzero(mask & geometry.valid_depth & geometry.overlap_mask))+ if raw != valid + invalid + overlap:+ raise AssertionError('raw/valid exclusion partition')+ result[name] = dict(raw=raw, valid=valid, invalid_depth=invalid,+ positive_depth_overlap=overlap, minimum=min(16, valid))+ raw_ms = (perf_counter()-t0)*1000+ return result, count_ms, raw_ms+++def exact_result(first, second):+ for field in FIELDS:+ np.testing.assert_array_equal(getattr(first, field), getattr(second, field), err_msg=field)+ if set(first.metadata) != set(second.metadata):+ raise AssertionError('feature field mismatch')+ for field in first.metadata:+ np.testing.assert_array_equal(first.metadata[field], second.metadata[field], err_msg=field)+ if first.counts != second.counts or first.object_budgets != second.object_budgets:+ raise AssertionError('selection counts mismatch')+++def exact_saved(result, archive, key=KEY):+ for field in FIELDS:+ np.testing.assert_array_equal(getattr(result, field), archive[f'{key}/{field}'], err_msg=field)+ saved = {n.split('/metadata/')[1] for n in archive.files if n.startswith(key+'/metadata/')}+ if saved != set(result.metadata):+ raise AssertionError('available feature fields mismatch')+ for field in result.metadata:+ np.testing.assert_array_equal(result.metadata[field], archive[f'{key}/metadata/{field}'], err_msg=field)+++def validate_selection(result, evidence, config, candidates):+ validate_result(result, evidence, config)+ counts = [len(candidates[i].points) for _, i in OBJECTS]+ expected = allocate_budget(config.num_points, counts, config.min_points, counts)+ np.testing.assert_array_equal([result.object_budgets[i] for _, i in OBJECTS], expected)+ if len(result.points) != min(config.num_points, sum(counts)):+ raise AssertionError('selected total differs from capacity-limited request')+ if len(np.unique(result.points, axis=0)) != len(result.points):+ raise AssertionError('duplicate XYZ')+ for _, oid in OBJECTS:+ keep = result.object_id == oid+ rows = np.searchsorted(candidates[oid].flat_index, result.flat_index[keep])+ for field, values in result.metadata.items():+ np.testing.assert_array_equal(values[keep], candidates[oid].metadata[field][rows], err_msg=field)+ c = result.counts[oid]+ if c['selected'] != c['priority'] + c['surface_fps'] or c['depth_priority']:+ raise AssertionError('S3 role accounting')+++def save_evidence(path, evidence):+ """Lossless temporary observation cache: global gate before any ablation."""+ f = evidence.frame+ g = f.geometry+ a = dict(xyz=g.xyz, valid_depth=g.valid_depth, overlap=g.overlap_mask)+ for _, oid in OBJECTS:+ a[f'mask/{oid}'] = g.object_masks[oid]+ for field in GeometricFeatures.__dataclass_fields__:+ a[f'feature/{oid}/{field}'] = getattr(f.objects[oid], field)+ for field in PairEvidence.__dataclass_fields__:+ a[f'pair/{oid}/{field}'] = np.asarray(getattr(evidence.pairs[oid], field))+ a['provenance'] = np.array(json.dumps(dict(source_frame=f.source_frame, camera=f.camera,+ frame_idx=f.frame_idx, timestamp=f.timestamp, timings_ms=evidence.timings_ms)))+ np.savez_compressed(path, **a)+++def load_evidence(path):+ with np.load(path, allow_pickle=False) as a:+ p = json.loads(str(a['provenance']))+ g = OrganizedGeometry(a['xyz'], a['valid_depth'], {i:a[f'mask/{i}'] for _, i in OBJECTS}, a['overlap'])+ features = {i:GeometricFeatures(**{k:a[f'feature/{i}/{k}'] for k in GeometricFeatures.__dataclass_fields__})+ for _, i in OBJECTS}+ pairs = {i:PairEvidence(**{k:tuple(a[f'pair/{i}/{k}']) if k == 'shape' else a[f'pair/{i}/{k}']+ for k in PairEvidence.__dataclass_fields__}) for _, i in OBJECTS}+ f = GeometryFrame(p['source_frame'], p['camera'], p['frame_idx'], p['timestamp'], g, features, p['timings_ms'])+ return SamplingEvidence(f, pairs, 'pca5', p['timings_ms'])+++def nearest(source, target):+ if not len(source):+ return np.empty(0)+ return cKDTree(target).query(source)[0]*1000 if len(target) else np.full(len(source), np.nan)+++def distance_summary(distances):+ finite = np.isfinite(distances)+ return dict(distance_mm=distribution(distances), source_count=len(distances),+ missing_count=int((~finite).sum()), within_3mm=int((distances[finite] <= 3).sum()),+ coverage_3mm=ratio(int((distances[finite] <= 3).sum()), len(distances)))+++def general_geometry(frame, evidence, candidates, sample, context):+ report, arrays = {}, {}+ g = evidence.frame.geometry+ for name, oid in OBJECTS:+ obj = candidates[oid]+ x = obj.flat_index+ c = x[obj.metadata['structural_candidate']]+ chosen = sample.object_id == oid+ f = sample.flat_index[chosen]+ p = sample.flat_index[chosen & sample.priority_selected]+ s = sample.flat_index[chosen & ~sample.priority_selected]+ xyz = g.xyz.reshape(-1, 3)+ xf, cp = nearest(xyz[x], xyz[f]), nearest(xyz[c], xyz[p])+ components, count = label(g.observed_mask(oid))+ component_rows = []+ component_index = components.ravel()+ for k in range(1, count+1):+ keep = component_index[x] == k+ nc, np_, nf = (int((component_index[v] == k).sum()) for v in (c, p, f))+ component_rows.append(dict(id=k, support=int(keep.sum()), candidate=nc, priority=np_, final=nf,+ small=bool(keep.sum() <= 64), candidate_without_priority=bool(nc and not np_),+ candidate_without_final=bool(nc and not nf), **distance_summary(xf[keep])))+ paths = dict(X=x, C=c, P=p, S=s, F=f)+ stages = staged_reference_coverage(context['matchers'][name], c, p, s, f)+ depth = occupancy(frame, paths, context['negatives'][name])+ report[name] = dict(x_to_f=distance_summary(xf), c_to_p=distance_summary(cp), components=component_rows,+ stages=stages, occupancy=depth,+ camera_range_m=distribution(np.linalg.norm(xyz[x].astype(float), axis=1)))+ arrays[name+'/c_to_p'] = cp+ arrays[name+'/x_to_f'] = xf+ return report, arrays+++def sampling_timing(sample):+ t = {k:float(sample.timings_ms[k]) for k in (*TIMERS, 'sampling_total')}+ t['gather_packaging_and_other_overhead'] = t['sampling_total']-sum(t[k] for k in TIMERS)+ if t['gather_packaging_and_other_overhead'] < -1e-9:+ raise AssertionError('negative timer residual')+ return t+++def latency_summary(records):+ result = {}+ for condition in CONDITIONS:+ rows = [r for r in records if r['condition'] == condition]+ per_frame, effective, executed = {}, {}, {}+ for r in rows:+ owner = next(x for x in records if x['source_frame'] == r['source_frame']+ and x['repeat'] == r['repeat'] and x['condition'] == (r['alias_of'] or condition))+ for key, value in owner['timings_ms'].items():+ effective.setdefault(key, []).append(value)+ per_frame.setdefault(key, {}).setdefault(r['source_frame'], []).append(value)+ if r['executed']:+ executed.setdefault(key, []).append(value)+ result[condition] = dict(executed_calls=sum(r['executed'] for r in rows),+ alias_calls=sum(not r['executed'] for r in rows),+ frame_median_then_distribution={k:distribution([np.median(v) for v in frames.values()])+ for k, frames in per_frame.items()},+ all_repetitions_effective_including_explicit_alias={k:distribution(v) for k,v in effective.items()},+ executed_only={k:distribution(v) for k,v in executed.items()})+ return result+++def preserve_check(before):+ changed = [name for name, expected in before['sha256'].items()+ if not (REPO/name).is_file() or digests(REPO/name)[1] != expected]+ return dict(checked_files=len(before['sha256']), changed_or_missing=changed, unchanged=not changed)+++def add_temporal_and_pairs(rows):+ for index, row in enumerate(rows):+ if row['source_frame'] != index:+ raise AssertionError('source frame continuity')+ for condition, data in row['conditions'].items():+ previous = rows[index-1]['conditions'][condition] if index else None+ for field in ('requested', 'selected'):+ delta = data[field]-previous[field] if previous else None+ data['delta_'+field] = delta+ data['abs_delta_'+field] = abs(delta) if delta is not None else None+ fixed = row['conditions']['Fixed256']['selected']+ data['node_reduction_vs_fixed256'] = 1-data['selected']/fixed if fixed else None+ for name, _ in OBJECTS:+ base = row['conditions']['Fixed256']['geometry']['objects'][name]+ current = data['geometry']['objects'][name]+ f, a = (v['structural']['tolerance']['2px_3mm']['sampling_retention'] for v in (base, current))+ data['objects'][name]['retention_difference_pp_vs_fixed256'] = (a-f)*100 if a is not None and f is not None else None+ for field in ('mean', 'p95'):+ f, a = (v['surface']['all']['distance_mm'][field] for v in (base, current))+ data['objects'][name]['surface_'+field+'_difference_mm_vs_fixed256'] = a-f if a is not None and f is not None else None+++def make_summary(rows, pools, distance_pools, matched, policy):+ summary = {}+ fixed_sum = sum(r['conditions']['Fixed256']['selected'] for r in rows)+ for condition in CONDITIONS:+ geometry = summarize(pools[condition], distance_pools[condition])+ geometry.pop('timings_ms', None) # timings are paired separately, with explicit aliases+ counts = {field:distribution([r['conditions'][condition][field] for r in rows])+ for field in ('requested', 'selected', 'priority', 'surface', 'shortfall',+ 'delta_requested', 'delta_selected', 'abs_delta_selected')}+ selected = sum(r['conditions'][condition]['selected'] for r in rows)+ objects = {}+ for name, _ in OBJECTS:+ objects[name] = dict(+ allocated=distribution([r['conditions'][condition]['objects'][name]['allocated'] for r in rows]),+ selected=distribution([r['conditions'][condition]['objects'][name]['selected'] for r in rows]),+ density_per_valid_pixel=distribution([r['conditions'][condition]['objects'][name]['density_per_valid_pixel'] for r in rows]),+ retention_difference_pp=distribution([r['conditions'][condition]['objects'][name]['retention_difference_pp_vs_fixed256'] for r in rows]),+ c_to_p_mm=distribution(np.concatenate(distance_pools[condition][name+'/c_to_p'])))+ summary[condition] = dict(counts=counts, selected_sum=selected, node_reduction_fraction=1-selected/fixed_sum,+ geometry=geometry, objects=objects,+ requested_max_frames=[r['source_frame'] for r in rows if r['conditions'][condition]['requested'] == 256],+ requested_min_frames=[r['source_frame'] for r in rows if r['conditions'][condition]['requested'] == r['minimum_total']])+ area = [sum(r['areas'][name]['valid'] for name, _ in OBJECTS) for r in rows]+ median_area = float(np.median(area))+ strata = {}+ for title, ids in [('area_le_median',[i for i,a in enumerate(area) if a <= median_area]),+ ('area_gt_median',[i for i,a in enumerate(area) if a > median_area]),+ ('box_support_zero',[i for i,r in enumerate(rows) if not r['areas']['box']['valid']])]:+ strata[title] = dict(source_frames=ids, objects={name:distribution([+ rows[i]['conditions']['Adaptive']['objects'][name]['retention_difference_pp_vs_fixed256'] for i in ids])+ for name, _ in OBJECTS})+ return dict(conditions=summary, matched=matched,+ policy=dict(alpha=1, reference=policy.reference, reference_source=policy.reference_source,+ rounding='integer half-up', maximum=256, minimum='sum min(16, current object support)'),+ area_strata=dict(median_valid_area=median_area, strata=strata))+++def plot_results(output, rows, latency):+ import matplotlib+ matplotlib.use('Agg')+ import matplotlib.pyplot as plt+ colors = dict(Fixed256='#64748b', Adaptive='#e76f51', FixedMatched='#247ba0')+ x = np.arange(len(rows))+ plotdir = output/'plots'+ plotdir.mkdir(exist_ok=True)+ def finish(fig, axes, filename):+ for ax in np.asarray(axes).ravel():+ for lo, hi in ((18,26),(56,65)):+ if ax.get_xlabel() == 'Source frame':+ ax.axvspan(lo-.5,hi+.5,color='#cbd5e1',alpha=.4)+ ax.grid(alpha=.2)+ ax.legend(fontsize=7, loc='best')+ fig.savefig(plotdir/filename, dpi=140)+ plt.close(fig)+ fig, axes = plt.subplots(4,1,figsize=(15,12),layout='constrained')+ for name, _ in OBJECTS:+ for field, ls in [('raw','--'),('valid','-')]:+ axes[0].plot(x,[r['areas'][name][field] for r in rows],ls,label=name+' '+field)+ for condition in CONDITIONS:+ axes[1].plot(x,[r['conditions'][condition]['selected'] for r in rows],label=condition,color=colors[condition])+ for name, ls in [('peg','-'),('box','--')]:+ axes[2].plot(x,[r['conditions'][condition]['objects'][name]['allocated'] for r in rows],ls,+ label=condition+' '+name,color=colors[condition])+ for field, ls in [('priority','-'),('surface','--')]:+ axes[3].plot(x,[r['conditions'][condition][field] for r in rows],ls,label=condition+' '+field,color=colors[condition])+ for ax,title in zip(axes,['Raw / valid projected pixel areas','Actual point nodes','Object allocated budgets','Priority / Surface roles']):+ ax.set(title=title,xlabel='Source frame')+ finish(fig,axes,'budget_timeseries.png')+ fig, axes = plt.subplots(2,3,figsize=(17,9),layout='constrained')+ area = [sum(r['areas'][n]['valid'] for n,_ in OBJECTS) for r in rows]+ reduction = [r['conditions']['Adaptive']['node_reduction_vs_fixed256']*100 for r in rows]+ for col,(name,_) in enumerate(OBJECTS):+ for condition in CONDITIONS:+ retention = [r['conditions'][condition]['geometry']['objects'][name]['structural']['tolerance']['2px_3mm']['sampling_retention'] for r in rows]+ axes[0,col].scatter(reduction,retention,s=10,label=condition,color=colors[condition],alpha=.7)+ axes[1,col].plot(x,[r['conditions'][condition]['geometry']['objects'][name]['surface']['all']['distance_mm']['p95'] for r in rows],+ label=condition,color=colors[condition])+ axes[0,col].set(title=name+' retention vs Adaptive node reduction',xlabel='Adaptive node reduction (%)',ylabel='Observable reference retention')+ axes[1,col].set(title=name+' X to F p95 distance',xlabel='Source frame',ylabel='mm')+ for condition in CONDITIONS:+ axes[0,2].scatter(area,[r['conditions'][condition]['selected'] for r in rows],s=12,label=condition,color=colors[condition])+ axes[0,2].set(title='Area / node relationship (cap 256)',xlabel='Valid projected pixels',ylabel='Actual nodes',ylim=(0,270))+ axes[1,2].plot(x,[r['conditions']['Adaptive']['delta_selected'] for r in rows],label='Adaptive signed delta')+ axes[1,2].plot(x,[r['conditions']['Adaptive']['abs_delta_selected'] for r in rows],label='Adaptive abs delta')+ axes[1,2].set(title='Temporal node changes',xlabel='Source frame',ylabel='Nodes / frame')+ finish(fig,axes,'preservation_temporal.png')+ fig, axes = plt.subplots(2,2,figsize=(15,9),layout='constrained')+ for condition in CONDITIONS:+ ys = [np.median([next(t for t in latency if t['source_frame']==r['source_frame'] and t['repeat']==rep and+ t['condition']==(next(z for z in latency if z['source_frame']==r['source_frame'] and z['repeat']==rep and z['condition']==condition)['alias_of'] or condition))['timings_ms']['sampling_total']+ for rep in range(3)]) for r in rows]+ axes[0,0].plot(x,ys,label=condition,color=colors[condition])+ axes[0,1].scatter([r['conditions'][condition]['selected'] for r in rows],ys,s=12,label=condition,color=colors[condition])+ axes[0,0].set(title='Paired sampling (frame median; aliases explicit in JSON)',xlabel='Source frame',ylabel='ms')+ axes[0,1].set(title='Selected nodes / actual measured selection latency',xlabel='Actual nodes',ylabel='ms')+ for name,_ in OBJECTS:+ axes[1,0].plot(x,[r['conditions']['Adaptive']['general'][name]['occupancy']['depth_m']['X']['median'] for r in rows],label=name+' median z')+ axes[1,1].scatter([r['areas'][name]['valid'] for r in rows],+ [r['conditions']['Adaptive']['objects'][name]['retention_difference_pp_vs_fixed256'] for r in rows],s=15,label=name)+ axes[1,0].set(title='Observed depth; contamination retained',xlabel='Source frame',ylabel='Camera z (m)')+ axes[1,1].set(title='Small masks / sampling retention loss',xlabel='Valid projected pixels',ylabel='Adaptive - Fixed256 (pp)')+ finish(fig,axes,'latency_depth.png')+++def overlay(output, frame, candidates, samples, context):+ import matplotlib.pyplot as plt+ h,w = frame.depth.shape+ fig,axes = plt.subplots(3,3,figsize=(15,13),layout='constrained')+ for row, oid in enumerate((None, PEG, BOX)):+ union = frame.masks[PEG] | frame.masks[BOX] if oid is None else frame.masks[oid]+ v,u = np.nonzero(union)+ limits = (max(0,int(u.min())-10),min(w-1,int(u.max())+10),min(h-1,int(v.max())+10),max(0,int(v.min())-10)) if len(u) else (0,w-1,h-1,0)+ for col,condition in enumerate(CONDITIONS):+ ax=axes[row,col]; ax.imshow(frame.rgb)+ for name,i in OBJECTS:+ if oid is not None and oid != i:+ continue+ mask=frame.masks[i]+ if mask.any() and not mask.all():+ ax.contour(mask,[.5],colors=['#69ff72'],linewidths=.5)+ flat=candidates[i].flat_index[candidates[i].metadata['structural_candidate']]+ cv,cu=np.unravel_index(flat,(h,w));ax.scatter(cu,cv,s=2,c='#ff5d41',alpha=.45)+ uv=context['references'][name][0];ax.scatter(uv[:,0],uv[:,1],s=12,c='#ff65cc',marker='+',linewidths=.4)+ s=samples[condition]+ keep=np.ones(len(s.points),bool) if oid is None else s.object_id==oid+ for priority,color,marker,size in [(False,'#00d9ff','o',9),(True,'#ffff00','*',24)]:+ pv,pu=s.pixels_vu[keep & (s.priority_selected==priority)].T+ ax.scatter(pu,pv,s=size,c=color,marker=marker,edgecolors='black',linewidths=.2)+ ax.set(xlim=limits[:2],ylim=limits[2:],title=f'{condition} | {"All" if oid is None else ("Peg" if oid==PEG else "Box")} N={int(keep.sum())}')+ ax.axis('off')+ fig.suptitle(f'Source {frame.source_frame} | same crop per row | yellow=Priority, cyan=Surface, red=candidate, pink=GT eval\nMasks may be contaminated; absent object remains empty. No padding.')+ fig.savefig(output/'frames'/f'f{frame.source_frame:04d}_overlay.png',dpi=140);plt.close(fig)+++def html_report(output, data, rows):+ def value(v):+ return 'N/A' if v is None else f'{v:.3f}'+ summary=[]+ for condition,s in data['conditions'].items():+ g=s['geometry']['objects']+ summary.append('<tr>'+''.join(f'<td>{html.escape(str(v))}</td>' for v in [condition,+ value(s['counts']['selected']['mean']), value(s['counts']['selected']['p50']),+ value(100*s['node_reduction_fraction']),+ value(100*g['peg']['structural']['2px_3mm']['sampling_retention']),+ value(100*g['box']['structural']['2px_3mm']['sampling_retention']),+ value(g['peg']['surface']['all']['distance_mm']['p95']),+ value(g['box']['surface']['all']['distance_mm']['p95'])])+'</tr>')+ table=[]+ for r in rows:+ source=r['source_frame']+ links=f'<a href="frames/f{source:04d}_samples.npz">NPZ</a>'+ if source in REPRESENTATIVE:+ links+=f' <a href="frames/f{source:04d}_overlay.png">overlay</a>'+ table.append('<tr>'+''.join(f'<td>{v}</td>' for v in [source,+ r['areas']['peg']['raw'],r['areas']['peg']['valid'],r['areas']['box']['raw'],r['areas']['box']['valid'],+ *[r['conditions'][c]['selected'] for c in CONDITIONS],links])+'</tr>')+ plots=''.join(f'<a href="plots/{p.name}"><img src="plots/{p.name}" alt="{p.stem}"></a>' for p in sorted((output/'plots').glob('*.png')))+ images=''.join(f'<a href="frames/f{s:04d}_overlay.png"><img src="frames/f{s:04d}_overlay.png" alt="Source {s}"></a>' for s in REPRESENTATIVE)+ dependencies=''.join(f'<li><a href="{html.escape(v)}">{html.escape(k)}</a></li>' for k,v in data['dependency_links'].items())+ (output/'adaptive_node_budget.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8">+<title>Task03-AB adaptive total node budget</title><style>body{font:15px system-ui;max-width:1500px;margin:28px auto;padding:0 16px;color:#17212b}img{width:100%;margin:15px 0}table{border-collapse:collapse;width:100%;font-variant-numeric:tabular-nums}td,th{padding:7px;border:1px solid #ccd3da;text-align:right}th:first-child,td:first-child{text-align:left}pre{white-space:pre-wrap}a{color:#146cb2}</style>+<h1>Task03-AB — Adaptive Total Node Budget</h1>'''+f'<p>Run {data["run_id"]}. CPU only; ep000 source 0–120. All 121-frame gates passed before adaptive geometry evaluation.</p>'+ +'<p>First positive valid support fixes the causal reference. Pixel area is projected area, not physical 3D surface area. FixedMatched uses episode counts offline. Same S3 / 20° / .25 / seed0 / 3D FPS; Priority cap changes with requested budget.</p>'+ +'<p>Joint matcher: the same pair within 2px AND 3mm. Retention denominator is tracker-observable references. N/A is preserved. Gray bands mark recorded Box support loss, not independently proven occlusion. Sampling latency excludes PCA5 extraction, GT and I/O; aliases have no invented FPS calls. No GNN/BC, stale-cache integration, GPU or end-to-end 20Hz claim.</p>'+ +'<p><a href="adaptive_node_budget.json">Summary/config</a> · <a href="frame_metrics.json">All frame metrics</a> · <a href="latency.json">Raw/aggregated timing</a> · <a href="verification.json">Gates/preservation</a> · <a href="tests.log">Tests</a> · <a href="implementation.patch">Implementation diff</a></p>'+ +'<table><tr><th>Condition</th><th>Mean N</th><th>Median N</th><th>Reduction %</th><th>Peg retention %</th><th>Box retention %</th><th>Peg surface p95 mm</th><th>Box surface p95 mm</th></tr>'+''.join(summary)+'</table>'+ +plots+'<h2>Representative frames</h2>'+images+'<h2>All frame artifacts</h2><table><tr><th>Source</th><th>Peg raw</th><th>Peg valid</th><th>Box raw</th><th>Box valid</th><th>Fixed256</th><th>Adaptive</th><th>FixedMatched</th><th>Files</th></tr>'+''.join(table)+'</table>'+ +'<h2>Original read-only dependencies</h2><ul>'+dependencies+'</ul><details><summary>Policy / reference / matched control</summary><pre>'+ +html.escape(json.dumps(dict(policy=data['policy'],reference=data['reference_camera'],matched=data['matched']),indent=2))+'</pre></details></html>',encoding='utf-8')+++def evaluate(preservation_before, tests_log=None):+ source=SOURCE+ original=json.loads((source/'comparison.json').read_text())+ cfg=original['config']+ episode=REPO/'visual/data/step2/ep000.npz'+ masks=REPO/'visual/results/runtime_tracking/ep000/masks.npz'+ camera='base_camera'+ saved=[json.loads((source/f'f{i:04d}_metrics.json').read_text())[KEY] for i in range(121)]+ counts=[tuple(r['objects'][n]['counts']['observed'] for n,_ in OBJECTS) for r in saved]+ policy=AreaBudget()+ planned=[policy.step(c,i)[0] for i,c in enumerate(counts)]+ matched=matched_budget([sum(c) for c in counts],planned)+ config=dict(task='03-AB', source_run_id=original['run_id'], input=str(episode), masks=str(masks),+ camera=camera, alpha=1, maximum=256, minimum_per_object=16, matched=matched,+ reference=policy.reference, reference_source=policy.reference_source,+ baseline=KEY, tolerances=TOLERANCES, seed=0, device='cpu', independent_episode=False,+ timing_repetitions=3, extraction='once per frame; lossless cache to enforce all-frame gates first',+ policy_inputs='current observed support counts and fixed first-positive reference only',+ python=platform.python_version(), numpy=np.__version__, platform=platform.platform())+ with ExperimentLogger(team='visual',config=config,seed=0,model='task03ab_adaptive_node_budget',job_type='evaluate') as logger:+ output=logger.directory+ print('Output:',output,flush=True)+ for p in ('cache','frames','evaluated_source'):+ (output/p).mkdir()+ before=json.loads(Path(preservation_before).read_text())+ write_json(output/'preservation_before.json',before)+ verification=dict(gates_passed=False,adaptive_geometry_executed=False,frame_gates=[],+ primary_tolerance='same pair 2px AND 3mm')+ try:+ for path, expected in ((episode,cfg['input_sha256']),(masks,cfg['masks_sha256'])):+ if digests(path)[1] != expected:+ raise AssertionError('input hash mismatch: '+str(path))+ verification['input_hashes']={str(p.relative_to(REPO)):digests(p)[1] for p in (episode,masks)}+ verification['source_contract']=source_contract(source,cfg)+ with np.load(masks,allow_pickle=False) as ar:+ np.testing.assert_array_equal(ar['source_frame'],np.arange(121))+ tracking=json.loads(masks.with_name('tracking.json').read_text())+ if tracking['camera'] != camera:+ raise AssertionError('tracker camera mismatch')+ if digests(Path(tracking['input']))[1] != cfg['input_sha256']:+ raise AssertionError('tracker input provenance mismatch')+ if TOLERANCES != ((1.,.002),(2.,.003),(3.,.005)):+ raise AssertionError('joint tolerances changed')+ for relative in (*cfg['source_sha256'], 'visual/runtime/test/run_rim_bottleneck.py',+ 'visual/runtime/test/run_adaptive_node_budget.py',+ 'visual/runtime/test/test_adaptive_node_budget.py'):+ dest=output/'evaluated_source'/relative+ dest.parent.mkdir(parents=True,exist_ok=True)+ shutil.copyfile(REPO/relative,dest)+ patch=''+ for relative in ('visual/runtime/test/run_adaptive_node_budget.py','visual/runtime/test/test_adaptive_node_budget.py'):+ proc=subprocess.run(['git','diff','--no-index','--','/dev/null',relative],cwd=REPO,capture_output=True,text=True)+ patch+=proc.stdout+ (output/'implementation.patch').write_text(patch)+ if tests_log:+ shutil.copyfile(tests_log,output/'tests.log')+ required=[f'{camera}/seg','peg_id','box_id','peg_pose','box_pose','box_hole_pose','peg_half_sizes','box_hole_radii','seed']+ with np.load(episode,allow_pickle=False) as ar:+ if len(ar[f'{camera}/depth']) != 121:+ raise AssertionError('episode frame count')+ gt={k:ar[k] for k in required} # never supplied to the budget helper or sampler+ robot_ids=cfg['robot_ids']+ pools={c:[] for c in CONDITIONS}+ distance_pools={c:{} for c in CONDITIONS}+ gate_rows=[]+ reference_camera=None+ for index,frame in enumerate(iter_saved_rgbd(episode,masks,camera=camera)):+ if frame.source_frame != index:+ raise AssertionError('source mapping')+ evidence=extract_sampling_evidence(frame,'pca5')+ candidates=extract_candidates(evidence,SamplingConfig(),'S3')+ areas,count_ms,raw_ms=measure_areas(frame,evidence.frame.geometry)+ actual=tuple(areas[n]['valid'] for n,_ in OBJECTS)+ if actual != counts[index]:+ raise AssertionError('observed count mismatch')+ fixed=sample_points(evidence,SamplingConfig(),method='S3')+ validate_selection(fixed,evidence,SamplingConfig(),candidates)+ with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as archive:+ if int(archive['source_frame']) != index:+ raise AssertionError('archive source mapping')+ np.testing.assert_array_equal(archive['shape'],frame.depth.shape)+ for _,oid in OBJECTS:+ c=candidates[oid]+ np.testing.assert_array_equal(c.flat_index[c.metadata['structural_candidate']],+ archive[f'evidence/pca5/{oid}/20/orientation_flat'])+ exact_saved(fixed,archive)+ context=evaluation_context(frame,evidence,gt,camera,robot_ids)+ for name,oid in OBJECTS:+ reference=tuple(archive[f'evaluation/{name}/reference_{s}'] for s in ('uv','xyz'))+ for a,b in zip(reference,context['references'][name]):+ np.testing.assert_array_equal(a,b)+ context['references'][name]=reference+ context['matchers'][name]=CoverageMatcher(evidence.frame.geometry,oid,reference)+ score,dist=score_selection(fixed,context)+ np.testing.assert_equal(score['objects'],saved[index]['objects'])+ score['source_frame']=index+ pools['Fixed256'].append(score)+ for k,v in dist.items():+ distance_pools['Fixed256'].setdefault(k,[]).append(v.astype(np.float32))+ save_evidence(output/'cache'/f'f{index:04d}_evidence.npz',evidence)+ gate_rows.append(dict(source_frame=index,areas=areas,support_count_ms=count_ms,+ raw_area_diagnostics_ms=raw_ms,extraction_ms=evidence.timings_ms))+ if index == policy.reference_source:+ reference_camera=dict(source_frame=index,frame_idx=frame.frame_idx,timestamp=frame.timestamp,+ shape=list(frame.depth.shape),camera=camera,intrinsic=frame.intrinsic.tolist(),+ cam2world=frame.cam2world.tolist(),areas=areas,unit='projected pixel count')+ verification['frame_gates'].append(dict(source_frame=index,support_exact=True,candidate_exact=True,+ fixed256_all_fields_exact=True,reference_exact=True,fixed256_original_metrics_exact=True))+ if index%15 == 0:+ print(f'Gate {index+1}/121: support/candidates/selection/features/reference/metrics exact',flush=True)+ if len(verification['frame_gates']) != 121:+ raise AssertionError('all-frame gate incomplete')+ verification['gates_passed']=True+ write_json(output/'verification.json',verification)+ print('All 121 gates passed. Starting paired ablation.',flush=True)+ except Exception as exc:+ verification['failure']=dict(type=type(exc).__name__,message=str(exc))+ write_json(output/'verification.json',verification)+ (output/'adaptive_node_budget.html').write_text('<!doctype html><meta charset="utf-8"><h1>Gate failed; adaptive geometry NOT RUN</h1><a href="verification.json">Verification</a>')+ raise++ rows=[];timings=[];actual_policy=AreaBudget();warmups=[]+ for index,frame in enumerate(iter_saved_rgbd(episode,masks,camera=camera)):+ evidence=load_evidence(output/'cache'/f'f{index:04d}_evidence.npz')+ candidates=extract_candidates(evidence,SamplingConfig(),'S3')+ area=gate_rows[index]['areas']+ current_counts=tuple(area[n]['valid'] for n,_ in OBJECTS)+ request,minimums=actual_policy.step(current_counts,index)+ if request != planned[index]:+ raise AssertionError('causal policy differs from count-only planning')+ configs=dict(Fixed256=SamplingConfig(),Adaptive=SamplingConfig(num_points=request,min_points=minimums),+ FixedMatched=SamplingConfig(num_points=matched['budget']))+ owner={};unique={}+ for condition,c in configs.items():+ signature=(c.num_points,tuple(min(m,a) for m,a in zip(c.min_points,current_counts)))+ owner[condition]=unique.setdefault(signature,condition)+ names=list(dict.fromkeys(owner.values()))+ if index == 0:+ for condition in names:+ sample_points(evidence,configs[condition],method='S3')+ warmups.append(dict(condition=condition,source_frame=0,measured=False))+ selected={}+ budget_times=[]+ for repeat in range(3):+ start=perf_counter();check=requested_budget(current_counts,actual_policy.reference)+ budget_times.append((perf_counter()-start)*1000)+ if check != (request,minimums):+ raise AssertionError('deterministic budget')+ order=names[(index+repeat)%len(names):]+names[:(index+repeat)%len(names)]+ for condition in order:+ sample=sample_points(evidence,configs[condition],method='S3')+ measured=sampling_timing(sample)+ validate_selection(sample,evidence,configs[condition],candidates)+ if repeat:+ exact_result(sample,selected[condition])+ else:+ selected[condition]=sample+ timings.append(dict(source_frame=index,repeat=repeat,condition=condition,executed=True,+ alias_of=None,order=order,timings_ms=measured))+ for condition in CONDITIONS:+ if owner[condition] != condition:+ timings.append(dict(source_frame=index,repeat=repeat,condition=condition,executed=False,+ alias_of=owner[condition],timings_ms=None))+ results={c:selected[owner[c]] for c in CONDITIONS}+ with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as ar:+ exact_saved(results['Fixed256'],ar)+ if request == 256:+ exact_saved(results['Adaptive'],ar)+ # No GT is supplied until all selections and deterministic checks are complete.+ context=evaluation_context(frame,evidence,gt,camera,robot_ids)+ with np.load(source/f'f{index:04d}_samples.npz',allow_pickle=False) as ar:+ for name,oid in OBJECTS:+ reference=tuple(ar[f'evaluation/{name}/reference_{s}'] for s in ('uv','xyz'))+ for a,b in zip(reference,context['references'][name]):+ np.testing.assert_array_equal(a,b)+ context['references'][name]=reference+ context['matchers'][name]=CoverageMatcher(evidence.frame.geometry,oid,reference)+ row=dict(gate_rows[index],minimum_total=sum(minimums),adaptive_budget_ms=budget_times,+ intrinsic=frame.intrinsic.tolist(),cam2world=frame.cam2world.tolist(),conditions={})+ archive=dict(source_frame=np.array(index),shape=np.array(frame.depth.shape))+ for name,oid in OBJECTS:+ c=candidates[oid]+ archive[f'support/{name}/flat_index']=c.flat_index+ archive[f'support/{name}/xyz']=c.points+ archive[f'candidate/{name}/flat_index']=c.flat_index[c.metadata['structural_candidate']]+ archive[f'candidate/{name}/xyz']=c.points[c.metadata['structural_candidate']]+ for suffix,a in zip(('uv','xyz'),context['references'][name]):+ archive[f'evaluation/{name}/reference_{suffix}']=a+ for condition,sample in results.items():+ if condition == 'Fixed256':+ score=pools['Fixed256'][index]+ else:+ score,dist=score_selection(sample,context);score['source_frame']=index+ pools[condition].append(score)+ for k,v in dist.items():+ distance_pools[condition].setdefault(k,[]).append(v.astype(np.float32))+ general,dist=general_geometry(frame,evidence,candidates,sample,context)+ for k,v in dist.items():+ distance_pools[condition].setdefault(k,[]).append(v.astype(np.float32))+ object_rows={}+ for name,oid in OBJECTS:+ c=sample.counts[oid]+ object_rows[name]=dict(allocated=c['budget'],selected=c['selected'],priority=c['priority'],+ surface=c['surface_fps'],candidates=c['candidates'],selected_candidates=c['selected_candidates'],+ shortfall=c['budget']-c['selected'],minimum_support_shortfall=max(0,16-area[name]['valid']),+ density_per_valid_pixel=ratio(c['selected'],area[name]['valid']),+ density_per_raw_pixel=ratio(c['selected'],area[name]['raw']))+ n=configs[condition].num_points+ row['conditions'][condition]=dict(requested=n,selected=len(sample.points),+ allocated_total=sum(sample.object_budgets.values()),priority=int(sample.priority_selected.sum()),+ surface=int((~sample.priority_selected).sum()),priority_cap=n//4,+ shortfall=n-len(sample.points),maximum_saturated=n==256,minimum_saturated=n==sum(minimums),+ alias_of=owner[condition] if owner[condition]!=condition else None,+ objects=object_rows,geometry=score,general=general)+ for field in FIELDS:+ archive[f'{condition}/{field}']=getattr(sample,field)+ for field,a in sample.metadata.items():+ archive[f'{condition}/metadata/{field}']=a+ rows.append(row)+ np.savez_compressed(output/'frames'/f'f{index:04d}_samples.npz',**archive)+ if index in REPRESENTATIVE:+ overlay(output,frame,candidates,results,context)+ if index%15 == 0:+ print(f'Ablation {index+1}/121: adaptive request={request}, matched={matched["budget"]}',flush=True)+ add_temporal_and_pairs(rows)+ latency=dict(raw=timings,summary=latency_summary(timings),warmups=warmups,+ adaptive_budget_ms=distribution([np.median(r['adaptive_budget_ms']) for r in rows]),+ support_count_ms=distribution([r['support_count_ms'] for r in rows]),+ raw_area_diagnostics_ms=distribution([r['raw_area_diagnostics_ms'] for r in rows]),+ extraction_ms={k:distribution([r['extraction_ms'][k] for r in rows]) for k in rows[0]['extraction_ms']},+ scope='CPU same process, 3 rotated repetitions; per-frame median then across frames. Raw diagnostic scan excluded; support count shared once. Aliases have timings_ms=null; effective statistics reference an actual owner call. Gather residual includes overhead. GT/I/O/plots/extraction excluded from sampling_total.')+ data=make_summary(rows,pools,distance_pools,matched,actual_policy)+ import os+ data.update(run_id=logger.run_id,source_run_id=original['run_id'],config=config,+ reference_camera=reference_camera,latency=latency['summary'],+ input_hashes=verification['input_hashes'],source_contract=verification['source_contract'],+ dependency_links={k:os.path.relpath(v,output) for k,v in dict(+ original_comparison=source/'comparison.json', original_html=source/'comparison.html',+ original_samples_frame0=source/'f0000_samples.npz', rgbd=episode, tracker_masks=masks).items()})+ write_json(output/'adaptive_node_budget.json',data)+ write_json(output/'frame_metrics.json',rows)+ write_json(output/'latency.json',latency)+ plot_results(output,rows,timings)+ html_report(output,data,rows)+ verification.update(adaptive_geometry_executed=True,deterministic_repetitions=True,+ adaptive_request256_exact_frames=[r['source_frame'] for r in rows if r['conditions']['Adaptive']['requested']==256],+ preservation=preserve_check(before),evaluated_frames=len(rows),gpu_executed=False,+ source_snapshot_sha256={str(p.relative_to(output/'evaluated_source')):digests(p)[1]+ for p in (output/'evaluated_source').rglob('*') if p.is_file()})+ if not verification['preservation']['unchanged']:+ raise AssertionError('pre-existing source/artifact changed')+ write_json(output/'verification.json',verification)+ for p in sorted(output.rglob('*')):+ if p.is_file() and p.name not in ('config.yaml','metadata.json','metrics.json','manifest.json') and not p.name.endswith('.tracking.json'):+ logger.link_output(p,kind='metrics' if p.suffix=='.json' else 'trajectory' if p.suffix=='.npz' else 'reports')+ logger.log({c:dict(mean_nodes=data['conditions'][c]['counts']['selected']['mean'],+ reduction=data['conditions'][c]['node_reduction_fraction']) for c in CONDITIONS},prefix='eval/task03ab')+ logger.record(evaluated_frames=121,evaluation_device='cpu',gpu_executed=False,source_run_id=original['run_id'])+ print('Completed:',output,flush=True)+ return output+++def main():+ parser=argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--preservation-before',type=Path,required=True)+ parser.add_argument('--tests-log',type=Path)+ args=parser.parse_args()+ evaluate(args.preservation_before,args.tests_log)+++if __name__ == '__main__':+ main()diff --git a/visual/runtime/test/test_adaptive_node_budget.py b/visual/runtime/test/test_adaptive_node_budget.pynew file mode 100644index 0000000..e082856--- /dev/null+++ b/visual/runtime/test/test_adaptive_node_budget.py@@ -0,0 +1,182 @@+"""Adaptive total-budget contracts; shared sampler/evaluator remain unchanged."""+from dataclasses import replace+import json+from pathlib import Path+import tempfile+import unittest++import numpy as np++from visual.runtime.geometry import build_organized_geometry+from visual.runtime.rgbd import PEG, BOX+from visual.runtime.sampling import SamplingConfig, extract_candidates, extract_sampling_evidence, sample_points+from visual.runtime.test.normal_diagnostics import synthetic_frame, synthetic_case+from visual.runtime.test.sampling_evaluation import CoverageMatcher+from visual.runtime.test.run_adaptive_node_budget import (+ AreaBudget, requested_budget, matched_budget, measure_areas, exact_result,+ exact_saved, validate_selection, save_evidence, load_evidence, distance_summary,+ nearest, distribution, latency_summary, sampling_timing, preserve_check,+)++K = np.array([[100.,0,16.],[0,100.,16.],[0,0,1.]])+++class AdaptiveBudgetTests(unittest.TestCase):+ def frame(self, counts=(200,200)):+ a,b=counts+ masks={PEG:np.zeros((32,32),bool),BOX:np.zeros((32,32),bool)}+ masks[PEG].ravel()[:a]=True+ masks[BOX].ravel()[512:512+b]=True+ return replace(synthetic_frame(np.full((32,32),.4,np.float32),K,masks[PEG]),masks=masks)++ def test_first_positive_reference_never_resets(self):+ p=AreaBudget()+ self.assertEqual(p.step((0,0),0),(0,(0,0)))+ self.assertIsNone(p.reference)+ self.assertEqual(p.step((100,100),1)[0],256)+ self.assertEqual(p.step((50,50),2)[0],128)+ self.assertEqual(p.step((0,0),3)[0],0)+ self.assertEqual(p.step((0,200),4)[0],256)+ self.assertEqual((p.reference,p.reference_source),(200,1))++ def test_half_up_minimum_maximum_and_invalid_inputs(self):+ # 256*81/512 = 40.5 -> 41, rather than ties-to-even 40.+ self.assertEqual(requested_budget((40,41),512)[0],41)+ self.assertEqual(requested_budget((16,16),100000)[0],32)+ self.assertEqual(requested_budget((0,20),100000),(16,(0,16)))+ self.assertEqual(requested_budget((2,3),100000),(5,(2,3)))+ self.assertEqual(requested_budget((1000,1000),100)[0],256)+ for counts in ((-1,0),(True,0),(1.2,0),(1,)):+ with self.assertRaises(ValueError):requested_budget(counts,10)+ with self.assertRaises(ValueError):requested_budget((1,0),None)+ with self.assertRaises(ValueError):requested_budget((0,0),0)+ with self.assertRaises(ValueError):SamplingConfig(num_points=16)++ def test_causal_prefix_and_future_independence(self):+ prefix=[(0,0),(100,200),(60,50),(0,0)]+ def run(sequence):+ p=AreaBudget()+ return [p.step(c,i) for i,c in enumerate(sequence)]+ self.assertEqual(run(prefix),run(prefix+[(100000,100000),(1,1)])[:len(prefix)])+ self.assertEqual(run(prefix),run(prefix+[(0,0),(0,4)])[:len(prefix)])+ values=[requested_budget((i,0),500)[0] for i in range(1000)]+ self.assertEqual(values,sorted(values))++ def test_raw_valid_partition_invalid_and_overlap(self):+ f=self.frame((200,100));m={k:v.copy() for k,v in f.masks.items()}+ m[BOX].ravel()[0:5]=True+ d=f.depth.copy();d.ravel()[5:10]=[0,-1,np.nan,np.inf,-np.inf]+ f=replace(f,depth=d,masks=m)+ e=extract_sampling_evidence(f)+ areas,count_ms,raw_ms=measure_areas(f,e.frame.geometry)+ self.assertEqual(areas['peg']['raw'],200)+ self.assertEqual(areas['peg']['valid'],190)+ self.assertEqual(areas['peg']['invalid_depth'],5)+ self.assertEqual(areas['peg']['positive_depth_overlap'],5)+ self.assertEqual(areas['box']['valid'],100)+ self.assertGreaterEqual(count_ms,0);self.assertGreaterEqual(raw_ms,0)+ c=extract_candidates(e,SamplingConfig())+ self.assertEqual(len(c[PEG].points),areas['peg']['valid'])++ def test_sampler_empty_sparse_capacity_and_alignment(self):+ for counts in ((0,0),(3,4),(0,5),(100,0),(200,200)):+ f=self.frame(counts);e=extract_sampling_evidence(f)+ n,mins=requested_budget(counts,100000)+ cfg=SamplingConfig(num_points=n,min_points=mins)+ s=sample_points(e,cfg)+ c=extract_candidates(e,cfg)+ validate_selection(s,e,cfg,c)+ self.assertEqual(len(s.points),min(n,sum(counts)))+ self.assertEqual(s.points.shape,(len(s.points),3))+ self.assertEqual(len(np.unique(s.flat_index)),len(s.flat_index))+ self.assertLessEqual(s.priority_selected.sum(),n//4)+ self.assertTrue(all(s.counts[o]['selected']>=min(16,counts[o]) for o in (PEG,BOX)))+ np.testing.assert_array_equal(f.depth,np.full((32,32),.4,np.float32))++ def test_256_reproduction_including_support_shortfall(self):+ for counts in ((200,200),(0,100),(3,4),(0,0)):+ e=extract_sampling_evidence(self.frame(counts))+ a=sample_points(e,SamplingConfig())+ b=sample_points(e,SamplingConfig(num_points=256,min_points=tuple(min(16,c) for c in counts)))+ exact_result(a,b)+ archive={f'baseline/{field}':getattr(a,field) for field in (+ 'points','pixels_vu','flat_index','object_id','priority_selected','depth_priority_selected')}+ archive.update({f'baseline/metadata/{k}':v for k,v in a.metadata.items()})+ class Archive(dict):+ @property+ def files(self):return list(self)+ exact_saved(b,Archive(archive),'baseline')+ archive['baseline/points']=a.points+1+ if len(a.points):+ with self.assertRaises(AssertionError):exact_saved(b,Archive(archive),'baseline')++ def test_requested_priority_cap_and_roles(self):+ f,_,_=synthetic_case('crease',K,shape=(32,32))+ e=extract_sampling_evidence(f)+ for n in (16,41,64,256):+ cfg=SamplingConfig(num_points=n,min_points=(16,0))+ s=sample_points(e,cfg)+ validate_selection(s,e,cfg,extract_candidates(e,cfg))+ capacity=sum(int(c.metadata['structural_candidate'].sum()) for c in extract_candidates(e,cfg).values())+ self.assertEqual(int(s.priority_selected.sum()),min(n//4,capacity))+ self.assertEqual(s.counts[PEG]['selected'],s.counts[PEG]['priority']+s.counts[PEG]['surface_fps'])++ def test_gt_annotation_and_reference_cannot_affect_selection(self):+ f=self.frame();e=extract_sampling_evidence(f)+ p=AreaBudget();n,mins=p.step((200,200),0)+ cfg=SamplingConfig(num_points=n,min_points=mins)+ before=sample_points(e,cfg)+ g=e.frame.geometry+ for shift in (0.,100.):+ reference=(np.array([[0.,0.]]),g.xyz[0,0][None]+shift)+ CoverageMatcher(g,PEG,reference).score(before.flat_index[before.object_id==PEG])+ after=sample_points(e,cfg)+ exact_result(before,after)+ self.assertEqual(p.reference,400)+ with self.assertRaises(TypeError):sample_points(e,cfg,gt={})++ def test_lossless_evidence_cache_and_source_preservation(self):+ e=extract_sampling_evidence(self.frame());a=sample_points(e)+ with tempfile.TemporaryDirectory() as tmp:+ path=Path(tmp)/'e.npz';save_evidence(path,e);loaded=load_evidence(path)+ exact_result(a,sample_points(loaded))+ np.testing.assert_array_equal(e.frame.geometry.xyz,loaded.frame.geometry.xyz)+ from visual.runtime.test.run_adaptive_node_budget import REPO+ relative='visual/runtime/sampling.py'+ from utils.experiment_artifacts import digests+ self.assertTrue(preserve_check({'sha256':{relative:digests(REPO/relative)[1]}})['unchanged'])+ self.assertFalse(preserve_check({'sha256':{relative:'incorrect'}})['unchanged'])++ def test_fixedmatched_capacity_tie_and_count_only(self):+ m=matched_budget([1000,1000],[100,101])+ self.assertEqual(m['budget'],100)+ self.assertEqual(m['mean_error_nodes'],-.5)+ self.assertFalse(m['causal_online'])+ self.assertEqual(matched_budget([5,1000],[5,100])['budget'],100)+ self.assertEqual(matched_budget([5,5],[5,5])['budget'],32)+ self.assertEqual(matched_budget([1000],[16])['mean_error_nodes'],16)++ def test_missing_distance_ratios_distributions_and_timer_aliases(self):+ a=distance_summary(nearest(np.ones((3,3)),np.empty((0,3))))+ self.assertEqual(a['missing_count'],3);self.assertEqual(a['coverage_3mm'],0)+ self.assertIsNone(distance_summary(np.empty(0))['coverage_3mm'])+ self.assertEqual(distribution([1,2,3,None,np.nan])['mean'],2)+ self.assertEqual(distribution([1,2,3])['min'],1)+ raw=[]+ for frame in range(2):+ for repeat in range(3):+ for c in ('Fixed256','Adaptive','FixedMatched'):+ alias='Fixed256' if c=='Adaptive' else None+ raw.append(dict(source_frame=frame,repeat=repeat,condition=c,executed=alias is None,+ alias_of=alias,timings_ms=None if alias else {'sampling_total':float(frame+repeat+1)}))+ s=latency_summary(raw)+ self.assertEqual(s['Adaptive']['executed_calls'],0)+ self.assertEqual(s['Adaptive']['alias_calls'],6)+ self.assertEqual(s['Fixed256']['frame_median_then_distribution']['sampling_total']['mean'],2.5)+ self.assertEqual(s['Adaptive']['frame_median_then_distribution'],s['Fixed256']['frame_median_then_distribution'])+ t=sampling_timing(sample_points(extract_sampling_evidence(self.frame())))+ self.assertGreaterEqual(t['gather_packaging_and_other_overhead'],0)+++if __name__ == '__main__':+ unittest.main()diff --git a/docs/visual-graph-integration/03ab_adaptive_node_budget.md b/docs/visual-graph-integration/03ab_adaptive_node_budget.mdnew file mode 100644index 0000000..1138ab8--- /dev/null+++ b/docs/visual-graph-integration/03ab_adaptive_node_budget.md@@ -0,0 +1,398 @@+# Task 03-AB — Adaptive Total Node Budget Ablation++**121프레임 구현·검증·실험을 완료했다.** 첫 유효 관측 면적을 고정 reference로 쓰는 선형 정책은+Fixed256 대비 평균 node 수를 **62.93%**, 평균 sampling 시간을 **45.55%** 줄였다.+그 대가로 Peg seam retention은 **61.28% → 28.16%**, Box rim은 **11.43% → 7.77%**로 낮아졌다.+이 결과는 geometry 손실이 작다는 가설을 지지하지 않는다.++평균 95점의 FixedMatched와 비교하면 Adaptive의 누적 reference retention과 전체 표면 거리는+유리하지만, 프레임별 평균 retention과 일부 작은 영역의 보존은 불리하다.+이번 결과만으로 Adaptive를 최종 sampling 정책으로 채택하거나 일반화된 최적 budget으로 판단하지 않는다.++Run: `f68c59f210b5499dadc7e962c7f64492`.+[정적 HTML](../../experiments/f68c59f210b5499dadc7e962c7f64492/adaptive_node_budget.html),+[설정·summary JSON](../../experiments/f68c59f210b5499dadc7e962c7f64492/adaptive_node_budget.json),+[121프레임 원시 metrics](../../experiments/f68c59f210b5499dadc7e962c7f64492/frame_metrics.json),+[latency](../../experiments/f68c59f210b5499dadc7e962c7f64492/latency.json),+[검증 기록](../../experiments/f68c59f210b5499dadc7e962c7f64492/verification.json),+[추가 집계](../../experiments/f68c59f210b5499dadc7e962c7f64492/analysis.json).++## 1. 구현과 실행 전 관문++[승인된 계획](03ab_adaptive_node_budget_plan.md)과 [Vision–Graph 계약](00_interface.md)을 따랐다.+새 repository 파일은 다음 세 개다.++| 파일 | 내용 |+| --- | --- |+| [run_adaptive_node_budget.py](../../visual/runtime/test/run_adaptive_node_budget.py) | 평가 전용 budget helper, 전체 관문, 기존 sampler/evaluator 호출, 세 조건의 평가·timing·NPZ·HTML |+| [test_adaptive_node_budget.py](../../visual/runtime/test/test_adaptive_node_budget.py) | reference·반올림·causality·minimum/capacity·정렬·GT 독립성·집계 테스트 |+| 이 문서 | 실제 수치, 실패 사례, 재현 방법과 범위 |++Production `sampling.py`, normal estimator, 기존 evaluator, tracking, Task03-D/E/F 및 Graph 코드는+변경하지 않았다. 기존 `allocate_budget()`와 `sample_points()`를 그대로 사용한다.+평가에는 기존 `CoverageMatcher`, `score_selection`, `summarize`, 단계별 coverage helper와+기존 source 보존·ROI occupancy 진단 helper를 재사용했다. Sampler를 복제하지 않았다.++Baseline은 Task03 run `2551448b0fae4c6bbce3caf48774275f`의 `S3_n256_r0.25_t20_s0`다.+S3 optimized PCA5 orientation-only / 20° / ratio .25 / seed 0 / 3D Euclidean Priority·Surface FPS /+observed-points allocation / Peg·Box minimum 각 16점을 고정했다.+Task03-E depth metric과 Task03-F local grouping은 사용하지 않았다.++**다음 관문을 전체 121프레임에서 통과한 뒤에만 Adaptive/FixedMatched geometry 평가를 시작했다.**++| 관문 | 결과 |+| --- | --- |+| RGB-D와 tracker mask hash, source 0–120 mapping, camera/input provenance | 일치 |+| 현재 sampler와 원본 evaluated source, 기존 평가 함수·matcher·상수 의미 | 기존 source 계약 검사 통과. 평가 파일의 기존 additive helper는 허용 |+| 재추출 support count와 저장 observed count | Peg/Box 전 프레임 exact |+| optimized PCA5 20° orientation candidate flat index | Peg/Box 전 프레임 exact |+| Fixed256 선택 flat index·순서·XYZ·pixel·object·role·모든 저장 feature | 전 프레임 exact |+| 저장 reference UV/XYZ·순서 및 기존 frame geometry metrics | 전 프레임 exact. 같은 pair의 2px AND 3mm 유지 |++기존 Task03 NPZ에는 dense feature 전체가 없으므로 `extract_sampling_evidence()`를 프레임당+한 번 실행했다. 새 run의 `cache/fNNNN_evidence.npz`에 observation evidence를 손실 없이 저장하고,+전체 관문 통과 후 이를 재사용했다. 54조건 Task03 sweep, simulator, tracker는 재실행하지 않았다.++입력은 ep000 / `base_camera` / 512×512 / source 0–120, 총 121프레임이다.+Episode SHA-256은 `22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba`,+mask SHA-256은 `6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042`다.++## 2. 확정한 정책과 실제 node 수++정책 입력은 `A_valid,o = count_nonzero(geometry.observed_mask(o))`다.+Finite-positive depth, tracker 소속, overlap 제외를 만족하는 이 행 수가 기존 allocation의 observed+count와 정확히 일치했다. Normal validity나 GT로 면적을 수정하지 않는다.+Raw tracker 면적은 별도의 진단 값이다. 두 값 모두 pixel 단위 투영 면적이며 물리 표면적이 아니다.++첫 양의 관측인 source 0의 Peg 11,780 + Box 11,665 = **A_ref 23,445px**를 episode 끝까지 고정했다.+Reference camera intrinsic·cam2world·resolution·timestamp와 frame별 camera state는 JSON에 기록했다.+Reference를 성능이나 미래 면적으로 재선택하지 않았다. 다른 camera/resolution에 그대로 적용할+보편적 calibration 값으로 해석하지 않는다.++```python+minimums = (min(16, A_peg), min(16, A_box))+rounded = (512 * (A_peg + A_box) + A_ref) // (2 * A_ref)+requested = min(256, max(sum(minimums), rounded))+```++최초 양의 관측 전에는 요청 0이다. 이후에도 support 0이면 요청·선택 모두 0이며 reference는 보존한다.+Config에는 support-capped minimum tuple을 전달해 작은 요청량에서도 기존 validation을 유지했다.+이는 기존 allocator의 `min(capacity,16)` 예약과 동일하다. 실제 수는 `min(requested, total support)`다.+GT·미래 frame·geometry 평가 수치는 budget/selection에 입력하지 않는다.++FixedMatched는 count-only 절대 총량 차이 최소화 규칙으로 **b=95**를 선택했다.+Adaptive 총 선택 11,482개에 대해 FixedMatched는 11,495개로, frame당 **+0.10744개** 차이다.+정수 제약으로 평균이 완전히 같지는 않다. 이 조건은 전체 episode count를 사용하는 offline+control이며 causal 온라인 정책이 아니다. Adaptive reference와 선택에는 b를 제공하지 않았다.++| 실제 point node 수 | Fixed256 | Adaptive | FixedMatched |+| --- | ---: | ---: | ---: |+| 평균 | 256.00 | 94.89 | 95.00 |+| 중앙값 | 256 | 78 | 95 |+| p95 | 256 | 232 | 95 |+| 최소 / 최대 | 256 / 256 | 45 / 256 | 95 / 95 |+| 전체 합계 | 30,976 | 11,482 | 11,495 |+| ���균·총량 절감률 vs Fixed256 | — | 62.93% | 62.89% |++Adaptive의 중앙값은 Fixed256보다 69.53% 작지만 **최대 node 수는 줄지 않았다**.+요청 256 포화는 source 0,1,2의 3프레임이며 모두 원본 S3와 exact 재현됐다.+총 minimum 포화는 0프레임, 최저 요청 45는 source 69,70이었다.+이 episode에서는 모든 조건의 request=allocated 합계=selected였고 shortfall은 모두 0이다.+원본 계약의 support 부족·빈 관측 출력은 합성 테스트에서 별도로 확인했다.+Adaptive object allocation이 관측 가능한 minimum에 닿은 경우는 Box 1프레임, Peg 0프레임이었다.++| 평균 물체별 selected | Fixed256 | Adaptive | FixedMatched |+| --- | ---: | ---: | ---: |+| Peg | 161.98 | 59.97 | 58.88 |+| Box | 94.02 | 34.93 | 36.12 |+| 전체 Priority | 64.00 | 23.28 | 23.00 |+| 전체 Surface | 192.00 | 71.61 | 72.00 |++Priority cap은 각 frame의 **request**에 대해 `floor(.25 * request)`로 재계산했다.+Adaptive의 실제 Priority는 11–64개다. Node 감소와 Priority quota 감소가 함께 발생하므로,+결과를 Priority만의 독립 인과 효과로 분해하지 않는다. Surface가 선택한 candidate membership은+Priority role과 별도 기록했다.++### Raw / valid 면적 진단++| 121프레임 합계, pixel-frame | Peg | Box |+| --- | ---: | ---: |+| Raw tracker mask | 687,830 | 367,494 |+| Valid observed support | 685,762 | 365,372 |+| Invalid/nonpositive depth로 제외 | 0 | 54 |+| Finite-positive overlap으로 제외 | 2,068 | 2,068 |++Raw-valid 차이는 여기서는 위 두 제외 항목으로 설명된다. 그렇다고 남은 valid support가 GT 물체의+정확한 mask라는 뜻은 아니다. Finite-positive tracker 오염은 두 면적에 모두 남는다.+기존 negative ROI와 depth 분포도 보존했으며 mask·depth를 교정하지 않았다.++## 3. 구조 보존과 FixedMatched 비교++Primary retention은 **같은 point/reference pair가 ≤2px AND ≤3mm**를 만족할 때의+`unique covered reference / tracker-observable reference`다. GT visible과 tracker observable을 분리했다.+분모 0은 N/A다. 아래 micro 집계는 각 frame의 reference count를 합한 것이며 물리 point identity를+episode 전체에서 추적한 수가 아니다.++| 구조 | GT visible / observable | Fixed256 | Adaptive | FixedMatched |+| --- | ---: | ---: | ---: | ---: |+| Peg seam | 32,664 / 32,460 | 19,893 / 32,460 = 61.28% | 9,141 / 32,460 = 28.16% | 8,410 / 32,460 = 25.91% |+| Box rim | 1,778 / 1,365 | 156 / 1,365 = 11.43% | 106 / 1,365 = 7.77% | 85 / 1,365 = 6.23% |++Adaptive는 Fixed256보다 Peg **−33.12pp**, Box **−3.66pp**다.+Fixed256가 덮은 reference 수 대비로는 각각 45.95%, 67.95%를 유지했다.+같은 frame의 observable 집합이 세 조건에서 동일하므로 이 추가 손실을 관측 소실 탓으로 돌리지 않는다.+Visible reference 중 관측부터 잃은 수는 Peg 204 / Box 413으로 모든 조건에서 같았다.+관측 가능하지만 Final에서 보존하지 못한 수는 Fixed256의 12,567 / 1,209에서+Adaptive의 **23,319 / 1,259**로 증가했다.++Candidate가 덮는 unique reference는 Peg 30,355 / Box 1,143으로 모든 조건에서 동일하다.+선택 이후 단계는 다음과 같다. 각 triple은 **selected node / matching node / unique reference**다.++| 물체 / 조건 | Priority triple | Final triple | Surface가 Priority에 추가한 unique reference |+| --- | ---: | ---: | ---: |+| Peg Fixed256 | 5,412 / 4,834 / 19,588 | 19,600 / 4,936 / 19,893 | 305 |+| Peg Adaptive | 2,004 / 1,783 / 8,935 | 7,256 / 1,833 / 9,141 | 206 |+| Peg FixedMatched | 1,942 / 1,683 / 8,226 | 7,125 / 1,734 / 8,410 | 184 |+| Box Fixed256 | 2,332 / 40 / 103 | 11,376 / 67 / 156 | 53 |+| Box Adaptive | 813 / 26 / 75 | 4,226 / 39 / 106 | 31 |+| Box FixedMatched | 841 / 17 / 47 | 4,370 / 36 / 85 | 38 |++Candidate/Priority/Surface/Final의 matching node·reference ID·coverage, 겹침과 집합 차이를+모든 frame JSON에 저장했다. Surface 자체의 reference 수와 위의 추가분도 구분한다.+같은 node가 여러 reference를 덮거나 여러 node가 같은 reference를 덮을 수 있다.++### 평균 node 수가 비슷해도 geometry 결과는 한 방향이 아니다++Adaptive는 FixedMatched보다 누적 retention이 Peg **+2.25pp**, Box **+1.54pp** 높다.+그러나 **프레임별 retention 차이의 평균**은 Peg **−1.16pp**, Box **−16.33pp**다.+Peg 121개 비교는 Adaptive 우세/동률/열세가 44/17/60,+Box observable 분모가 있는 47개 비교는 10/25/12였다.++이는 모순이 아니다. Micro 집계는 observable reference가 많은 frame에 더 큰 가중치를 준다.+Adaptive가 초기 큰 면적에 더 많은 node를 쓰는 방식은 누적 reference를 더 보존했지만,+일부 후반 작은 mask에서는 95점 고정보다 크게 잃었다. 특히 Box의 작은 분모 frame은+frame 평균��서 크게 반영된다. Frame 평균과 누적 비율을 서로 대체해 개선을 주장하지 않는다.++## 4. 일반 geometry 보존과 작은 관측의 실패++아래는 같은 물체의 **전체 observed X → Final F** 최근접 3D 거리다.+Contamination을 포함한 원본 support를 유지했다. Mean/p95는 모든 source point-frame의 pooled+거리이며, frame별 p95의 평균과 구분한다.++| 물체 / 조건 | Mean mm | p95 mm | Max mm | Within 3mm |+| --- | ---: | ---: | ---: | ---: |+| Peg Fixed256 | 3.425 | 7.019 | 12.625 | 45.63% |+| Peg Adaptive | 5.578 | 11.701 | 22.168 | 18.49% |+| Peg FixedMatched | 5.979 | 12.050 | 20.254 | 17.40% |+| Box Fixed256 | 7.175 | 16.277 | 24.840 | 15.63% |+| Box Adaptive | 12.850 | 22.244 | 40.762 | 4.41% |+| Box FixedMatched | 14.928 | 34.515 | 54.285 | 4.82% |++Fixed256 대비 Adaptive의 mean/p95 손실은 Peg **+2.153 / +4.682mm**,+Box **+5.675 / +5.967mm**다. FixedMatched 대비 mean/p95는 두 물체 모두 유리하지만+Peg max와 Box within-3mm는 불리하다. 일반 geometry가 일관되게 개선됐다고 판단하지 않는다.++| Candidate C → Priority P 거리 | Fixed256 mean / p95 / max mm | Adaptive | FixedMatched |+| --- | ---: | ---: | ---: |+| Peg | 1.910 / 5.286 / 14.345 | 4.638 / 16.919 / 33.630 | 4.764 / 14.012 / 26.448 |+| Box | 9.013 / 27.905 / 40.645 | 11.321 / 30.651 / 46.565 | 19.989 / 61.533 / 92.179 |++기존 ≤64px image component 내 within-3mm coverage는 Peg **50% → 0% → 0%**,+Box **38.15% → 17.65% → 21.51%**(Fixed256 / Adaptive / FixedMatched)다.+Peg의 이 분모는 단 2 point-frame, Box는 595 point-frame이므로 일반적인 작은 구조 보존율로+해석하지 않는다. Component-frame 수는 Peg 122 / Box 208이며, 후보가 있는데 P 또는 F가+전혀 없는 support component는 세 조건 모두 0이었다. 이 거친 component 진단은 같은 큰 mask+내부의 국소 누락을 감추므로, 거리·reference ID·overlay를 함께 보아야 한다.++기존 negative union의 Priority 수는 Fixed256 Peg 426 / Box 2,004,+Adaptive 173 / 560, FixedMatched 201 / 739다.+일반 Surface node는 negative ROI에 있다는 이유만으로 잘못 선택된 구조 node로 분류하지 않는다.+Box valid support 365,372 중 기존 negative union 350,610도 그대로 남겼다.+이 ROI 수치는 GT 진단이며 tracker를 수정하는 근거로 sampling에 피드백하지 않았다.++### 작은 면적과 원거리·가림·tracking의 해석++전체 valid 면적의 median 7,134px로 나눈 **진단용** 구간에서 Adaptive−Fixed256 frame 평균+retention 차이는 다음과 같다. 이 분할은 평가용이며 reference나 정책에 입력하지 않았다.++| 전체 mask 면적 구간 | Peg 차이 | Box 차이 |+| --- | ---: | ---: |+| ≤7,134px | −31.25pp (61 frame) | −31.31pp (observable 33 frame) |+| >7,134px | −36.05pp (60 frame) | −1.34pp (observable 14 frame) |++**Box 손실은 작은 면적 구간에 더 컸지만 Peg는 큰 면적에서도 큰 손실을 보였다.**+작은 mask일수록 항상 더 많이 잃는다는 단순 관계는 확인되지 않았다.+Source 73의 Peg는 90개 reference가 모두 관측 가능했지만 Fixed256의 90개 보존에서+Adaptive **21개(23.33%)**로 줄었다. 이때 전체 요청 49, Peg 할당 27점이며+FixedMatched는 57개(63.33%)를 보존했다. 관측 소실로 설명할 수 없는 sampling 손실이다.+Source 75/83/98의 Box에서는 각각 observable reference가 3/1/2개인 상황에서+Fixed256가 모두 보존한 것을 Adaptive가 하나도 남기지 못했다. 작은 분모도 함께 공개한다.++기존 depth/intrinsic으로 계산한 관측 median camera range는 Peg 0.190–0.403m,+Box 0.507–0.532m였다. Median range와 valid 면적의 Spearman 상관은 Peg **−0.665**,+Box **+0.024**다. Camera z-depth와 range는 구분해 JSON에 기록했다.+이는 시간적으로 연속된 한 episode의 기술 통계다. 물체 운동·viewpoint·부분 가림·tracker 오염이+함께 변하므로 원거리 하나의 인과 효과를 입증하지 못한다. 작은 mask가 단순 geometry라는+보장도 없으며, 깊이 보정 정책이나 GT mask 수정은 추가하지 않았다.++## 5. Temporal stability, 소실과 reference 영향++Adaptive의 연속 frame `ΔN`은 **−13…+3**이며, `|ΔN|`의 mean/median/p95/max는+**2.083 / 1 / 9.05 / 13개**였다. Fixed256와 FixedMatched의 전체 node 수 변화는 0이다.+가장 큰 감소는 source 15→16의 148→135점이다. Peg의 최악 retention 차이는 source 73에 있어,+가장 큰 budget 점프와 최악 손실이 같은 frame에 집중되지는 않았다.++| source / 관측 사건 | Adaptive 전체 N | Adaptive Peg / Box allocation |+| --- | ---: | ---: |+| 17, 첫 Box 소실 직전 | 124 | 106 / 18 |+| 18, Box support 0 | 119 | 119 / 0 |+| 26, 소실 마지막 frame | 103 | 103 / 0 |+| 27, Box 재관측 | 101 | 83 / 18 |+| 55, 두 번째 소실 직전 | 78 | 62 / 16 |+| 56, Box support 0 | 79 | 79 / 0 |+| 65, 소실 마지막 frame | 55 | 55 / 0 |+| 66, Box 재관측 | 52 | 35 / 17 |++Box support가 사라진 18–26, 56–65의 총 19프레임에서 Box 선택은 모든 조건에서 0이다.+재관측 즉시 Box node를 다시 할당하지만 전체 N은 Peg를 포함한 총면적에 따라 달라지므로+소실 직전 값이나 256으로 복귀한다는 뜻은 아니다. 이 19프레임의 Peg paired retention 손실은+평균 −50.21pp다. 남아 있는 물체의 geometry에도 예산 감소가 영향을 주었다.++현재 episode에서 양쪽 support가 동시에 0인 경우는 없었다. 이 경우의 빈 출력은 합성 테스트로+확인했다. Smoothing, hysteresis, 물리 point identity tracking은 구현하지 않았다.+Mask 축소나 빈 mask를 모두 실제 occlusion으로 단정하지 않는다.++초기 reference 23,445px는 이 episode의 큰 관측에 가깝다. 이후 총 valid 면적이 약 4천px까지+줄면서 요청 45점이 됐고, 총 minimum 제한은 한 번도 작동하지 않았다.+즉 minimum 위에서도 심한 geometry 손실이 발생했다. 최대 256 포화는 처음 3프레임만 보호했다.+이 결과를 보고 α/reference/minimum을 바꾸거나 추가 sweep하지 않았다.++## 6. Paired CPU latency++동일 macOS CPU process에서 evidence를 공유하고 조건 순서를 회전하며 3회 측정했다.+조건별 동일 선택은 alias로 재사용했다. 첫 frame의 Adaptive=Fixed256은 같은 warmup을 공유하고,+FixedMatched는 따로 warmup했다. 반복 간 모든 selection field·feature·count가 deterministic했다.+아래는 먼저 각 frame의 3회 median을 만든 뒤 121프레임에서 집계한 값이다.++| Sampling total ms | Fixed256 | Adaptive | FixedMatched |+| --- | ---: | ---: | ---: |+| 평균 | 4.453 | 2.425 | 2.190 |+| 중앙값 | 4.172 | 1.928 | 2.044 |+| p95 | 7.605 | 6.907 | 3.825 |++Adaptive의 sampling 절감은 평균 **2.028ms / 45.55%**, median **53.79%**, p95 **9.18%**다.+큰 support의 초기 frame에서는 256점 또는 큰 요청량을 유지해 tail 비용 감소가 작았다.+FixedMatched보다 Adaptive 평균 시간은 **10.72% 더 길었다**.+평균 node 수를 맞춘 것은 FPS의 실제 CPU 연산량까지 맞춘 것은 아니다.++| 평균 세부 시간 ms | Fixed256 | Adaptive | FixedMatched |+| --- | ---: | ---: | ---: |+| Candidate selection | 0.659 | 0.660 | 0.672 |+| Budget allocation | 0.048 | 0.049 | 0.049 |+| Priority FPS | 0.245 | 0.142 | 0.138 |+| Surface FPS | 3.438 | 1.525 | 1.275 |+| Gather/packaging 및 나머지 overhead 잔차 | 0.055 | 0.045 | 0.045 |++각 세부 timer도 frame별 median으로 따로 집계했으므로 그 합이 sampling total median과 정확히+일치할 필요는 없다. 원시 호출별로는 timer 합계와 잔차를 재검증했다.+잔차는 순수 gather 시간이 아니다. 기존 sampler의 결과 생성과 나머지 함수 overhead를 포함한다.++| 별도 비용 ms | Mean | Median | p95 | 범위 |+| --- | ---: | ---: | ---: | --- |+| Adaptive budget helper | 0.00348 | 0.00333 | 0.00463 | 이미 확보한 observed count와 고정 reference의 정수 계산·검증 |+| Valid support count scan | 0.05089 | 0.05158 | 0.05683 | 관문에서 현재 support를 실제로 세는 비용, frame당 한 번 |+| Raw 면적·제외량 진단 scan | 0.08774 | 0.08850 | 0.09608 | 진단 비용. Budget 함수에 사용하지 않음 |+| PCA5 evidence extraction | 14.366 | 12.992 | 26.344 | frame당 한 번. Geometry/normal/feature/pair 포함 |++Sampling total은 budget helper, 별도 support/raw scan, PCA5 extraction, GT, I/O, 그림 생성을+포함하지 않는다. 이미 count가 확보돼 있으면 Adaptive의 추가 직접 비용은 budget helper다.+그 mean을 sampling mean에 더하면 2.428ms이며, raw scan을 온라인 정책 필수 비용으로 더하지 않는다.+Support scan은 검증용 실제 계측을 별도 공개했으며, sampler 내부 allocation의 행 수 확인 비용과+동일한 것으로 다시 계상하지 않았다.++측정 호출은 Fixed256 363회, Adaptive 354회 + alias 9회,+FixedMatched 318회 + alias 45회다. Alias는 `executed=false`, `timings_ms=null`로 저장했다.+모든 frame 비교를 위한 effective 분포는 실제 owner 호출 시간을 참조하며, 실행하지 않은 FPS에+새 시간을 부여하지 않았다. 실행된 호출만의 분포도 latency JSON에 별도로 보존했다.++이 수치는 CPU 현재-observation sampling의 비용이다. Node 감소에 따른 실제 GNN latency,+BC 성능, Vision 전체 속도, end-to-end 20Hz는 검증하지 않았다. GPU/CUDA/MPS와 새로운+simulator backend 실행도 하지 않았다.++## 7. 테스트·재현·원본 보존++[tests.log](../../experiments/f68c59f210b5499dadc7e962c7f64492/tests.log)의 관련 테스트 **42/42 PASS**다.+기존 sampling/geometry/evaluation 테���트와 새 Adaptive 테스트 11개를 포함한다.+반올림 동률, 첫 양의 reference 고정, future/prefix 독립성, 빈/부족/overlap/invalid 관측,+minimum·capacity·structural cap, 256점 exact reproduction, 전체 feature alignment,+GT reference 변경 불변성, FixedMatched 동률, NaN/N/A, timing alias·집계를 확인했다.++저장 결과도 121프레임 전부 다시 읽어 source/pixel/XYZ/모든 feature 정렬, 중복·padding 없음,+capacity/minimum/priority, causal request, matched 총량, ΔN/ratio, reference 집합 관계,+timing 잔차·alias를 재검사했다. HTML의 상대경로 156개가 모두 실제 로컬 파일에 연결됐다.+정량 PNG 3개와 대표 overlay 6개를 만들었고 주요 그림·빈 Box·초기/후반 overlay를 직접 확인했다.+외부 CDN/framework/JS fetch 없이 `file://`로 표와 그림을 읽을 수 있는 정적 HTML이다.++재현 명령은 repository root의 기존 환경에서 다음과 같다. `--preservation-before`에는 실행 전+기존 파일 hash와 Git 상태를 담은 snapshot을 전달한다. 이번 snapshot도 새 run 안에 보존했다.+실제 재실행은 새 Logger UUID를 만들며 원본 run을 덮어쓰지 않는다.++```bash+WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03ab-mpl \+ .venv/bin/python -m unittest \+ visual.runtime.test.test_adaptive_node_budget \+ visual.runtime.test.test_sampling \+ visual.runtime.test.test_sampling_geometry \+ visual.runtime.test.test_sampling_evaluation -v++WANDB_MODE=disabled MPLCONFIGDIR=/tmp/task03ab-mpl \+ .venv/bin/python -m visual.runtime.test.run_adaptive_node_budget \+ --preservation-before experiments/f68c59f210b5499dadc7e962c7f64492/preservation_before.json \+ --tests-log experiments/f68c59f210b5499dadc7e962c7f64492/tests.log+```++공통 `ExperimentLogger`의 새 UUID, project `graph-recurrent-vla`, group `vision`,+`WANDB_MODE=disabled`의 local 기록을 재사용했다. Logger는 `finished` 상태다.+새 산출물만 기존 `link_output`/`register_existing_output`으로 연결했고 원본 sidecar는 바꾸지 않았다.+실행 Git commit은 `2e10a51736826aa980f2fe79a801eb6c9da8e288`, `git_dirty=true`다.+Commit만으로 복구할 수 없는 현재 source는 evaluated source snapshot과+[implementation diff](../../experiments/f68c59f210b5499dadc7e962c7f64492/implementation.patch)에 보존했다.+공통 logger/publisher 코드는 변경하지 않았다.++시작 시 기존 dirty/untracked 상태와 **1,226개 기존 파일**의 hash를 기록했고,+source·input·원본 Task03 artifact·sidecar의 변경/삭제는 **0개**였다.+Git stage/commit/reset, 외부 업로드, dependency 설치를 하지 않았다.++## 8. 원본 산출물과 판단 범위++[HTML](../../experiments/f68c59f210b5499dadc7e962c7f64492/adaptive_node_budget.html)에서 전체 frame+metrics·NPZ·PNG와 원본 Task03 dependency를 상대경로로 열 수 있다.++| 대표 source | Fixed / Adaptive / Matched 실제 N | 선택점 overlay | 원본 결과 NPZ |+| --- | --- | --- | --- |+| 0 | 256 / 256 / 95 | [PNG](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0000_overlay.png) | [NPZ](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0000_samples.npz) |+| 15 | 256 / 148 / 95 | [PNG](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0015_overlay.png) | [NPZ](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0015_samples.npz) |+| 18 | 256 / 119 / 95 | [PNG](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0018_overlay.png) | [NPZ](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0018_samples.npz) |+| 45 | 256 / 95 / 95 | [PNG](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0045_overlay.png) | [NPZ](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0045_samples.npz) |+| 80 | 256 / 57 / 95 | [PNG](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0080_overlay.png) | [NPZ](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0080_samples.npz) |+| 120 | 256 / 76 / 95 | [PNG](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0120_overlay.png) | [NPZ](../../experiments/f68c59f210b5499dadc7e962c7f64492/frames/f0120_samples.npz) |++[Budget time series](../../experiments/f68c59f210b5499dadc7e962c7f64492/plots/budget_timeseries.png),+[geometry·temporal 그림](../../experiments/f68c59f210b5499dadc7e962c7f64492/plots/preservation_temporal.png),+[latency·depth 그림](../../experiments/f68c59f210b5499dadc7e962c7f64492/plots/latency_depth.png),+[실행 로그](../../experiments/f68c59f210b5499dadc7e962c7f64492/execution.log),+[source/input 보존 snapshot](../../experiments/f68c59f210b5499dadc7e962c7f64492/preservation_before.json)을 함께 보관한다.+NPZ에는 공통 support/candidate, 조건별 source·XYZ·role·정렬 feature와 별도 `evaluation/` reference가 있다.++**완료한 것은 구현·테스트와 ep000 한 episode의 geometry/계산 비용 ablation이다.**+평균 node·sampling 시간 절감은 확인했지만 geometry 손실은 크며 최종 채택은 별도 판단이다.+Graph/GNN/BC 개선과 전체 realtime 성능은 측정하지 않았다.+Pixel-frame 통계와 연속 frame 비교는 독립 episode 일반화 근거가 아니다.++Peg+Box point budget은 상한이고 실제 N은 가변이며 robot node 3개는 별도다.+GNN 기본 feature에 RGB를 추가하지 않았다. Vision/Graph의 책임과 interface는 유지했다.+이번 빈 관측 출력은 현재-observation sampler의 결과이며 기존 마지막 geometry·내부 edge·+관측 EE pose를 유지하는 stale 정책의 폐기를 의미하지 않는다.+Stale와 현재 관측의 합산 budget, EE Tensor/edge/Graph 통합, 03-F 결합은 이번에 구현하지 않았다.++**요청된 실험·Markdown·HTML을 제출하고 여기서 중단한다.**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411"""Task 02-C offline CPU sweep. Run from repository root with WANDB_MODE=disabled.
GT is read by this evaluator only, after observation-only extraction. No changesto the production extractor, representation, tracker, sampling or graph modules."""import argparsefrom dataclasses import fieldsimport ctypes.utilimport globimport importlib.utilimport importlib.metadataimport jsonfrom pathlib import Pathimport platformimport shutilimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.patches import Patchimport numpy as npfrom scipy.sparse import csr_matrixfrom scipy.sparse.csgraph import maximum_bipartite_matchingfrom scipy.spatial import cKDTree
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.rgbd import PEG, BOX, iter_saved_rgbdfrom visual.runtime.test.normal_diagnostics import erode, dilate, endpoints, pose_rotation, rays, statsfrom visual.runtime.test.run_normal_comparison import real_truth, boundsfrom visual.runtime.test.run_normal_diagnostics import save_jsonfrom visual.runtime.test.structural_edges import METHODS, THRESHOLDS, compare
OBJECTS = {'peg': PEG, 'box': BOX}LABELS = {'baseline': 'A: baseline', 'fd2': 'B: FD 2px', 'pca5': 'C: PCA 5x5'}TOL_PX, TOL_M = 2., .003
def pcl_status(): return dict(status='NOT RUN', python_modules={m: importlib.util.find_spec(m) is not None for m in ('pcl', 'pclpy')}, libraries={m: ctypes.util.find_library(m) for m in ('pcl_common', 'pcl_features')}, headers=[p for root in ('/opt/homebrew/include', '/usr/local/include', '/usr/include') for p in glob.glob(root+'/pcl*/pcl/features/organized_edge_detection.h')], pkg_config=shutil.which('pkg-config'), installed_or_built=False, rgb_canny=False, reason='No usable PCL dependency on this host; no installation or binding attempted')
def raster_reference(mask, truth, intrinsic): vu = np.column_stack(np.nonzero(mask)) return vu[:, ::-1].astype(float), (rays(mask.shape, intrinsic)*truth['depth'][..., None])[mask]
def rim_reference(frame, gt, truth, legacy_region): """Physical line samples, visibility restricted by the unchanged Task02-A ROI.
At most one reference per rounded projected pixel. Samples must be within 1.5px of a GT-visible legacy rim surface AND within its 4mm physical gate. This is evaluation discretization, not sampling predicted structural points. """ if not legacy_region.any(): return np.empty((0, 2)), np.empty((0, 3)) s = frame.source_frame pose = gt['box_pose'][s] rot = pose_rotation(pose) centre = ((gt['box_hole_pose'][s, :3]-pose[:3]) @ rot)[1:] radius, half = float(gt['box_hole_radii']), float(gt['peg_half_sizes'][0]) segments = [] for axis, other, c, oc in ((1, 2, centre[0], centre[1]), (2, 1, centre[1], centre[0])): for sign in (-1, 1): p = np.zeros((2001, 3)); p[:, 0] = np.sign(truth['origin'][0])*half p[:, axis] = c+sign*radius p[:, other] = np.linspace(oc-radius, oc+radius, len(p)) segments.append(p) world_to_cv = np.linalg.inv(frame.cam2world) xyz = (np.concatenate(segments) @ rot.T+pose[:3]) @ world_to_cv[:3, :3].T+world_to_cv[:3, 3] xyz = xyz[xyz[:, 2] > 0] uv = xyz[:, :2]/xyz[:, 2:]*np.diag(frame.intrinsic)[:2]+frame.intrinsic[:2, 2]-.5 visible_uv, visible_xyz = raster_reference(legacy_region, truth, frame.intrinsic) distance, nearest = cKDTree(visible_uv).query(uv) keep = (distance <= 1.5) & (np.linalg.norm(xyz-visible_xyz[nearest], axis=1) <= .004) uv, xyz = uv[keep], xyz[keep] if not len(uv): return uv, xyz rounded = np.rint(uv).astype(int) # Choose the subpixel line point nearest its raster centre, deterministically. order = np.argsort(np.linalg.norm(uv-rounded, axis=1), kind='stable') _, unique = np.unique(rounded[order], axis=0, return_index=True) indices = order[unique] return uv[indices], xyz[indices]
class Matcher: """Whole observed support, no GT corridor restriction on predictions.
Tolerance matches require the SAME reference/prediction pair to satisfy both <=2px AND <=3mm. One-to-one maximum matching penalizes thick duplicate bands. Nearest 2D and nearest 3D errors are separately reported in both directions. """ def __init__(self, geometry, object_id, reference): self.support = np.flatnonzero(geometry.observed_mask(object_id)) vu = np.column_stack(np.unravel_index(self.support, geometry.valid_depth.shape)) self.uv, self.xyz = vu[:, ::-1], geometry.xyz.reshape(-1, 3)[self.support] self.ref_uv, self.ref_xyz = reference self.nref = len(self.ref_uv) self.near2 = np.full(len(vu), np.nan) self.near3 = self.near2.copy() if len(vu) and self.nref: self.near2 = cKDTree(self.ref_uv).query(self.uv)[0] self.near3 = cKDTree(self.ref_xyz).query(self.xyz)[0]*1000 matrix = cKDTree(self.uv).sparse_distance_matrix(cKDTree(self.ref_uv), TOL_PX, output_type='coo_matrix') ok = np.linalg.norm(self.xyz[matrix.row]-self.ref_xyz[matrix.col], axis=1) <= TOL_M self.adjacency = csr_matrix((np.ones(ok.sum(), bool), (matrix.row[ok], matrix.col[ok])), shape=(len(vu), self.nref)) else: self.adjacency = csr_matrix((len(vu), self.nref), dtype=bool)
def score(self, prediction, distances=False): choose = prediction.ravel()[self.support] adjacency = self.adjacency[choose] count = int(choose.sum()) tp = int(np.count_nonzero(adjacency.getnnz(axis=1))) hit = int(np.count_nonzero(adjacency.getnnz(axis=0))) one = int(np.count_nonzero(maximum_bipartite_matching(adjacency, perm_type='column') >= 0)) if count and self.nref else 0 row = dict(candidates=count, references=self.nref, matched_candidates=tp, covered_references=hit, one_to_one=one, candidates_without_visible_reference=count if not self.nref else 0) arrays = {} if distances: arrays = dict(candidate_to_gt_px=self.near2[choose], candidate_to_gt_mm=self.near3[choose]) arrays['gt_to_candidate_px'] = cKDTree(self.uv[choose]).query(self.ref_uv)[0] if count and self.nref else np.empty(0) arrays['gt_to_candidate_mm'] = cKDTree(self.xyz[choose]).query(self.ref_xyz)[0]*1000 if count and self.nref else np.empty(0) row['location'] = {k: stats(v) for k, v in arrays.items()} return row, arrays
def ratios(row): n, r = row['candidates'], row['references'] row.update(precision=row['matched_candidates']/n if n else None, recall=row['covered_references']/r if r else None, one_to_one_precision=row['one_to_one']/n if n else None, one_to_one_recall=row['one_to_one']/r if r else None, one_to_one_f1=2*row['one_to_one']/(n+r) if n+r else None) return row
class Pool: def __init__(self): self.items = {}
def add(self, key, row, arrays): item = self.items.setdefault(key, dict(counts={k: 0 for k in row if k != 'location'}, arrays={})) for k, v in row.items(): if k != 'location': item['counts'][k] += v for k, v in arrays.items(): item['arrays'].setdefault(k, []).append(v.astype(np.float32))
def summary(self): return {k: dict(**ratios(item['counts']), location={a: stats(np.concatenate(v)) for a, v in item['arrays'].items()}) for k, item in self.items.items()}
def negative_regions(regions, maps, reference, shape): # Exclude known physical structure neighbourhood before calling a boundary FP. raster = np.zeros(shape, bool) uv = np.rint(reference[0]).astype(int) inside = (uv[:, 0] >= 0) & (uv[:, 0] < shape[1]) & (uv[:, 1] >= 0) & (uv[:, 1] < shape[0]) uv = uv[inside]; raster[uv[:, 1], uv[:, 0]] = True away = ~dilate(raster, 3) result = {k: regions[k] & away for k in ('silhouette_2px', 'occlusion_2px', 'same_plane_tracker_cut_2px', 'invalid_depth_2px')} if 'robot_occlusion_2px' in regions: result['robot_occlusion_2px'] = regions['robot_occlusion_2px'] & away result['contamination'] = regions['contamination'] & away if 'plane_interior' in regions: result['plane_interior'] = regions['plane_interior'] & away return result
def comparison_plot(output, frame, evidence, regions, maps, references): union_mask = frame.masks[PEG] | frame.masks[BOX] views = [('Full image', None, (0, frame.depth.shape[1]-1, frame.depth.shape[0]-1, 0)), ('Peg', PEG, bounds(regions['peg']['gt_visible'], union_mask)), ('Box / physical hole entrance', BOX, bounds(regions['box']['hole_rim'], regions['box']['gt_visible'], 12))] colors = dict(orientation='#ff3939', depth='#ffba18', occluding='#d737ef', occluded='#29c5ff', invalid='#ffffff', mask='#67e535') fig, axes = plt.subplots(3, 4, figsize=(19, 13), constrained_layout=True) for row, (view, oid, extent) in enumerate(views): for col in range(4): ax = axes[row, col]; ax.imshow(frame.rgb) if col == 0: for name in OBJECTS: uv = references[name]['all'][0] ax.scatter(uv[:, 0], uv[:, 1], s=3, c='#ffff00', linewidths=0) for cause, color in (('occlusion', '#d737ef'), ('cut', '#67e535')): v, u = np.nonzero(maps[name][cause]); ax.scatter(u, v, s=3, c=color, linewidths=0) ax.set_title(view+' | GT only (yellow structure)') else: method = METHODS[col-1] for i in OBJECTS.values() if oid is None else (oid,): candidates = evidence[method][i].candidates(20) for cause, color in colors.items(): v, u = np.nonzero(candidates[cause]) if cause in ('depth', 'mask'): ax.scatter(u, v, s=14 if cause == 'depth' else 8, marker='s' if cause == 'depth' else 'o', facecolors='none', edgecolors=color, linewidths=.45) else: ax.scatter(u, v, s=3, c=color, linewidths=0) ax.set_title(LABELS[method]+' | angle >20 deg') ax.set_xlim(extent[:2]); ax.set_ylim(extent[2:]); ax.set_aspect('equal') ax.set_xlabel('source u (px)'); ax.set_ylabel('source v (px)') fig.legend(handles=[Patch(color=c, label=k) for k, c in colors.items()], loc='outside lower center', ncol=6) fig.suptitle(f'Source {frame.source_frame}: same crop / CV source pixels. Colours are diagnostic; causes overlap.\nNear/far depth order is potential occlusion only; mask/occlusion is not a structural label.') fig.savefig(output/f'f{frame.source_frame:04d}_comparison.png', dpi=135); plt.close(fig)
def sweep_plot(output, summary): fig, axes = plt.subplots(2, 3, figsize=(17, 10), constrained_layout=True) for method in METHODS: for channel, style in (('union', '-'), ('orientation', '--')): rows = [summary[f'{method}/{channel}/{t}/all'] for t in THRESHOLDS] axes[0, 0].plot([r['recall'] for r in rows], [r['precision'] for r in rows], style, marker='.', label=LABELS[method]+' '+channel) axes[0, 1].plot([r['one_to_one_recall'] for r in rows], [r['one_to_one_precision'] for r in rows], style, marker='.') rows = [summary[f'{method}/union/{t}/all'] for t in THRESHOLDS] axes[0, 2].plot(THRESHOLDS[:-1], [r['candidates'] for r in rows[:-1]], marker='.', label=LABELS[method]) for ax, key in zip(axes[1], ('peg_seam', 'box_rim', 'peg_plane')): if key == 'peg_plane': y = [summary[f'{method}/union/{t}/negative/peg/plane_interior']['rate'] for t in THRESHOLDS] else: y = [summary[f'{method}/union/{t}/{key}']['recall'] for t in THRESHOLDS] ax.plot(THRESHOLDS[:-1], y[:-1], marker='.', label=LABELS[method]); ax.set_title(key); ax.set_xlabel('angle threshold (deg)') axes[0, 0].set(xlabel='coverage / recall', ylabel='candidate precision', title='Whole support: <=2px AND <=3mm') axes[0, 1].set(xlabel='one-to-one recall', ylabel='one-to-one precision', title='Maximum one-to-one matching') axes[0, 2].set(xlabel='angle threshold (deg)', ylabel='candidates / 121 frames', title='Density (depth-only at 180 in JSON)') for ax in axes.flat: ax.grid(alpha=.25) axes[0, 0].legend(fontsize=8); axes[0, 2].legend(fontsize=8) fig.savefig(output/'tradeoffs.png', dpi=140); plt.close(fig)
def density_plot(output, density, shape): fig, axes = plt.subplots(2, 3, figsize=(14, 8), constrained_layout=True) vmax = max(max(v['grid_8x8'][i][j] for i in range(8) for j in range(8)) for k, v in density.items() if '/union/20/' in k) for row, name in enumerate(OBJECTS): for col, method in enumerate(METHODS): d = density[f'{method}/union/20/{name}']; ax = axes[row, col] im = ax.imshow(d['grid_8x8'], extent=(0, shape[1], shape[0], 0), vmin=0, vmax=vmax, cmap='magma') fraction = f'{d["fraction"]:.1%}' if d['fraction'] is not None else 'no observation' ax.set(title=f'{LABELS[method]} {name}: {fraction}', xlabel='source u (px)', ylabel='source v (px)') fig.colorbar(im, ax=axes, label='Candidate pixel-frames per image tile (8x8 grid); same scale') fig.savefig(output/'density.png', dpi=140); plt.close(fig)
def evaluate(episode_path, masks_path, output_root, camera='base_camera', selected=(0, 15, 45, 80, 120)): episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() with np.load(episode_path, allow_pickle=False) as archive: required = [f'{camera}/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed'] if set(required)-set(archive.files): raise ValueError('GT fields missing') gt = {k: archive[k] for k in required} with np.load(masks_path, allow_pickle=False) as archive: sources = archive['source_frame'] if not np.array_equal(sources, np.arange(len(gt[f'{camera}/seg']))): raise ValueError('Task02-C requires every episode frame exactly once in source order') tracker_meta = masks_path.with_name('tracking.json') if tracker_meta.exists(): track = json.loads(tracker_meta.read_text()) if track.get('camera', camera) != camera: raise ValueError('tracker camera mismatch') track_input = Path(track.get('input') or episode_path) if track_input.exists() and digests(track_input)[1] != digests(episode_path)[1]: raise ValueError('tracker episode mismatch') segmap_path = episode_path.with_name('segmentation_id_map.json') segmap = json.loads(segmap_path.read_text()) if segmap_path.exists() else {} robot_ids = [int(k) for k, v in segmap.items() if v.startswith('panda_')] config = dict(task='02-C', input=str(episode_path), masks=str(masks_path), camera=camera, input_sha256=digests(episode_path)[1], masks_sha256=digests(masks_path)[1], methods=METHODS, angle_thresholds_deg=THRESHOLDS, depth_gate_abs_m=.01, depth_gate_rel=.02, tolerance_px=TOL_PX, tolerance_m=TOL_M, pcl=pcl_status(), seed=int(gt['seed']), device='cpu', python=platform.python_version(), numpy=np.__version__, platform=platform.platform(), scipy=importlib.metadata.version('scipy'), matplotlib=matplotlib.__version__, rgb_canny=False, gt_detector_input=False, full_resolution=True, robot_segmentation_ids=robot_ids, segmentation_map_sha256=digests(segmap_path)[1] if segmap else None, selected_sources=selected, timing='warmup excluded; rotated order; both objects; shared XYZ charged to each; no I/O, GT, sweep or plotting', source_sha256={str(p.relative_to(REPO)): digests(p)[1] for p in [Path(__file__), Path(__file__).with_name('structural_edges.py'), REPO/'visual/runtime/geometry.py', Path(__file__).with_name('normal_estimators.py'), Path(__file__).with_name('normal_diagnostics.py'), Path(__file__).with_name('run_normal_comparison.py')]}) with ExperimentLogger(team='visual', config=config, seed=int(gt['seed']), model='task02c_structural_edges', job_type='evaluate') as logger: output = Path(output_root).resolve()/logger.run_id; output.mkdir(parents=True, exist_ok=False) print('Output:', output, flush=True) for source in config['source_sha256']: destination = output/'evaluated_source'/source destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(REPO/source, destination) pool, negative, records, density, legacy_rim = Pool(), {}, [], {}, {} iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) for index, frame in enumerate(iterator): if index == 0: compare(frame) # one warmup per method results, evidence = compare(frame, index) truths, regions, maps = real_truth(frame, results['baseline'], gt, camera) for name in OBJECTS: robot_occluder = (np.isin(gt[f'{camera}/seg'][frame.source_frame], robot_ids) & np.isfinite(truths[name]['depth']) & results['baseline'].geometry.valid_depth & (frame.depth < truths[name]['depth']-.0015)) regions[name]['robot_occlusion_2px'] = (dilate(endpoints(regions[name]['gt_visible'], robot_occluder), 2) & regions[name]['gt_visible']) references, matchers, negatives = {}, {}, {} record = dict(source_frame=frame.source_frame, methods={}, gt={}, observations={}) for name, oid in OBJECTS.items(): references[name] = {'seam': raster_reference(maps[name]['seam'], truths[name], frame.intrinsic)} if name == 'box': references[name]['rim'] = rim_reference(frame, gt, truths[name], regions[name]['hole_rim']) # Additional box plane control; fixed face-wise erosion, no new GT detector input. regions[name]['plane_interior'] = np.logical_or.reduce([erode(regions[name]['gt_visible'] & (truths[name]['face'] == f), 3) for f in range(6)]) regions[name]['plane_interior'] &= ~dilate(regions[name]['hole_rim'], 4) references[name]['all'] = tuple(np.concatenate([r[k] for r in references[name].values()]) for k in (0, 1)) _, unique = np.unique(np.rint(references[name]['all'][0]).astype(int), axis=0, return_index=True) references[name]['all'] = tuple(x[unique] for x in references[name]['all']) matchers[name] = {key: Matcher(results['baseline'].geometry, oid, ref) for key, ref in references[name].items()} negatives[name] = negative_regions(regions[name], maps[name], references[name]['all'], frame.depth.shape) record['gt'][name] = {k: len(v[0]) for k, v in references[name].items()} if name == 'box': record['gt'][name]['legacy_rim_band'] = int(regions[name]['hole_rim'].sum()) f = results['baseline'].objects[oid] record['observations'][name] = dict(mask=int(f.object_mask.sum()), points=int(f.valid_points.sum()), gt_visible=int(regions[name]['gt_visible'].sum()), contamination=int((f.valid_points & regions[name]['contamination']).sum()), legacy_rim_observed=int((f.valid_points & regions[name].get('hole_rim', np.zeros_like(f.valid_points))).sum())) for method in METHODS: record['methods'][method] = dict(timing_ms=results[method].timings_ms, thresholds={}) for threshold in THRESHOLDS: detail = {} for name, oid in OBJECTS.items(): candidates = evidence[method][oid].candidates(threshold) f = results[method].objects[oid] # Full-raster equivalence to the requested original union. expected = f.valid_points & (f.depth_discontinuity | (np.rad2deg(f.normal_variation_rad) > threshold)) if not np.array_equal(candidates['union'], expected): raise AssertionError('pair union differs from original feature maps') for channel in ('union', 'orientation'): prediction = candidates[channel] key = f'{method}/{channel}/{threshold}' for target, matcher in matchers[name].items(): row, arrays = matcher.score(prediction, distances=threshold in (10, 20, 30)) label = name+'_'+target if target != 'all' else 'all' pool.add(key+'/'+label, row, arrays) detail[name+'/'+target+'/'+channel] = row if name == 'box': lr = legacy_rim.setdefault(key, dict(gt_band=0, observed_band=0, detected_band=0)) rim = regions[name]['hole_rim'] lr['gt_band'] += int(rim.sum()); lr['observed_band'] += int((rim & f.valid_points).sum()) lr['detected_band'] += int((rim & prediction).sum()) for region, mask in negatives[name].items(): supported = mask & f.valid_points nr = negative.setdefault(key+'/negative/'+name+'/'+region, dict(points=0, candidates=0)) nr['points'] += int(supported.sum()); nr['candidates'] += int((supported & prediction).sum()) detail[name+'/negative/'+region+'/'+channel] = dict(points=int(supported.sum()), candidates=int((supported & prediction).sum())) v, u = np.nonzero(prediction) grid = np.histogram2d(v, u, bins=(8, 8), range=((0, frame.depth.shape[0]), (0, frame.depth.shape[1])))[0].astype(int) den = density.setdefault(key+'/'+name, dict(observed=0, candidates=0, grid_8x8=np.zeros((8, 8), int))) den['observed'] += int(f.valid_points.sum()); den['candidates'] += len(v); den['grid_8x8'] += grid if threshold == 20: detail[name+'/causes'] = {k: int(v.sum()) for k, v in candidates.items()} record['methods'][method]['thresholds'][str(threshold)] = detail if frame.source_frame in selected: comparison_plot(output, frame, evidence, regions, maps, references) # Every frame's pair evidence is preserved, not just selected plots. arrays = dict(source_frame=np.array(frame.source_frame), shape=np.array(frame.depth.shape), intrinsic=frame.intrinsic) for method in METHODS: for name, oid in OBJECTS.items(): pair = evidence[method][oid] for field in fields(pair): arrays[f'{method}/{name}/{field.name}'] = getattr(pair, field.name) if frame.source_frame in selected: arrays.update({f'{method}/{name}/candidate20/{k}': v for k, v in pair.candidates(20).items()}) if frame.source_frame in selected: for name in OBJECTS: arrays.update({f'evaluation/{name}/{k}': v for k, v in regions[name].items()}) for target, ref in references[name].items(): arrays[f'evaluation/{name}/{target}_uv'] = ref[0]; arrays[f'evaluation/{name}/{target}_xyz'] = ref[1] arrays['depth_m'] = frame.depth np.savez_compressed(output/f'f{frame.source_frame:04d}_pairs.npz', **arrays) records.append(record) if index % 10 == 0: print(f'Frames {index+1}/{len(sources)}', flush=True) summary = pool.summary() summary.update({k: dict(**v, rate=v['candidates']/v['points'] if v['points'] else None) for k, v in negative.items()}) density = {k: dict(observed=v['observed'], candidates=v['candidates'], grid_8x8=v['grid_8x8'].tolist(), fraction=v['candidates']/v['observed'] if v['observed'] else None) for k, v in density.items()} legacy_rim = {k: dict(**v, coverage=v['detected_band']/v['gt_band'] if v['gt_band'] else None) for k, v in legacy_rim.items()} latency = {m: {k: stats([r['methods'][m]['timing_ms'][k] for r in records]) for k in records[0]['methods'][m]['timing_ms']} for m in METHODS} data = dict(run_id=logger.run_id, config=config, evaluated_frames=len(records), git_commit=logger.metadata['git_commit'], git_dirty=logger.metadata['git_dirty'], summary=summary, density=density, legacy_rim=legacy_rim, latency_ms=latency, frames=records) save_json(output/'comparison.json', data) sweep_plot(output, summary) density_plot(output, density, frame.depth.shape) body = ''.join(f'<p><a href="{p.name}"><img src="{p.name}"></a></p>' for p in [output/'tradeoffs.png', output/'density.png']+[output/f'f{s:04d}_comparison.png' for s in selected]) (output/'comparison.html').write_text(f'''<!doctype html><html><meta charset="utf-8"><title>Task02-C</title><style>body{{font:15px system-ui;max-width:1800px;margin:24px auto}}img{{width:100%}}</style><h1>Task 02-C — structural edge candidate comparison</h1><p>Run {logger.run_id}; all {len(records)} frames; CPU only.<a href="comparison.json">Full sweep / counts / errors / latency / density / frame metrics</a>.</p><p>PCL: NOT RUN (absent). RGB Canny: disabled. GT never used by detectors. Union is a proposal, not a structural class.Whole-support precision uses <=2px AND <=3mm to visible physical references, without GT corridor filtering.One-to-one matching additionally penalizes thick bands. Errors to GT are conditional on references being visible;empty predictions still give zero recall. Curves sweep angle while preserving the original depth gate and normal support.Rim line samples use the unchanged visible physical rim ROI for visibility; legacy band coverage remains in JSON.No independent episode or final production threshold selection. Colours are debugging only; causes overlap.</p>{body}</html>''', encoding='utf-8') for p in sorted(p for p in output.rglob('*') if p.is_file()): logger.link_output(p, kind='metrics' if p.suffix == '.json' else 'trajectory' if p.suffix == '.npz' else 'reports') logger.log({m: summary[f'{m}/union/20/all'] for m in METHODS}, prefix='eval/task02c') logger.record(evaluated_frames=len(records), evaluation_device='cpu', gpu_executed=False, pcl_executed=False, dataset_sha256=config['input_sha256'], masks_sha256=config['masks_sha256']) return output
if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, default=REPO/'visual/data/step2/ep000.npz') parser.add_argument('--masks', type=Path, default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') parser.add_argument('--camera', default='base_camera') parser.add_argument('--out', type=Path, default=REPO/'visual/results/structural_edges') args = parser.parse_args() print(evaluate(args.input, args.masks, args.out, args.camera))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Fixed-view comparison plots; colours are debugging only, GT is evaluation only."""import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as npfrom visual.runtime.rgbd import PEG, BOXfrom visual.runtime.test.run_normal_comparison import boundsfrom visual.runtime.sampling import extract_candidates, SamplingConfig
COLORS = dict(candidate='#ff5d41',depth='#cc54e5',priority='#ffff00',surface='#00d9ff',gt='#ff65cc',mask='#69ff72')
def overlays(output, frame, contexts, samples, evidence): context = contexts union=frame.masks[PEG]|frame.masks[BOX] views=[('Full RGB',None,(0,frame.depth.shape[1]-1,frame.depth.shape[0]-1,0)), ('Peg visible seam',PEG,bounds(context['regions']['peg']['gt_visible'],union,8)), ('Box physical rim',BOX,bounds(context['regions']['box']['hole_rim'],context['regions']['box']['gt_visible'],12))] fig,axes=plt.subplots(3,6,figsize=(21,12),constrained_layout=True) for axs,(title,oid,extent) in zip(axes,views): for col,ax in enumerate(axs): ax.imshow(frame.rgb) for name,i in [('peg',PEG),('box',BOX)]: if oid is not None and oid!=i:continue m=frame.masks[i] if m.any() and not m.all(): ax.contour(m,[.5],colors=[COLORS['mask']],linewidths=.45) uv=context['references'][name][0] ax.scatter(uv[:,0],uv[:,1],s=14,c=COLORS['gt'],marker='+',linewidths=.5) if col==0: ax.set_title(title+' | GT reference + masks',fontsize=10) else: method='S'+str(col-1); sample=samples[method] candidates=extract_candidates(evidence[method],SamplingConfig(),method) for i in (PEG,BOX) if oid is None else (oid,): c=candidates[i]; h,w=frame.depth.shape for key,color,marker in [('orientation_candidate',COLORS['candidate'],'.'),('depth_only_candidate',COLORS['depth'],'s')]: # Depth evidence is shown independently in every method. v,u=np.unravel_index(c.flat_index[c.metadata[key]],frame.depth.shape) if key=='depth_only_candidate':ax.scatter(u,v,s=8,facecolors='none',edgecolors=color,marker=marker,linewidths=.3,alpha=.7) else:ax.scatter(u,v,s=2,c=color,marker=marker,alpha=.6) keep=np.ones(len(sample.points),bool) if oid is None else sample.object_id==oid for priority,color,marker in [(False,COLORS['surface'],'o'),(True,COLORS['priority'],'*')]: v,u=sample.pixels_vu[keep & (sample.priority_selected==priority)].T ax.scatter(u,v,s=14 if priority else 8,c=color,marker=marker,edgecolors='black',linewidths=.2) ax.set_title(f'{method} | priority={int((sample.priority_selected&keep).sum())} / FPS={int((~sample.priority_selected&keep).sum())}',fontsize=10) ax.set(xlim=extent[:2],ylim=extent[2:]);ax.set_aspect('equal');ax.axis('off') handles=[Line2D([],[],marker=m,color=c,ls='',label=k) for k,c,m in [ ('orientation candidate',COLORS['candidate'],'.'),('depth-only evidence',COLORS['depth'],'s'), ('priority selected',COLORS['priority'],'*'),('Surface FPS selected',COLORS['surface'],'o'), ('GT reference (eval only)',COLORS['gt'],'+'),('tracker mask',COLORS['mask'],'_')]] fig.legend(handles=handles,loc='outside lower center',ncol=6,fontsize=9) fig.suptitle(f'Source {frame.source_frame}: 256 total nodes, ratio .25, angle >20 deg, seed 0; identical crops\n' 'Depth is separate evidence; S4 permits at most 16 depth-only priority slots. Markers may overlap.') fig.savefig(output/f'f{frame.source_frame:04d}_overlay.png',dpi=140);plt.close(fig)
def clouds(output,frame,context,samples,evidence): fig=plt.figure(figsize=(21,11),layout='constrained') fig.set_constrained_layout_pads(h_pad=.18, w_pad=.04, hspace=.06, wspace=.02) for row,(name,oid) in enumerate([('peg',PEG),('box',BOX)]): cloud=context['surfaces'][name]['xyz'] # Identical per-object viewport, not input filtering. Full coordinates are saved. if len(cloud): lo,hi=np.percentile(cloud,[.5,99.5],axis=0); centre=(lo+hi)/2 radius=max(float(np.max(hi-lo))/2,.005) else:centre=np.array([0,0,.3]);radius=.05 for col in range(6): ax=fig.add_subplot(2,6,row*6+col+1,projection='3d') if len(cloud):ax.scatter(*cloud.T,s=1.2 if col==0 else .4,c='#475566' if col==0 else '#999999',alpha=.85 if col==0 else .18,rasterized=True) if col: method='S'+str(col-1);sample=samples[method];keep=sample.object_id==oid for priority,color in [(False,'#008cbd'),(True,'#ff9b00')]: pts=sample.points[keep&(sample.priority_selected==priority)] ax.scatter(*pts.T,s=9 if priority else 5,c=color,depthshade=False) title=f'{name} {method}: {int(keep.sum())} selected' else:title=f'{name}: {len(cloud)} observed' if len(cloud): clipped=int((np.abs(cloud-centre)>radius).any(axis=1).sum()) title+=f'\nviewport excludes {clipped} points' ax.set(xlim=(centre[0]-radius,centre[0]+radius),ylim=(centre[1]-radius,centre[1]+radius),zlim=(centre[2]-radius,centre[2]+radius)) ax.view_init(elev=-65,azim=-85);ax.set_box_aspect((1,1,1));ax.set_title(title,fontsize=9,pad=12) ax.set_xlabel('CV X (m)',fontsize=7,labelpad=0);ax.set_ylabel('CV Y (m)',fontsize=7,labelpad=0);ax.set_zlabel('CV Z (m)',fontsize=7,labelpad=0) ax.tick_params(labelsize=6) fig.suptitle(f'Source {frame.source_frame}: gray=before, blue=Surface FPS, orange=priority; same per-object axes\n' 'Viewport uses observed .5/99.5 percentiles only for display; metrics and sampling retain every valid point. No GT points in these clouds.') fig.savefig(output/f'f{frame.source_frame:04d}_clouds.png',dpi=140);plt.close(fig)
def quantitative(output,summary,conditions): def get(method,n=256,r=.25,t=20,s=0): return summary[next(k for k,v in conditions.items() if v==dict(method=method,num_points=n,structural_ratio=0. if method=='S0' else r,orientation_threshold_deg=t,seed=s))] fig,axes=plt.subplots(2,3,figsize=(17,9),constrained_layout=True) for method in ('S0','S1','S2','S3','S4'): for ax,name in zip(axes[0,:2],('peg','box')): values=[get(method,n=n)['objects'][name]['structural']['2px_3mm']['sampling_retention'] for n in (64,128,256,512)] ax.plot([64,128,256,512],values,'o-',label=method) ax.set(title=name+' structure retained / tracker-observed',xlabel='Total point budget',ylabel='Joint coverage retention') ratios=[0.,.125,.25,.5] for name,ls in [('peg','-'),('box','--')]: axes[0,2].plot(ratios,[get(method,r=r)['objects'][name]['structural']['2px_3mm']['sampling_retention'] for r in ratios],ls,marker='.',label=method+' '+name) axes[1,0].plot(ratios,[get(method,r=r)['objects'][name]['surface']['all']['distance_mm']['p95'] for r in ratios],ls,marker='.',label=method+' '+name) row=get(method) total_priority=sum(v['counts']['priority'] for v in row['objects'].values()) fp=sum(v['negative']['known_negative_union']['priority'] for v in row['objects'].values()) axes[1,1].bar(method,fp/sum(v['counts']['selected'] for v in row['objects'].values())) axes[1,2].bar(method,row['timings_ms']['sampling_total']['p95']) axes[0,2].set(title='Ratio vs structure retention',xlabel='Structural ratio',ylabel='Retention') axes[1,0].set(title='Ratio vs all-observed surface p95',xlabel='Structural ratio',ylabel='Source to sampled distance (mm)') axes[1,1].set(title='Known-negative priority slots / all selected',ylabel='Fraction (overlapping ROIs unioned)') axes[1,2].set(title='Sampling latency at 256 nodes',ylabel='CPU p95 ms (no GT/I/O/plots)') for ax in axes.flat:ax.grid(alpha=.2) for ax in axes[0]:ax.legend(fontsize=7,ncol=2) axes[1,0].legend(fontsize=7,ncol=2) fig.savefig(output/'tradeoffs.png',dpi=150);plt.close(fig) fig,axes=plt.subplots(1,3,figsize=(16,4.5),constrained_layout=True) for method in ('S1','S2','S3','S4'): for ax,name in zip(axes[:2],('peg','box')): ax.plot([10,20,30,40],[get(method,t=t)['objects'][name]['structural']['2px_3mm']['sampling_retention'] for t in (10,20,30,40)],'o-',label=method) ax.set(title=name+' threshold diagnostic',xlabel='Angle threshold (deg)',ylabel='Retention') for name,ls in [('peg','-'),('box','--')]: vals=[get(method,s=s)['objects'][name]['structural']['2px_3mm']['sampling_retention'] for s in (0,1,2)] axes[2].plot([0,1,2],vals,ls,marker='.',label=method+' '+name) axes[2].set(title='Three FPS seeds at 256/.25/20',xlabel='FPS seed',ylabel='Retention') for ax in axes:ax.grid(alpha=.2);ax.legend(fontsize=7,ncol=2) fig.savefig(output/'sensitivity.png',dpi=150);plt.close(fig)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296{ "artifacts": [ { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/68383ee1b98ecbf9f7dd2d65b499e7c9dd11188195f55d4aed89bc36dea5621e/metrics.json", "sha256": "68383ee1b98ecbf9f7dd2d65b499e7c9dd11188195f55d4aed89bc36dea5621e", "size": 434 }, { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/abfa92e4b11dfa7aca06b7ec00edec04bd109ce66016943eef0bdf1ac9ef957b/adaptive_node_budget.json", "sha256": "abfa92e4b11dfa7aca06b7ec00edec04bd109ce66016943eef0bdf1ac9ef957b", "size": 130083 }, { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/03ad42a3d0690b248d45f7c8bf7a1e0b5e78a216b959a0a1a6e19afe89e644db/frame_metrics.json", "sha256": "03ad42a3d0690b248d45f7c8bf7a1e0b5e78a216b959a0a1a6e19afe89e644db", "size": 44649989 }, { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/725de8bb396a97bc5de7127adbd02c0c4e814420d3e54f931e49625ac20b437f/latency.json", "sha256": "725de8bb396a97bc5de7127adbd02c0c4e814420d3e54f931e49625ac20b437f", "size": 611016 }, { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/eb0adba87fb5be06430941687f23d712389a1229525a6d25518181744093a712/preservation_before.json", "sha256": "eb0adba87fb5be06430941687f23d712389a1229525a6d25518181744093a712", "size": 166461 }, { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/6f3cdc53d79413f85fcc2f9289fc9f314d2ed28d42ac2c9aadd2ba85fe1af37c/verification.json", "sha256": "6f3cdc53d79413f85fcc2f9289fc9f314d2ed28d42ac2c9aadd2ba85fe1af37c", "size": 34856 }, { "kind": "metrics", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/3170812df18b2b7df42f3b521e5f028104d4dc6144bb89e0e37b22f9f621ec14/analysis.json", "sha256": "3170812df18b2b7df42f3b521e5f028104d4dc6144bb89e0e37b22f9f621ec14", "size": 11825 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8269602147f2255e8aacb1ac62f20bcd02159711bf464b0b812bfe2e78fd10ce/adaptive_node_budget.html", "sha256": "8269602147f2255e8aacb1ac62f20bcd02159711bf464b0b812bfe2e78fd10ce", "size": 25167 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.py", "sha256": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "size": 4125 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.py", "sha256": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "size": 11385 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e/normal_estimators.py", "sha256": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "size": 6522 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.py", "sha256": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "size": 13402 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164/rgbd.py", "sha256": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "size": 8193 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.py", "sha256": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "size": 14001 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc/normal_diagnostics.py", "sha256": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "size": 14687 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9/run_adaptive_node_budget.py", "sha256": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "size": 47522 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b/run_normal_comparison.py", "sha256": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "size": 28566 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.py", "sha256": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "size": 31358 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.py", "sha256": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "size": 20175 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081/run_sampling.py", "sha256": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "size": 15131 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe/run_structural_edges.py", "sha256": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "size": 28118 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.py", "sha256": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "size": 15611 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223/sampling_plots.py", "sha256": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "size": 9243 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189/test_adaptive_node_budget.py", "sha256": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "size": 9722 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.py", "sha256": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "size": 13031 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.py", "sha256": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "size": 15253 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031/test_sampling_geometry.py", "sha256": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "size": 2396 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/623718ac7c7715adf6235f9a634496660e299d79185d1be17e3391fc447b2749/f0000_overlay.png", "sha256": "623718ac7c7715adf6235f9a634496660e299d79185d1be17e3391fc447b2749", "size": 1154923 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2aabb94be317001751f0ff6b1465dfe21b4b022619f1b85ea93bf58f6c49991a/f0015_overlay.png", "sha256": "2aabb94be317001751f0ff6b1465dfe21b4b022619f1b85ea93bf58f6c49991a", "size": 1184628 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36561474573076ee17f2ee639eda9bf409eb1571d02502a313aac06556eb916a/f0018_overlay.png", "sha256": "36561474573076ee17f2ee639eda9bf409eb1571d02502a313aac06556eb916a", "size": 1780672 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/1033399dea794928598c433dd74c43424b714d2a8d82ce051cd5f32319e52663/f0045_overlay.png", "sha256": "1033399dea794928598c433dd74c43424b714d2a8d82ce051cd5f32319e52663", "size": 525909 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fe9ddb73b2487529bec08235b79107b3e542036c1c2ed3a75cf21157f855d4e0/f0080_overlay.png", "sha256": "fe9ddb73b2487529bec08235b79107b3e542036c1c2ed3a75cf21157f855d4e0", "size": 327810 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a3ed390c821e53b3ef181025d3f8dc84fa7fed86f35cb2c695e30557124bb91a/f0120_overlay.png", "sha256": "a3ed390c821e53b3ef181025d3f8dc84fa7fed86f35cb2c695e30557124bb91a", "size": 308621 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dea26841465aa6959e4e07f09d6e407d45108112c001a5e57e2ffb67cf019867/implementation.patch", "sha256": "dea26841465aa6959e4e07f09d6e407d45108112c001a5e57e2ffb67cf019867", "size": 86545 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/f903d46f913aec28e967da93017980784f97ae9701a874e1d815b63c3fbb7c92/budget_timeseries.png", "sha256": "f903d46f913aec28e967da93017980784f97ae9701a874e1d815b63c3fbb7c92", "size": 282247 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d743c6d0dcffbf1928434f522a58a9eb3eeea29e195680d81ffe0d7e61dd157e/latency_depth.png", "sha256": "d743c6d0dcffbf1928434f522a58a9eb3eeea29e195680d81ffe0d7e61dd157e", "size": 205244 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/ea0cf309e75b8c90b1dcc5054db7dfe3db8653dabd248ab13ad177a259c3fa7e/preservation_temporal.png", "sha256": "ea0cf309e75b8c90b1dcc5054db7dfe3db8653dabd248ab13ad177a259c3fa7e", "size": 340841 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/105fac262d8756896c72f9708632d0e259a45a727e6a446566a58f4de89a628a/tests.log", "sha256": "105fac262d8756896c72f9708632d0e259a45a727e6a446566a58f4de89a628a", "size": 7908 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/0dce4af6f35bbad39f1c86a5cc8772082dcc3b5568182ac7849b0e045df17b98/execution.log", "sha256": "0dce4af6f35bbad39f1c86a5cc8772082dcc3b5568182ac7849b0e045df17b98", "size": 1406 }, { "kind": "reports", "path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b/report-67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b.zip", "sha256": "67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b", "size": 126444483 } ], "config_path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/config/937bd74f8b4c75bc2f57a7281c25b32c475dc0119549647cb1bb5ce4211a6895/config.yaml", "environment": null, "episode_metadata_paths": [], "git_commit": "2e10a51736826aa980f2fe79a801eb6c9da8e288", "git_dirty": true, "metrics_path": "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/68383ee1b98ecbf9f7dd2d65b499e7c9dd11188195f55d4aed89bc36dea5621e/metrics.json", "model_name": "task03ab_adaptive_node_budget", "random_seed": 0, "report_paths": [ "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8269602147f2255e8aacb1ac62f20bcd02159711bf464b0b812bfe2e78fd10ce/adaptive_node_budget.html", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e/normal_estimators.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164/rgbd.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc/normal_diagnostics.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9/run_adaptive_node_budget.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b/run_normal_comparison.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081/run_sampling.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe/run_structural_edges.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223/sampling_plots.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189/test_adaptive_node_budget.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031/test_sampling_geometry.py", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/623718ac7c7715adf6235f9a634496660e299d79185d1be17e3391fc447b2749/f0000_overlay.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2aabb94be317001751f0ff6b1465dfe21b4b022619f1b85ea93bf58f6c49991a/f0015_overlay.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36561474573076ee17f2ee639eda9bf409eb1571d02502a313aac06556eb916a/f0018_overlay.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/1033399dea794928598c433dd74c43424b714d2a8d82ce051cd5f32319e52663/f0045_overlay.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fe9ddb73b2487529bec08235b79107b3e542036c1c2ed3a75cf21157f855d4e0/f0080_overlay.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a3ed390c821e53b3ef181025d3f8dc84fa7fed86f35cb2c695e30557124bb91a/f0120_overlay.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dea26841465aa6959e4e07f09d6e407d45108112c001a5e57e2ffb67cf019867/implementation.patch", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/f903d46f913aec28e967da93017980784f97ae9701a874e1d815b63c3fbb7c92/budget_timeseries.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d743c6d0dcffbf1928434f522a58a9eb3eeea29e195680d81ffe0d7e61dd157e/latency_depth.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/ea0cf309e75b8c90b1dcc5054db7dfe3db8653dabd248ab13ad177a259c3fa7e/preservation_temporal.png", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/105fac262d8756896c72f9708632d0e259a45a727e6a446566a58f4de89a628a/tests.log", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/0dce4af6f35bbad39f1c86a5cc8772082dcc3b5568182ac7849b0e045df17b98/execution.log", "visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b/report-67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b.zip" ], "run_id": "f68c59f210b5499dadc7e962c7f64492", "schema_version": 1, "selection": [ "metrics", "reports" ], "task": null, "team": "visual", "wandb_run_id": "f68c59f210b5499dadc7e962c7f64492"}.gitattributes+1
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/config/937bd74f8b4c75bc2f57a7281c25b32c475dc0119549647cb1bb5ce4211a6895/config.yamlAdded+44
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/03ad42a3d0690b248d45f7c8bf7a1e0b5e78a216b959a0a1a6e19afe89e644db/frame_metrics.jsonAdded+3
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/3170812df18b2b7df42f3b521e5f028104d4dc6144bb89e0e37b22f9f621ec14/analysis.jsonAdded+476
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/68383ee1b98ecbf9f7dd2d65b499e7c9dd11188195f55d4aed89bc36dea5621e/metrics.jsonAdded+14
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/6f3cdc53d79413f85fcc2f9289fc9f314d2ed28d42ac2c9aadd2ba85fe1af37c/verification.jsonAdded+1130
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/725de8bb396a97bc5de7127adbd02c0c4e814420d3e54f931e49625ac20b437f/latency.jsonAdded
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/abfa92e4b11dfa7aca06b7ec00edec04bd109ce66016943eef0bdf1ac9ef957b/adaptive_node_budget.jsonAdded
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/metrics/eb0adba87fb5be06430941687f23d712389a1229525a6d25518181744093a712/preservation_before.jsonAdded
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/0dce4af6f35bbad39f1c86a5cc8772082dcc3b5568182ac7849b0e045df17b98/execution.logAdded+21
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/1033399dea794928598c433dd74c43424b714d2a8d82ce051cd5f32319e52663/f0045_overlay.pngAdded

Large File Pointer Details
- SHA256: 1033399dea794928598c433dd74c43424b714d2a8d82ce051cd5f32319e52663
- Pointer size: 131 Bytes
- Size of remote file: 526 kB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/105fac262d8756896c72f9708632d0e259a45a727e6a446566a58f4de89a628a/tests.logAdded+52
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2aabb94be317001751f0ff6b1465dfe21b4b022619f1b85ea93bf58f6c49991a/f0015_overlay.pngAdded

Large File Pointer Details
- SHA256: 2aabb94be317001751f0ff6b1465dfe21b4b022619f1b85ea93bf58f6c49991a
- Pointer size: 132 Bytes
- Size of remote file: 1.18 MB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.pyAdded+81
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36561474573076ee17f2ee639eda9bf409eb1571d02502a313aac06556eb916a/f0018_overlay.pngAdded

Large File Pointer Details
- SHA256: 36561474573076ee17f2ee639eda9bf409eb1571d02502a313aac06556eb916a
- Pointer size: 132 Bytes
- Size of remote file: 1.78 MB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.pyAdded+255
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9/run_adaptive_node_budget.pyAdded+745
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.pyAdded+266
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/623718ac7c7715adf6235f9a634496660e299d79185d1be17e3391fc447b2749/f0000_overlay.pngAdded

Large File Pointer Details
- SHA256: 623718ac7c7715adf6235f9a634496660e299d79185d1be17e3391fc447b2749
- Pointer size: 132 Bytes
- Size of remote file: 1.15 MB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b/report-67fd988224d72d3d86741b5e06ae3136d31dd38d35bf6244072accab5fe6eb0b.zipAdded+3
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.pyAdded+475
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.pyAdded+258
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8269602147f2255e8aacb1ac62f20bcd02159711bf464b0b812bfe2e78fd10ce/adaptive_node_budget.htmlAdded+90
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.pyAdded+206
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.pyAdded+247
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a3ed390c821e53b3ef181025d3f8dc84fa7fed86f35cb2c695e30557124bb91a/f0120_overlay.pngAdded

Large File Pointer Details
- SHA256: a3ed390c821e53b3ef181025d3f8dc84fa7fed86f35cb2c695e30557124bb91a
- Pointer size: 131 Bytes
- Size of remote file: 309 kB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031/test_sampling_geometry.pyAdded+43
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b/run_normal_comparison.pyAdded+453
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164/rgbd.pyAdded+202
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e/normal_estimators.pyAdded+130
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc/normal_diagnostics.pyAdded+303
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d743c6d0dcffbf1928434f522a58a9eb3eeea29e195680d81ffe0d7e61dd157e/latency_depth.pngAdded

Large File Pointer Details
- SHA256: d743c6d0dcffbf1928434f522a58a9eb3eeea29e195680d81ffe0d7e61dd157e
- Pointer size: 131 Bytes
- Size of remote file: 205 kB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189/test_adaptive_node_budget.pyAdded+182
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b/sampling_evaluation.pyAdded+248
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081/run_sampling.pyAdded+203
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/dea26841465aa6959e4e07f09d6e407d45108112c001a5e57e2ffb67cf019867/implementation.patchAdded+1343
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/ea0cf309e75b8c90b1dcc5054db7dfe3db8653dabd248ab13ad177a259c3fa7e/preservation_temporal.pngAdded

Large File Pointer Details
- SHA256: ea0cf309e75b8c90b1dcc5054db7dfe3db8653dabd248ab13ad177a259c3fa7e
- Pointer size: 131 Bytes
- Size of remote file: 341 kB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe/run_structural_edges.pyAdded+411
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/f903d46f913aec28e967da93017980784f97ae9701a874e1d815b63c3fbb7c92/budget_timeseries.pngAdded

Large File Pointer Details
- SHA256: f903d46f913aec28e967da93017980784f97ae9701a874e1d815b63c3fbb7c92
- Pointer size: 131 Bytes
- Size of remote file: 282 kB
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223/sampling_plots.pyAdded+126
visual/f68c59f210b5499dadc7e962c7f64492/artifacts/reports/fe9ddb73b2487529bec08235b79107b3e542036c1c2ed3a75cf21157f855d4e0/f0080_overlay.pngAdded

Large File Pointer Details
- SHA256: fe9ddb73b2487529bec08235b79107b3e542036c1c2ed3a75cf21157f855d4e0
- Pointer size: 131 Bytes
- Size of remote file: 328 kB
visual/f68c59f210b5499dadc7e962c7f64492/manifests/c4b3bc965a4e5a872aae8d5f40f1fe305fdc6eeb05e52e3e6eb3c2720bdf1c1c/manifest.jsonAdded+296