Publish experiment 7f657cf88baf4f1f89e594252e243e1c (rollouts)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/config/1088901223b936b83da80f8770bd43b1e6b1de9b345776ee42a59a1894d3f044/config.yamlAdded+97
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/metrics/2d3d14deeb565bc7d762f21e103cfdf31bbab43c3235673b4b61d770135f29ab/metrics.jsonAdded+56
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522/tracking.pyAdded+93
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f/experiment_artifacts.pyAdded+470
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a/benchmark_pca_cuda.pyAdded+92
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/08503679a20063b8b8b9d46bd17ad88b4908daaea345ca850a26659a8c411917/html_preview.pngAdded
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/1233cefa7e4998f15a912330c606c2ac042d7f18125544feebe734b3bcd7b09d/tests.logAdded+63
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/12e91248337a3e8c23b01c88862e396073e58ac713dfe67c63933bfa1b338f2e/tests_final.logAdded+17
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/156ab94c6115890fb82fcbe8f77af4bd52909683775e9285bc289b3f3202eed3/peg_structural_zoom.pngAdded
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/15f32b8c1eff70d55395c515b82c50ee9724aadb16b126b1a925d59cb5e75ef5/browser_render.logAdded+10
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/17d69c52d2d467b5d86030c37b0480b7a55696ca9fb5da217567ea416580ab23/implementation.patchAdded
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252/initialization.pyAdded+77
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866/test_geometry_evaluation.pyAdded+82
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3/run_tracking.pyAdded+254
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diffAdded+259
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb/benchmark_pca_streaming.pyAdded+146
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.pyAdded+81
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/34e0643471303d8f788f977f0bad7ae4829239c93e6c0af97ddbfe0ccc916b51/test_priority_fps_metric_control.pyAdded+154
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.pyAdded+255
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a/run_rgbd.pyAdded+445
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692/normal_estimators.pyAdded+2
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b/grounding.pyAdded+90
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890/pca_optimized.pyAdded+2
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/406a4b17e370b21c3edef72a1fb3c920ec92d9d8f9c9ef7ef9e410959a84bce2/spatial_xz.pngAdded
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/406d1d9ffbf439a5e39ed59c61b6c16203c325311c989f0c6bc39d8689a5a38c/verification.jsonAdded+212
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b/run_pca_optimization.pyAdded+206
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.pyAdded+266
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942/test_rgbd_evaluation.pyAdded+160
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/59431ef2427510990adc4e994238de3552a0ff723905c6795b5cd9bae8a778a9/priority_fps_metric_control.npzAdded+3
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a/test_priority_fps_trace.pyAdded+64
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4/test_normal_diagnostics.pyAdded+111
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.pyAdded+475
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692/pca_triton.pyAdded+173
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645/test_priority_fps_seed_control.pyAdded+244
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482/pca_torch.pyAdded+150
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/6c5e2373431ec7c7e390a7f77baa963ab2d649c2361b28c0f1553a542e20ac34/run_priority_fps_metric_control.pyAdded+833
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/6e6b1cb6a837013c19f75919e0bbb9490607e5eb244a85e1e1d3b68a060807b8/priority_fps_metric_control.htmlAdded+36
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/72c564d7cbb3d927d7cc1eec058c4c8c3dac68163212839364e52ba70b77037e/browser_verification.jsonAdded+47
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45/experiment_logger.pyAdded+237
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.pyAdded+258
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/81df499127fcdcddff89fefdccaa0a86f3b126c4c826b527d0ba1d41784659dc/browser_image_check.htmlAdded+43
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.pyAdded+206
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d/run_grounding.pyAdded+223
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/88fed1fc274039a5f6506d928639a1ba4038702c784e3e6d714b13f86b7b309f/coverage_surface_tradeoff.pngAdded
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0/test_initialization.pyAdded+38
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.pyAdded+247
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/91f3709ef38aae7fd17c70a862ad58e397fc438b89933cb1bc8371becce007e9/box_line_node_spacing.pngAdded
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565/test_priority_fps_metric_control.pyAdded+163
- visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1/test_pca_optimized.pyAdded+148
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697{ "budgets": { "box": 127, "peg": 129 }, "device": "cpu", "episode": "ep000", "frame": 0, "gpu_executed": false, "gt_selection_input": false, "input_sha256": { "experiments/aa5d71078e0841fd886b5026d6030ebc/priority_fps_trace.json": "330f451d1424ec05d237070443cd898f5f5b4f6118a1132cfcb06184075577e0", "experiments/d3f14ee494894daabb8ba2fab8e1b00c/diagnostic.json": "2a0346704763e2a5aca9ef3d52913699ced651501b031a8b1a49c57e6dcdfcff", "experiments/f36f1e9e2bb64866b8d6c792db158635/priority_fps_seed_control.json": "11d49e29ff4dda86fc1d0d51227251f53d49f40adfff21b775efdca45daa4927", "visual/data/step2/ep000.npz": "22ad72d776057da9ed5f85014cba47b4603e421623f29763c88edb159a5087ba", "visual/results/normal_comparison/4b1c377ae2044344a4f596b249627d89/f0000.npz": "801799c9ef1fefb464e0d24b244ab37ca341ea4715a214448406aa7aaf3217d2", "visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/f0000.npz": "62f4fe9782cc1d6cd1aa737491999255f7286b22f2a589d9a3152c440538df93", "visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/geometry.json": "6d93c76efa582ecadf2acbb3b6d0b9ae829179cc3e915be5ccc51cbec46fa846", "visual/results/runtime_tracking/ep000/masks.npz": "6bf9555a9c97c83a09d9733e582e9c4b9509f95e9dd06854ba05d3ac25fb7042", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json": "a88035aa821b879f1e6b87cf5b477af13f0d5858568ca0efa7c26c364894e94c", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_metrics.json": "6df34b94fa8e513d8872c3259bfe5a3d60b5718875b80d1715e5f8b6522ebbe8", "visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz": "9f6d46356212bc43bd29ceb6df34c1a96ea70b3879f0bb4da2c6ccae535dd058", "visual/results/structural_edges/b622e76deceb419ab9c5aa80a8f8280c/f0000_pairs.npz": "cb2320d63ed533270b1623e9128399514c51774f0471b4a7a5adbf71ded1d6f4" }, "lambdas": [ 1.0, 0.25, 0.0 ], "methods": { "S2": "fd2", "S3": "pca5" }, "metric": "dx^2+dy^2+lambda*dz^2 (Priority only)", "num_points": 256, "numpy": "2.4.6", "priority_count": 32, "python": "3.11.13", "seed": 0, "simulator_executed": false, "source_run_id": "2551448b0fae4c6bbce3caf48774275f", "source_sha256": { "utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "visual/runtime/test/run_priority_fps_metric_control.py": "6c5e2373431ec7c7e390a7f77baa963ab2d649c2361b28c0f1553a542e20ac34", "visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "visual/runtime/test/test_priority_fps_metric_control.py": "34e0643471303d8f788f977f0bad7ae4829239c93e6c0af97ddbfe0ccc916b51", "visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522" }, "structural_ratio": 0.25, "surface_metric": "original 3D Euclidean", "task": "03-E", "threshold_deg": 20}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556[ { "metrics": { "eval/task03e/S2/box/0.0/final_refs": 20, "eval/task03e/S2/box/0.0/priority_refs": 17, "eval/task03e/S2/box/0.0/surface_mean_mm": 12.018814253629463, "eval/task03e/S2/box/0.0/surface_p95_mm": 20.210218110653702, "eval/task03e/S2/box/0.25/final_refs": 19, "eval/task03e/S2/box/0.25/priority_refs": 16, "eval/task03e/S2/box/0.25/surface_mean_mm": 11.903134036411096, "eval/task03e/S2/box/0.25/surface_p95_mm": 19.857416679599623, "eval/task03e/S2/box/1.0/final_refs": 16, "eval/task03e/S2/box/1.0/priority_refs": 13, "eval/task03e/S2/box/1.0/surface_mean_mm": 11.992340623566282, "eval/task03e/S2/box/1.0/surface_p95_mm": 20.17851278540447, "eval/task03e/S2/peg/0.0/final_refs": 142, "eval/task03e/S2/peg/0.0/priority_refs": 142, "eval/task03e/S2/peg/0.0/surface_mean_mm": 5.263032772326343, "eval/task03e/S2/peg/0.0/surface_p95_mm": 8.675915285871412, "eval/task03e/S2/peg/0.25/final_refs": 137, "eval/task03e/S2/peg/0.25/priority_refs": 137, "eval/task03e/S2/peg/0.25/surface_mean_mm": 5.167955791794336, "eval/task03e/S2/peg/0.25/surface_p95_mm": 8.606890089366493, "eval/task03e/S2/peg/1.0/final_refs": 139, "eval/task03e/S2/peg/1.0/priority_refs": 139, "eval/task03e/S2/peg/1.0/surface_mean_mm": 5.138372297008036, "eval/task03e/S2/peg/1.0/surface_p95_mm": 8.587040055050842, "eval/task03e/S3/box/0.0/final_refs": 12, "eval/task03e/S3/box/0.0/priority_refs": 9, "eval/task03e/S3/box/0.0/surface_mean_mm": 11.580148511102212, "eval/task03e/S3/box/0.0/surface_p95_mm": 19.076807755646733, "eval/task03e/S3/box/0.25/final_refs": 6, "eval/task03e/S3/box/0.25/priority_refs": 6, "eval/task03e/S3/box/0.25/surface_mean_mm": 11.461199957394197, "eval/task03e/S3/box/0.25/surface_p95_mm": 19.0884022485739, "eval/task03e/S3/box/1.0/final_refs": 3, "eval/task03e/S3/box/1.0/priority_refs": 3, "eval/task03e/S3/box/1.0/surface_mean_mm": 11.253332822335286, "eval/task03e/S3/box/1.0/surface_p95_mm": 18.751134367052327, "eval/task03e/S3/peg/0.0/final_refs": 160, "eval/task03e/S3/peg/0.0/priority_refs": 160, "eval/task03e/S3/peg/0.0/surface_mean_mm": 5.283681389491101, "eval/task03e/S3/peg/0.0/surface_p95_mm": 8.609455303854801, "eval/task03e/S3/peg/0.25/final_refs": 143, "eval/task03e/S3/peg/0.25/priority_refs": 143, "eval/task03e/S3/peg/0.25/surface_mean_mm": 5.2679850018034164, "eval/task03e/S3/peg/0.25/surface_p95_mm": 8.694041757991016, "eval/task03e/S3/peg/1.0/final_refs": 151, "eval/task03e/S3/peg/1.0/priority_refs": 151, "eval/task03e/S3/peg/1.0/surface_mean_mm": 5.17004229914612, "eval/task03e/S3/peg/1.0/surface_p95_mm": 8.549935208152453 }, "run_id": "7f657cf88baf4f1f89e594252e243e1c", "step": 0 }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""SAM2 video tracking for runtime visual pipelines.
Example::
tracker = SAM2Tracker() state = tracker.start(video_path, {1: [x1, y1, x2, y2]}) for frame_idx, masks in tracker.track(state): ... tracker.reset(state)
``video_path`` is a directory of RGB frames accepted by SAM2. Boxes use pixelcoordinates in ``[x1, y1, x2, y2]`` format and integer object IDs. Returnedmasks are keyed by tracker ID; each value is a boolean Torch tensor with shape``[height, width]``. ``visual.runtime.rgbd.attach_rgbd`` joins this iterator torecorded RGB-D, camera calibration, and TCP poses. The Visual output includesexplicit conversion from tracker IDs to the object IDs consumed by Graph."""
from __future__ import annotations
from collections.abc import Iterator, Mapping, Sequencefrom pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parents[1]DEFAULT_CONFIG = "configs/sam2.1/sam2.1_hiera_s.yaml"DEFAULT_CHECKPOINT = ROOT / "checkpoints" / "sam2.1_hiera_small.pt"
class SAM2Tracker: """Load a SAM2 video predictor once and track prompted objects in videos.
Args: device: Torch device for SAM2 inference. Defaults to ``"cuda"`` to match the existing Visual pipeline. config: SAM2 Hydra config path, relative to the SAM2 package config directory or an absolute path. checkpoint: Model checkpoint path. hydra_overrides: Optional SAM2 model configuration overrides. predictor: Existing SAM2-compatible predictor, useful when another pipeline owns model construction. When provided, model arguments are ignored. """
def __init__(self, device: str = "cuda", config: str = DEFAULT_CONFIG, checkpoint: str | Path = DEFAULT_CHECKPOINT, hydra_overrides: Sequence[str] | None = None, predictor=None): self.device = device if predictor is None: from sam2.build_sam import build_sam2_video_predictor
predictor = build_sam2_video_predictor( config, str(checkpoint), device=device, hydra_overrides_extra=list(hydra_overrides or ()), ) self.predictor = predictor
def start(self, video_path: str | Path, boxes: Mapping[int, Sequence[float]], frame_idx: int = 0) -> dict: """Create a video state and prompt each object with its initial box.""" state = self.predictor.init_state(video_path=str(video_path)) for object_id, box in boxes.items(): coords = np.asarray(box, dtype=np.float32) if coords.shape != (4,): self.predictor.reset_state(state) raise ValueError(f"box for object {object_id} must have four coordinates") self.predictor.add_new_points_or_box( state, frame_idx=frame_idx, obj_id=int(object_id), box=coords ) return state
def track(self, state: dict, start_frame: int = 0) -> Iterator[tuple[int, dict[int, object]]]: """Yield ``(frame_index, {object_id: boolean_mask})`` for each frame.""" for frame_idx, object_ids, logits in self.predictor.propagate_in_video( state, start_frame_idx=start_frame ): masks = { int(object_id): logits[i, 0] > 0 for i, object_id in enumerate(object_ids) } yield int(frame_idx), masks
def reset(self, state: dict) -> None: """Release the predictor's per-video tracking state.""" self.predictor.reset_state(state)
# Keep the concise spelling available alongside the descriptive class name.Tracker = SAM2Tracker123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470"""Local artifact inventory and explicit Hugging Face publishing.
No network calls occur in the experiment logger. Team formats remain opaque."""from dataclasses import dataclassimport hashlibimport importlibimport ioimport jsonimport osfrom pathlib import Path, PurePosixPathimport reimport timefrom zipfile import ZIP_DEFLATED, ZipFile, ZipInfo
from .experiment_logger import REPO, clean, load_env_file, write
ORGANIZATION = 'Graph-Recurrent-VLA'DEFAULT_HF_ENV_FILE = Path('/root/.secrets/hf.env')TEAMS = ('visual', 'graph', 'recurrent', 'integration')CATEGORIES = {'checkpoint': 'checkpoint_paths', 'rollouts': 'rollout_video_paths', 'episode_metadata': 'episode_metadata_paths', 'trajectory': 'trajectory_paths', 'metrics': 'additional_metrics_paths', 'reports': 'report_paths'}
@dataclass(frozen=True)class Repository: repo_id: str repo_type: str
DEFAULT_REPOSITORIES = { 'checkpoint': Repository(f'{ORGANIZATION}/graph-recurrent-models', 'model'), 'rollouts': Repository(f'{ORGANIZATION}/graph-recurrent-rollouts', 'dataset'),}
def validate_repositories(repositories): if set(repositories) != set(DEFAULT_REPOSITORIES): raise ValueError('only checkpoint and rollouts repositories are supported') for key, repo in repositories.items(): if not re.fullmatch(r'Graph-Recurrent-VLA/[A-Za-z0-9][A-Za-z0-9._-]*', repo.repo_id): raise ValueError('repositories must belong to Graph-Recurrent-VLA') if repo.repo_type != DEFAULT_REPOSITORIES[key].repo_type: raise ValueError('repository type does not match artifact kind')
def infer_kind(path): suffix = Path(path).suffix.lower() if suffix in ('.pt', '.pth', '.ckpt', '.safetensors', '.bin'): return 'checkpoint' if suffix in ('.mp4', '.webm', '.mov', '.avi', '.mkv'): return 'rollouts' if suffix in ('.h5', '.hdf5', '.npz', '.parquet'): return 'trajectory' if suffix == '.json': return 'metrics' return None
def save_manifest(directory, metadata=None): """Cheap inventory of registered outputs, without hashing or scanning folders.
References are relative to the experiment directory, including external files. Missing registered files remain visible and are validated only when selected. """ directory = Path(directory).resolve() metadata = metadata or json.loads((directory / 'metadata.json').read_text()) manifest = dict(schema_version=1, run_id=metadata['run_id'], team=metadata['team'], model_name=metadata.get('model'), task=metadata.get('task'), environment=metadata.get('environment'), git_commit=metadata.get('git_commit'), git_dirty=metadata.get('git_dirty'), random_seed=metadata.get('seed'), wandb_run_id=metadata['run_id'], config_path='config.yaml', metrics_path='metrics.json', **{field: [] for field in CATEGORIES.values()}) for value in metadata.get('outputs', []): path = Path(value) kind = metadata.get('artifact_kinds', {}).get(str(path)) or infer_kind(path) if kind: manifest[CATEGORIES[kind]].append(os.path.relpath(path, directory)) write(directory / 'manifest.json', manifest) return manifest
def encoded(value): return (json.dumps(clean(value), sort_keys=True, indent=2, allow_nan=False) + '\n').encode()
def digests(source): sha256, git = hashlib.sha256(), hashlib.sha1() size = len(source) if isinstance(source, bytes) else source.stat().st_size git.update(f'blob {size}\0'.encode()) if isinstance(source, bytes): sha256.update(source); git.update(source) else: with source.open('rb') as stream: for block in iter(lambda: stream.read(1024 * 1024), b''): sha256.update(block); git.update(block) return size, sha256.hexdigest(), git.hexdigest()
@dataclassclass UploadFile: path: str source: object size: int sha256: str git_sha1: str
def upload_file(prefix, category, name, source): size, sha256, git_sha1 = digests(source) return UploadFile(f'{prefix}/artifacts/{category}/{sha256}/{name}', source, size, sha256, git_sha1)
def register_existing_output(directory, path, *, kind): """Attach an explicitly selected artifact to a completed run, without a new ID.
This is also the migration path for a legacy HTML registered as metrics. Existing run identity, status and artifact bytes are retained. """ if kind not in CATEGORIES: raise ValueError('unknown artifact kind') directory, path = Path(directory).resolve(), Path(path).absolute() metadata = json.loads((directory / 'metadata.json').read_text()) if metadata.get('status') == 'running': raise ValueError('finish the experiment before registering post-run artifacts') if directory.name != metadata['run_id']: raise ValueError('experiment directory and run_id do not match') owner = _check_artifact(path, metadata) path = path.resolve() metadata.setdefault('artifact_kinds', {})[str(path)] = kind if str(path) not in metadata.setdefault('outputs', []): metadata['outputs'].append(str(path)) write(directory / 'metadata.json', metadata) if owner in (None, metadata['run_id']): write(path.with_name(path.name + '.tracking.json'), dict(run_id=metadata['run_id'], experiment_directory=str(directory), artifact=str(path))) save_manifest(directory, metadata) return path
def _check_artifact(path, metadata): if path.is_symlink(): raise ValueError('selected files must not be symlinks') if not path.is_file(): raise ValueError(f'missing selected artifact file: {path.name}') sidecar = path.with_name(path.name + '.tracking.json') owner = json.loads(sidecar.read_text()).get('run_id') if sidecar.exists() else None if owner not in (None, metadata['run_id'], metadata.get('source_run_id')): raise ValueError('artifact belongs to another run; refusing stale output link') return owner
def create_report_bundle(directory, selection): """Build a deterministic ZIP from explicit archive-name -> source selections.
No directory scan or new ExperimentLogger is used. Values are paths or {"source": path, "role": "result" | "input" | "dependency"}. JSON members use the shared credential redaction policy. Original files are read only. The content-addressed archive retains relative HTML/image/video paths. """ directory = Path(directory).resolve() metadata = json.loads((directory / 'metadata.json').read_text()) if metadata.get('status') == 'running': raise ValueError('finish the experiment before bundling reports') if directory.name != metadata['run_id']: raise ValueError('experiment directory and run_id do not match') files = selection.get('files', {}) if not isinstance(files, dict) or not files: raise ValueError('report selection requires an explicit nonempty files mapping') members, inventory = {}, [] for name, item in sorted(files.items()): archive = PurePosixPath(name) if (not name or not archive.parts or archive.is_absolute() or '..' in archive.parts or '\\' in name or name != archive.as_posix() or name == 'bundle_manifest.json' or archive.parts[0] == 'experiment'): raise ValueError('report member names must be safe, unique relative paths') spec = item if isinstance(item, dict) else {'source': item} role = spec.get('role', 'result') if role not in ('result', 'input', 'dependency'): raise ValueError('report member role must be result, input or dependency') source = Path(spec['source']).expanduser().absolute() # Inputs/dependencies may come from another run; preserve its known owner. owner_metadata = metadata if role != 'result': sidecar = source.with_name(source.name + '.tracking.json') owner = json.loads(sidecar.read_text()).get('run_id') if sidecar.exists() else None owner_metadata = dict(metadata, source_run_id=owner) owner = _check_artifact(source, owner_metadata) original = source.read_bytes() if not original: raise ValueError('report members must not be empty') body = encoded(json.loads(original)) if source.suffix.lower() == '.json' else original members[name] = body inventory.append(dict(path=name, role=role, source_run_id=owner, source_sha256=hashlib.sha256(original).hexdigest(), sha256=hashlib.sha256(body).hexdigest(), size=len(body))) entrypoint = selection.get('entrypoint') if entrypoint is not None and entrypoint not in members: raise ValueError('report entrypoint must be one of the selected files') # Keep execution identity separate from the later publication/source commit. provenance = {key: metadata.get(key) for key in ('run_id', 'team', 'git_commit', 'git_dirty', 'seed', 'source_run_id', 'dataset_sha256', 'masks_sha256', 'evaluation_device')} manifest = dict(schema_version=1, **provenance, entrypoint=entrypoint, description=selection.get('description'), publication_commit=selection.get('publication_commit'), files=inventory) members['bundle_manifest.json'] = encoded(manifest) for name in ('config.yaml', 'metrics.json'): members[f'experiment/{name}'] = encoded(json.loads((directory / name).read_text())) output = io.BytesIO() with ZipFile(output, 'w', compression=ZIP_DEFLATED, compresslevel=6) as archive: for name, body in sorted(members.items()): info = ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) info.compress_type = ZIP_DEFLATED info.external_attr = 0o100644 << 16 archive.writestr(info, body, compresslevel=6) body = output.getvalue() digest = hashlib.sha256(body).hexdigest() path = directory / 'reports' / f'report-{digest}.zip' if path.exists(): if digests(path)[1] != digest: raise ValueError('existing content-addressed report archive differs') else: path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(body) register_existing_output(directory, path, kind='reports') return path
def plan_upload(directory, include, repositories=None): """Validate only explicit selections; metadata/config accompany each target.""" directory = Path(directory).resolve() repositories = repositories or DEFAULT_REPOSITORIES validate_repositories(repositories) include = set(include) if not include or include - {'checkpoint', 'rollouts', 'metrics', 'reports'}: raise ValueError('select checkpoint, rollouts, metrics and/or reports explicitly') metadata = json.loads((directory / 'metadata.json').read_text()) run_id = metadata['run_id'] if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,127}', run_id) or metadata['team'] not in TEAMS: raise ValueError('invalid run_id or team') if directory.name != run_id: raise ValueError('experiment directory and run_id do not match') if metadata.get('status') == 'running': raise ValueError('finish the experiment before publishing') manifest = save_manifest(directory, metadata) prefix = f'{metadata["team"]}/{run_id}' config = clean(json.loads((directory / 'config.yaml').read_text())) plans = {} targets = include & {'checkpoint', 'rollouts'} if 'reports' in include: targets.add('rollouts') # Reports use the existing dataset repository. if not targets: # metrics-only uses the current model repository, not a future evaluation repo. targets = {'checkpoint'} for target in sorted(targets): remote = {k: v for k, v in manifest.items() if k not in CATEGORIES.values()} remote.pop('config_path'); remote.pop('metrics_path') remote['selection'] = sorted(include) remote['artifacts'] = [] files = []
def add(path, category, *, snapshot=False): path = Path(path) if not path.is_file(): raise ValueError(f'missing selected {category} file: {path.name}') if path.is_symlink(): raise ValueError('selected files must not be symlinks') sidecar = path.with_name(path.name + '.tracking.json') if sidecar.exists(): owner = json.loads(sidecar.read_text()).get('run_id') if owner not in (run_id, metadata.get('source_run_id')): raise ValueError('artifact belongs to another run; refusing stale output link') # JSON is sanitized using the existing logger policy; never load checkpoint code. source = encoded(json.loads(path.read_text())) if snapshot else path item = upload_file(prefix, category, path.name, source) if not item.size: raise ValueError(f'empty selected {category} file: {path.name}') if item.path not in {f.path for f in files}: files.append(item) remote['artifacts'].append(dict(kind=category, path=item.path, size=item.size, sha256=item.sha256)) return item.path
# Use the already sanitized snapshot, without persisting a second local config. cfg = upload_file(prefix, 'config', 'config.yaml', encoded(config)) files.append(cfg); remote['config_path'] = cfg.path if 'metrics' in include: remote['metrics_path'] = add(directory / manifest['metrics_path'], 'metrics', snapshot=True) for value in manifest['additional_metrics_paths']: if Path(value).suffix.lower() != '.json': raise ValueError('metrics artifacts must be JSON; register HTML as reports') add(directory / value, 'metrics', snapshot=True) if target in include: field = CATEGORIES[target] if not manifest[field]: raise ValueError(f'no registered {target} files; use link_output(kind=...)') remote[field] = [add(directory / value, target) for value in manifest[field]] if target == 'rollouts': remote['episode_metadata_paths'] = [add(directory / value, 'episode_metadata', snapshot=True) for value in manifest['episode_metadata_paths']] if 'reports' in include: if not manifest['report_paths']: raise ValueError('no registered reports files; register a report or prepare a bundle') remote['report_paths'] = [add(directory / value, 'reports') for value in manifest['report_paths']] # Immutable per-selection manifest: separate invocations cannot overwrite inventory. body = encoded(remote) digest = hashlib.sha256(body).hexdigest() size, sha256, git_sha1 = digests(body) files.append(UploadFile(f'{prefix}/manifests/{digest}/manifest.json', body, size, sha256, git_sha1)) plans[target] = dict(repository=repositories[target], prefix=prefix, files=files, manifest_path=files[-1].path) return plans
def load_hf_env(path=None): """Load optional HF dotenv credentials, retaining process environment priority.""" return load_env_file(path or os.getenv('HF_ENV_FILE') or DEFAULT_HF_ENV_FILE)
def connect(): """Return no client without an official token. Never return or log the token.""" load_hf_env() try: hub = importlib.import_module('huggingface_hub') except ImportError: return None, None, 'huggingface_hub is missing; install requirements-tracking.txt' try: if not hub.get_token(): return None, None, 'no Hugging Face token; set HF_TOKEN, configure HF_ENV_FILE or /root/.secrets/hf.env, or run hf auth login' return hub.HfApi(), hub.CommitOperationAdd, None except Exception as exc: return None, None, f'Hugging Face authentication unavailable ({type(exc).__name__})'
def initialize_repositories(repositories=None, *, dry_run=False): repositories = repositories or DEFAULT_REPOSITORIES validate_repositories(repositories) if dry_run: return {'status': 'dry-run', 'repositories': [r.repo_id for r in repositories.values()], 'private': True} api, _, reason = connect() if reason: return dict(status='skipped', reason=reason) results = {} try: identity = api.whoami() if identity.get('auth', {}).get('accessToken', {}).get('role') == 'read': return dict(status='skipped', reason='Hugging Face token is read-only; configure an organization write token and rerun --init-repos') allowed = any(org.get('name') == ORGANIZATION and org.get('roleInOrg') in ('admin', 'write', 'contributor') for org in identity.get('orgs', [])) if not allowed: return dict(status='skipped', reason='organization write access not confirmed; request Graph-Recurrent-VLA access') except Exception as exc: return dict(status='skipped', reason=f'authentication/access check failed ({type(exc).__name__})') for key, repo in repositories.items(): try: url = api.create_repo(repo_id=repo.repo_id, repo_type=repo.repo_type, private=True, exist_ok=True) results[key] = dict(status='ready', url=str(url)) except Exception as exc: results[key] = dict(status='failed', **failure_details(exc)) return dict(status='ready' if all(r['status'] == 'ready' for r in results.values()) else 'failed', repositories=results)
def remote_matches(item, remote): lfs = getattr(remote, 'lfs', None) lfs_sha = lfs.get('sha256') if isinstance(lfs, dict) else getattr(lfs, 'sha256', None) return remote.size == item.size and (lfs_sha == item.sha256 if lfs else remote.blob_id == item.git_sha1)
def failure_details(exc): """Safe diagnostics: never serialize SDK exception messages or responses.""" status = getattr(getattr(exc, 'response', None), 'status_code', None) reason = {401: 'Hugging Face authentication rejected; configure HF_TOKEN or hf auth login', 403: 'Hugging Face write access denied; check token scope and organization role', 404: 'repository missing or inaccessible; check access and run --init-repos explicitly', 409: 'repository changed concurrently; rerun the same command'}.get(status, 'publish failed; verify selected files, repository access and connectivity, then rerun') return dict(error_type=type(exc).__name__, http_status=status, reason=reason)
def publish(directory, include, *, repositories=None, dry_run=False, private=False, retries=2): """Post-run, per-repository atomic commits. Return errors without transport exceptions.""" if not 0 <= retries <= 5: raise ValueError('retries must be between 0 and 5') directory = Path(directory).resolve() plans = plan_upload(directory, include, repositories) report = dict(status='dry-run' if dry_run else 'pending', total_bytes=sum( f.size for plan in plans.values() for f in plan['files']), repositories={}) for key, plan in plans.items(): report['repositories'][key] = dict(repo_id=plan['repository'].repo_id, repo_type=plan['repository'].repo_type, files=[dict(path=f.path, size=f.size) for f in plan['files']]) if dry_run: return report api, operation, reason = connect() if reason: report.update(status='skipped', reason=reason) return report receipt_path = directory / 'huggingface_uploads.json' receipts = json.loads(receipt_path.read_text()) if receipt_path.exists() else {'schema_version': 1, 'publications': {}} for key, plan in plans.items(): repo = plan['repository'] result = report['repositories'][key] for attempt in range(retries + 1): try: info = api.repo_info(repo.repo_id, repo_type=repo.repo_type) if private and not info.private: raise ValueError('repository is public; --private requires a private repository') try: tree = api.list_repo_tree(repo.repo_id, path_in_repo=plan['prefix'], recursive=True, revision=info.sha, repo_type=repo.repo_type) existing = {f.path: f for f in tree if hasattr(f, 'blob_id')} except Exception as exc: if getattr(getattr(exc, 'response', None), 'status_code', None) != 404: raise existing = {} additions = [] for item in plan['files']: if digests(item.source)[1] != item.sha256: raise ValueError('artifact changed during publishing; stop writers and rerun') if item.path in existing: if not remote_matches(item, existing[item.path]): raise ValueError('remote immutable artifact differs; refusing overwrite') else: additions.append(operation(path_in_repo=item.path, path_or_fileobj=item.source)) revision = info.sha if additions: commit = api.create_commit(repo.repo_id, repo_type=repo.repo_type, operations=additions, parent_commit=info.sha, commit_message=f'Publish experiment {directory.name} ({key})') revision = commit.oid base = 'https://huggingface.co/' + ('datasets/' if repo.repo_type == 'dataset' else '') + repo.repo_id result.update(status='uploaded' if additions else 'unchanged', revision=revision, url=f'{base}/tree/{revision}/{plan["prefix"]}', manifest_path=plan['manifest_path'], uploaded_files=len(additions), skipped_files=len(plan['files']) - len(additions)) receipt_key = f'{repo.repo_type}:{repo.repo_id}:{plan["manifest_path"]}' receipts['publications'][receipt_key] = {k: v for k, v in result.items() if k != 'files'} write(receipt_path, receipts) break except Exception as exc: # Exception strings may include credentials or request headers. result.update(status='failed', **failure_details(exc), attempts=attempt + 1) status = result['http_status'] if isinstance(exc, ValueError) or (status and 400 <= status < 500 and status not in (409, 429)): break if attempt < retries: time.sleep(min(2 ** attempt, 8)) if result['status'] != 'failed': for field in ('error_type', 'attempts', 'http_status', 'reason'): result.pop(field, None) report['status'] = 'failed' if any(r['status'] == 'failed' for r in report['repositories'].values()) else 'complete' return report
def sync_wandb_links(directory): """Separate opt-in metadata update, no run resume/init or history replay.""" directory = Path(directory) receipts = json.loads((directory / 'huggingface_uploads.json').read_text()) metadata = json.loads((directory / 'metadata.json').read_text()) from .experiment_logger import has_wandb_api_key, load_wandb_env load_wandb_env() if not has_wandb_api_key() or not metadata.get('entity'): return dict(status='skipped', reason='W&B API key and recorded entity are required; HF receipts retained') try: wandb = importlib.import_module('wandb') run = wandb.Api(timeout=10).run(f'{metadata["entity"]}/{metadata["project"]}/{metadata["run_id"]}') run.summary['huggingface'] = receipts['publications'] run.summary.update() return dict(status='complete') except Exception as exc: return dict(status='failed', error_type=type(exc).__name__)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192"""CUDA PCA5 resident/transfer timing and same-estimator fidelity.
Uses real CUDA execution, paired CPU reference truth, full point support andfloat64 covariance. Does not claim tracking or final Graph handoff timing."""from __future__ import annotationsimport argparsefrom pathlib import Pathimport platformimport sysfrom time import perf_counterimport numpy as npimport torch
REPO=Path(__file__).resolve().parents[3];sys.path.insert(0,str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.geometry import GeometryFrame,GeometricFeatures,build_organized_geometryfrom visual.runtime.rgbd import iter_saved_rgbdfrom visual.runtime.test.pca_torch import TorchPCA5from visual.runtime.test.run_pca_optimization import reference,fidelity,combine_fidelity,synthetic_observationsfrom visual.runtime.test.normal_diagnostics import statsfrom visual.runtime.test.run_normal_diagnostics import save_json
def benchmark(input_path,masks_path,output_root,*,repeats=3,backend='eigh',synthetic=False): frames=list(iter_saved_rgbd(input_path,masks_path)) cfg=dict(task='pca5_cuda',repeats=repeats,backend=backend,synthetic=synthetic,pca_dtype='float64',initial_grounding_excluded=True,tracking_included=False, input_sha256=digests(Path(input_path))[1],masks_sha256=digests(Path(masks_path))[1],torch=torch.__version__,platform=platform.platform(), source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in [Path(__file__),Path(__file__).with_name('pca_torch.py'),Path(__file__).with_name('pca_triton.py')]}) with ExperimentLogger(team='visual',config=cfg,seed=0,model='pca5_cuda',job_type='evaluate') as logger: out=Path(output_root)/logger.run_id;out.mkdir(parents=True,exist_ok=False);print('Output:',out,flush=True) if not torch.cuda.is_available(): save_json(out/'cuda.json',dict(run_id=logger.run_id,config=cfg,status='not_executed',reason='CUDA unavailable')) logger.link_output(out/'cuda.json',kind='metrics');logger.record(gpu_executed=False);return out torch.set_num_threads(4) cfg['gpu']=torch.cuda.get_device_name();logger.record(evaluation_device='cuda',gpu_executed=True,gpu=cfg['gpu']) processor=TorchPCA5(frames[0].intrinsic,frames[0].depth.shape,device='cuda',backend=backend) resident=[(torch.as_tensor(f.depth,device='cuda'),{i:torch.as_tensor(m,device='cuda') for i,m in f.masks.items()}) for f in frames] for _ in range(3): processor(*resident[0]) torch.cuda.synchronize();torch.cuda.reset_peak_memory_stats() rows=[];quality=[] for idx,frame in enumerate(frames): expected=reference(frame) for repeat in range(repeats): for mode in (('resident','cpu_input') if (idx+repeat)%2==0 else ('cpu_input','resident')): torch.cuda.synchronize();start=perf_counter() if mode=='cpu_input': data=(torch.as_tensor(frame.depth,device='cuda'),{i:torch.as_tensor(m,device='cuda') for i,m in frame.masks.items()}) else:data=resident[idx] begin=torch.cuda.Event(enable_timing=True);end=torch.cuda.Event(enable_timing=True) begin.record();result=processor(*data);end.record();torch.cuda.synchronize();wall=(perf_counter()-start)*1000 rows.append(dict(source_frame=frame.source_frame,repeat=repeat,mode=mode,wall_ms=wall,device_ms=begin.elapsed_time(end))) if repeat==0 and mode=='resident': objects={i:GeometricFeatures(**{k:v.cpu().numpy() for k,v in f.items()}) for i,f in result['objects'].items()} actual=GeometryFrame(frame.source_frame,frame.camera,frame.frame_idx,frame.timestamp,build_organized_geometry(frame),objects,{}) np.testing.assert_array_equal(result['xyz'].cpu().numpy(),expected.geometry.xyz) q=fidelity(expected,actual);quality.append(q) if idx==0 or (idx+1)%20==0:print('CUDA frames',idx+1,'/',len(frames),flush=True) synthetic_rows=[] if synthetic: for idx,(condition,frame,truth,regions) in enumerate(synthetic_observations(frames[0].intrinsic)): expected=reference(frame) result=processor(torch.as_tensor(frame.depth,device='cuda'),{i:torch.as_tensor(m,device='cuda') for i,m in frame.masks.items()}) objects={i:GeometricFeatures(**{k:v.cpu().numpy() for k,v in f.items()}) for i,f in result['objects'].items()} actual=GeometryFrame(frame.source_frame,frame.camera,frame.frame_idx,frame.timestamp,build_organized_geometry(frame),objects,{}) np.testing.assert_array_equal(result['xyz'].cpu().numpy(),expected.geometry.xyz) synthetic_rows.append(dict(condition=condition,fidelity=fidelity(expected,actual))) if (idx+1)%48==0:print('CUDA synthetic conditions',idx+1,'/288',flush=True) fs=combine_fidelity(quality) sf=combine_fidelity([r['fidelity'] for r in synthetic_rows]) summary={mode:{k:stats([r[k] for r in rows if r['mode']==mode]) for k in ('wall_ms','device_ms')} for mode in ('resident','cpu_input')} passed=all(v['validity_differences']==0 and v['other_field_differences']==0 and v['normal_max_deg']<=.001 and v['variation_max_deg']<=.001 for v in (fs,sf)) save_json(out/'cuda.json',dict(run_id=logger.run_id,config=cfg,status='executed',quality_passed=passed,fidelity=fs,summary=summary,frames=rows, synthetic=dict(fidelity=sf,cases=synthetic_rows),peak_allocated_bytes=torch.cuda.max_memory_allocated(),peak_reserved_bytes=torch.cuda.max_memory_reserved())) logger.link_output(out/'cuda.json',kind='metrics');logger.log(summary,prefix='eval/cuda');logger.log(fs,prefix='eval/cuda/fidelity') if not passed:raise AssertionError('CUDA fidelity tolerance failed') return out
def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') p.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') p.add_argument('--out',type=Path,default=REPO/'visual/results/pca_optimization') p.add_argument('--repeats',type=int,default=3) p.add_argument('--backend',choices=['eigh','triton','triton_fused'],default='eigh') p.add_argument('--synthetic',action='store_true') a=p.parse_args();print(benchmark(a.input,a.masks,a.out,repeats=a.repeats,backend=a.backend,synthetic=a.synthetic))
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263test_joint_matching_same_pair_dedup_and_staged_union (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_joint_matching_same_pair_dedup_and_staged_union) ... oktest_peg_face_pair_endpoint_ambiguity_and_nonphysical_order_na (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_peg_face_pair_endpoint_ambiguity_and_nonphysical_order_na) ... oktest_rim_line_identity_from_existing_transform_and_corner_ambiguity (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_rim_line_identity_from_existing_transform_and_corner_ambiguity) ... oktest_spacing_uses_actual_node_projections_not_covered_reference_centres (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_spacing_uses_actual_node_projections_not_covered_reference_centres) ... oktest_all_weights_fixed_initial_quota_original_xyz_surface_metric (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_all_weights_fixed_initial_quota_original_xyz_surface_metric) ... oktest_every_gate_required_before_either_control (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_every_gate_required_before_either_control) ... oktest_feature_gather_exact_only_available_rows_no_placeholder (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_feature_gather_exact_only_available_rows_no_placeholder) ... oktest_gt_annotations_and_segment_labels_cannot_affect_selection (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_gt_annotations_and_segment_labels_cannot_affect_selection) ... oktest_lambda_one_matches_existing_priority_and_seeded_surface (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_lambda_one_matches_existing_priority_and_seeded_surface) ... oktest_metric_squared_distance_formula_and_original_unchanged (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_metric_squared_distance_formula_and_original_unchanged) ... oktest_zero_weight_z_change_does_not_change_priority_with_xy_ties (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_zero_weight_z_change_does_not_change_priority_with_xy_ties) ... 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/tmpj2y1fq13/out/a2d769350d834b809fd323bdbbbccd66Frames 1/2; 44 conditions eachoktest_staged_sweeps_cover_all_requested_values (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_staged_sweeps_cover_all_requested_values) ... oktest_tracking_and_sampling_losses_have_separate_denominators (visual.runtime.test.test_sampling_evaluation.SamplingEvaluationTests.test_tracking_and_sampling_losses_have_separate_denominators) ... oktest_empty_points_zero_observation_and_zero_visible (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_empty_points_zero_observation_and_zero_visible) ... oktest_general_fps_candidate_and_priority_are_inapplicable (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_general_fps_candidate_and_priority_are_inapplicable) ... oktest_geometry_alignment_invalid_depth_overlap_and_pixel_centres (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_geometry_alignment_invalid_depth_overlap_and_pixel_centres) ... oktest_historical_evaluation_changes_fail_closed (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_historical_evaluation_changes_fail_closed) ... oktest_invalid_nodes_and_non_partition_are_rejected (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_invalid_nodes_and_non_partition_are_rejected) ... oktest_negative_union_deduplicates_and_depth_bands_cover_paths (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_negative_union_deduplicates_and_depth_bands_cover_paths) ... oktest_reference_overlap_union_and_surface_outside_candidates (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_reference_overlap_union_and_surface_outside_candidates) ... oktest_two_different_nodes_cannot_satisfy_one_reference_pair (visual.runtime.test.test_sampling_evaluation.StagedCoverageTests.test_two_different_nodes_cannot_satisfy_one_reference_pair) ... oktest_duplicate_xyz_and_annotation_independence (visual.runtime.test.test_priority_fps_trace.PriorityFPSTraceTests.test_duplicate_xyz_and_annotation_independence) ... oktest_exact_tie_and_preselection_competition (visual.runtime.test.test_priority_fps_trace.PriorityFPSTraceTests.test_exact_tie_and_preselection_competition) ... oktest_fps_consumes_one_initial_integer_draw (visual.runtime.test.test_priority_fps_trace.PriorityFPSTraceTests.test_fps_consumes_one_initial_integer_draw) ... oktest_wrong_tie_winner_fails (visual.runtime.test.test_priority_fps_trace.PriorityFPSTraceTests.test_wrong_tie_winner_fails) ... oktest_corrupt_source_feature_role_or_order_fails (visual.runtime.test.test_priority_fps_seed_control.SavedAnalysisTests.test_corrupt_source_feature_role_or_order_fails) ... oktest_joint_same_pair_and_reference_dedup (visual.runtime.test.test_priority_fps_seed_control.SavedAnalysisTests.test_joint_same_pair_and_reference_dedup) ... oktest_seed0_reused_and_only_seed1_2_matched_without_fps (visual.runtime.test.test_priority_fps_seed_control.SavedAnalysisTests.test_seed0_reused_and_only_seed1_2_matched_without_fps) ... oktest_source_feature_role_alignment_without_fps (visual.runtime.test.test_priority_fps_seed_control.SavedAnalysisTests.test_source_feature_role_alignment_without_fps) ... oktest_gt_annotation_change_cannot_change_control_selection (visual.runtime.test.test_priority_fps_seed_control.SharedInitialTests.test_gt_annotation_change_cannot_change_control_selection) ... oktest_initial_included_total_32_exact_local_global_no_rng (visual.runtime.test.test_priority_fps_seed_control.SharedInitialTests.test_initial_included_total_32_exact_local_global_no_rng) ... oktest_initial_path_never_constructs_rng_even_when_seed_changes (visual.runtime.test.test_priority_fps_seed_control.SharedInitialTests.test_initial_path_never_constructs_rng_even_when_seed_changes) ... oktest_intersection_and_initial_mismatch_stop_before_fps (visual.runtime.test.test_priority_fps_seed_control.SharedInitialTests.test_intersection_and_initial_mismatch_stop_before_fps) ... oktest_invalid_fps_order_is_rejected (visual.runtime.test.test_priority_fps_seed_control.SharedInitialTests.test_invalid_fps_order_is_rejected) ... oktest_order_xyz_and_short_count_mismatch_stop_before_fps (visual.runtime.test.test_priority_fps_seed_control.SharedInitialTests.test_order_xyz_and_short_count_mismatch_stop_before_fps) ... ok
----------------------------------------------------------------------Ran 56 tests in 0.726s
OK1234567891011121314151617test_actual_gap_includes_matching_node_outside_visible_reference_span (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_actual_gap_includes_matching_node_outside_visible_reference_span) ... oktest_joint_matching_same_pair_dedup_and_staged_union (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_joint_matching_same_pair_dedup_and_staged_union) ... oktest_peg_face_pair_endpoint_ambiguity_and_nonphysical_order_na (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_peg_face_pair_endpoint_ambiguity_and_nonphysical_order_na) ... oktest_rim_line_identity_from_existing_transform_and_corner_ambiguity (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_rim_line_identity_from_existing_transform_and_corner_ambiguity) ... oktest_spacing_uses_actual_node_projections_not_covered_reference_centres (visual.runtime.test.test_priority_fps_metric_control.LocalEvaluationTests.test_spacing_uses_actual_node_projections_not_covered_reference_centres) ... oktest_all_weights_fixed_initial_quota_original_xyz_surface_metric (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_all_weights_fixed_initial_quota_original_xyz_surface_metric) ... oktest_every_gate_required_before_either_control (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_every_gate_required_before_either_control) ... oktest_feature_gather_exact_only_available_rows_no_placeholder (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_feature_gather_exact_only_available_rows_no_placeholder) ... oktest_gt_annotations_and_segment_labels_cannot_affect_selection (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_gt_annotations_and_segment_labels_cannot_affect_selection) ... oktest_lambda_one_matches_existing_priority_and_seeded_surface (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_lambda_one_matches_existing_priority_and_seeded_surface) ... oktest_metric_squared_distance_formula_and_original_unchanged (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_metric_squared_distance_formula_and_original_unchanged) ... oktest_zero_weight_z_change_does_not_change_priority_with_xy_ties (visual.runtime.test.test_priority_fps_metric_control.MetricSelectionTests.test_zero_weight_z_change_does_not_change_priority_with_xy_ties) ... ok
----------------------------------------------------------------------Ran 12 tests in 0.005s
OK12345678910[45509:4434323:1024/131233.616634:ERROR:ui/display/mac/cv_display_link_mac.mm:188] CVDisplayLinkCreateWithCGDisplay failed. CVReturn: -6670[45509:4434323:1024/131233.617358:ERROR:ui/display/mac/cv_display_link_mac.mm:188] CVDisplayLinkCreateWithCGDisplay failed. CVReturn: -6670[45509:4434323:1024/131233.617411:ERROR:ui/display/mac/cv_display_link_mac.mm:188] CVDisplayLinkCreateWithCGDisplay failed. CVReturn: -6670[45509:4434323:1024/131233.617458:ERROR:ui/display/mac/cv_display_link_mac.mm:188] CVDisplayLinkCreateWithCGDisplay failed. CVReturn: -6670[45509:4434323:1024/131233.617507:ERROR:ui/display/mac/cv_display_link_mac.mm:188] CVDisplayLinkCreateWithCGDisplay failed. CVReturn: -6670[45509:4434323:1024/131233.618011:ERROR:ui/display/mac/cv_display_link_mac.mm:188] CVDisplayLinkCreateWithCGDisplay failed. CVReturn: -6670Trying to load the allocator multiple times. This is *not* supported.836010 bytes written to file /Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/experiments/7f657cf88baf4f1f89e594252e243e1c/html_preview.png[45500:4434293:1024/131233.887610:ERROR:base/process/process_mac.cc:45] task_policy_set TASK_CATEGORY_POLICY: (os/kern) invalid argument (4)[45500:4434293:1024/131233.887627:ERROR:base/process/process_mac.cc:90] task_policy_set TASK_SUPPRESSION_POLICY: (os/kern) invalid argument (4)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""Grounding DINO initialization rules from the Visual v1 prototype.
Only RGB detections are used. A missing object stays missing until two scansagree; no simulator segmentation or pose is consulted."""
from __future__ import annotations
from itertools import product
PROMPTS = {"peg": "red and white block", "box": "cardboard box"}MAX_BOX_FRAC = 0.25MISSING_SCORE = 0.3EXCLUSION_IOU = 0.3SCAN_EVERY = 5
def box_iou(a, b): x = max(0.0, min(a[2], b[2]) - max(a[0], b[0])) y = max(0.0, min(a[3], b[3]) - max(a[1], b[1])) intersection = x * y area_a = (a[2] - a[0]) * (a[3] - a[1]) area_b = (b[2] - b[0]) * (b[3] - b[1]) union = area_a + area_b - intersection return intersection / union if union > 0 else 0.0
def candidates(detector, rgb, prompt, limit=5): height, width = rgb.shape[:2] boxes, scores = detector(rgb, prompt) return [(box, float(score)) for box, score in zip(boxes, scores) if (box[2] - box[0]) * (box[3] - box[1]) < MAX_BOX_FRAC * height * width][:limit]
def assign(peg_candidates, box_candidates): """Pick distinct objects jointly, with an explicit missing choice.""" best = (None, None) best_score = 2 * MISSING_SCORE for peg, box in product([*peg_candidates, None], [*box_candidates, None]): if peg is not None and box is not None and box_iou(peg[0], box[0]) >= EXCLUSION_IOU: continue score = (peg[1] if peg else MISSING_SCORE) + (box[1] if box else MISSING_SCORE) if score > best_score: best, best_score = (peg, box), score return best
def detect_initial(frames, detector, prompts=None): """Return each object's selected box, score and source-frame index.""" prompts = PROMPTS if prompts is None else prompts first = {name: candidates(detector, frames[0], prompts[name]) for name in PROMPTS} peg, box = assign(first["peg"], first["box"]) result = { "peg": {"box": peg[0] if peg else None, "score": peg[1] if peg else None, "frame": 0 if peg else None, "prompt": prompts["peg"], "scans": 1}, "box": {"box": box[0] if box else None, "score": box[1] if box else None, "frame": 0 if box else None, "prompt": prompts["box"], "scans": 1}, } for name in PROMPTS: if result[name]["box"] is not None: continue other = result["box" if name == "peg" else "peg"]["box"] pending = None for frame in range(SCAN_EVERY, len(frames), SCAN_EVERY): result[name]["scans"] += 1 choices = [candidate for candidate in candidates(detector, frames[frame], prompts[name]) if candidate[1] >= MISSING_SCORE and (other is None or box_iou(candidate[0], other) < EXCLUSION_IOU)] if not choices: pending = None continue choice = choices[0] if pending is not None and box_iou(choice[0], pending[0]) >= 0.5: result[name].update(box=choice[0], score=choice[1], frame=frame) break pending = choice return result12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Saved-mask integration: source rows, dense artifacts and local run identity."""
from dataclasses import fieldsimport jsonimport osfrom pathlib import Pathimport tempfileimport unittestfrom unittest.mock import patch
import matplotlib.image as mpimgimport numpy as np
from visual.runtime.geometry import GeometricFeatures, process_geometryfrom visual.runtime.rgbd import BOX, PEG, iter_saved_rgbdfrom visual.runtime.test.run_geometry import evaluate
class GeometryEvaluationTests(unittest.TestCase): def test_sparse_sources_and_empty_mask_preserve_dense_features_without_rgb(self): count, height, width = 3, 9, 11 depth = np.ones((count, height, width), np.float32) depth[2] *= 2 depth[2, 4, 4] = np.nan source = np.array([0, 2], np.int32) peg = np.zeros((2, height, width), bool) peg[:, 1:8, 1:6] = True box = np.zeros_like(peg) box[1, 1:8, 7:10] = True # Deliberately no simulator GT in the input. episode = {"camera/rgb": np.full((count, height, width, 3), 110, np.uint8), "camera/depth": depth, "camera/intrinsic": np.tile([[100, 0, 5.5], [0, 100, 4.5], [0, 0, 1]], (count, 1, 1)), "camera/cam2world": np.tile(np.eye(4), (count, 1, 1)), "tcp_pose": np.tile([0, 0, 0, 1, 0, 0, 0], (count, 1)), "frame_idx": np.array([10, 11, 12]), "timestamp": np.array([0, 0.05, 0.1])} with tempfile.TemporaryDirectory() as directory: root = Path(directory) episode_path, masks_path = root / "episode.npz", root / "masks.npz" np.savez(episode_path, **episode) np.savez(masks_path, source_frame=source, peg=peg, box=box) with patch.dict(os.environ, {"WANDB_MODE": "disabled", "EXPERIMENTS_DIR": str(root / "experiments")}): output = evaluate(episode_path, masks_path, camera="camera", output_root=root / "out", selected_sources=[0, 2], repeats=1) data = json.loads((output / "geometry.json").read_text()) self.assertEqual([r["source_frame"] for r in data["frames"]], [0, 2]) self.assertEqual([r["frame_idx"] for r in data["frames"]], [10, 12]) self.assertEqual(data["summary"]["box"]["no_points_frames"], 1) self.assertEqual(data["frames"][0]["objects"]["box"]["observation_state"], "empty_mask") self.assertEqual(data["timing_ms"]["total"]["count"], 2) self.assertEqual(data["config"]["gt_segmentation_ids"], {}) self.assertEqual(len(data["config"]["input_sha256"]), 64) for frame in iter_saved_rgbd(episode_path, masks_path, camera="camera"): expected = process_geometry(frame) with np.load(output / f"f{frame.source_frame:04d}.npz", allow_pickle=False) as saved: self.assertNotIn("rgb", saved) self.assertEqual(int(saved["source_frame"]), frame.source_frame) self.assertEqual(int(saved["frame_idx"]), frame.frame_idx) np.testing.assert_array_equal(saved["xyz"], expected.geometry.xyz) for name, object_id in (("peg", PEG), ("box", BOX)): for field in fields(GeometricFeatures): np.testing.assert_array_equal(saved[f"{name}/{field.name}"], getattr(expected.objects[object_id], field.name)) image = mpimg.imread(output / f"f{frame.source_frame:04d}.png") self.assertGreater(image.shape[0], 1000) self.assertGreater(float(image.std()), 0.1) for name in ("geometry.html", "geometry.json", "f0000.npz", "f0000.png", "f0002.npz", "f0002.png"): sidecar = json.loads((output / f"{name}.tracking.json").read_text()) self.assertEqual(sidecar["run_id"], output.name) metadata = json.loads((root / "experiments" / output.name / "metadata.json").read_text()) self.assertEqual(metadata["status"], "finished") self.assertEqual(metadata["evaluation_device"], "cpu") self.assertFalse(metadata["gpu_executed"])
def test_invalid_diagnostic_parameters_fail_before_output(self): for arguments in (dict(repeats=0), dict(variation_degrees=np.nan), dict(variation_degrees=181)): with self.subTest(arguments=arguments), self.assertRaises(ValueError): evaluate("missing_episode", "missing_masks", output_root="unused", **arguments)
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""Detect objects with Grounding DINO, track them with SAM2, and save a movie.
Run from the repository root::
.venv/bin/python visual/runtime/test/run_tracking.py \ --input visual/data/step2/ep000.npz --device cuda
Grounding DINO jointly assigns peg and box boxes, including late initialization.SAM2 propagates their masks. Outputs include an MP4, PNGs, masks, and metadata."""
from __future__ import annotations
import argparseimport jsonimport sysimport tempfileimport timefrom contextlib import nullcontextfrom pathlib import Path
import cv2import imageio.v2 as imageioimport numpy as np
SCRIPT_DIR = Path(__file__).resolve().parentRUNTIME_DIR = SCRIPT_DIR.parentVISUAL_ROOT = SCRIPT_DIR.parents[1]DEFAULT_INPUT = VISUAL_ROOT / "data/step2/ep000.npz"sys.path.insert(0, str(RUNTIME_DIR))
from tracking import SAM2Tracker # noqa: E402from initialization import detect_initial # noqa: E402
OBJECTS = { "peg": (1, (255, 70, 70), "red and white block"), "box": (2, (60, 130, 255), "cardboard box"),}
def load_input(path: Path, camera: str, parser: argparse.ArgumentParser): """Return RGB frames, input kind, timestamps, and a useful default fps.""" if path.suffix.lower() == ".npz": with np.load(path) as archive: key = f"{camera}/rgb" if key not in archive: parser.error(f"{path} has no '{key}' array") frames = np.asarray(archive[key], dtype=np.uint8) timestamps = np.asarray(archive["timestamp"]) if "timestamp" in archive else None fps = 20.0 if timestamps is not None: if len(timestamps) != len(frames): parser.error(f"timestamp length {len(timestamps)} differs from frame count {len(frames)}") gaps = np.diff(timestamps.astype(np.float64)) gaps = gaps[gaps > 0] if len(gaps): fps = float(1.0 / np.median(gaps)) return frames, "episode", timestamps, fps
capture = cv2.VideoCapture(str(path)) if not capture.isOpened(): parser.error(f"could not open video: {path}") fps = float(capture.get(cv2.CAP_PROP_FPS)) frames = [] while True: ok, bgr = capture.read() if not ok: break frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)) capture.release() if not frames: parser.error(f"video contains no readable frames: {path}") if not np.isfinite(fps) or fps <= 0: fps = 20.0 return np.stack(frames), "video", None, fps
def initial_boxes(frames: np.ndarray, args) -> dict: """Run the RGB-only v1 joint assignment and late initialization.""" from grounding import GDino
detector = GDino(device=args.device, threshold=args.threshold) prompts = {name: getattr(args, f"{name}_prompt") or default_prompt for name, (_, _, default_prompt) in OBJECTS.items()} return detect_initial(frames, detector, prompts)
def render_frame(rgb: np.ndarray, masks: dict[int, object], initial: dict, frame_idx: int) -> np.ndarray: """Blend predicted masks and draw initial Grounding DINO boxes.""" out = rgb.copy() for name, (object_id, color, _) in OBJECTS.items(): mask = masks.get(object_id) if mask is None: continue if hasattr(mask, "detach"): mask = mask.detach().to("cpu").numpy() mask = np.asarray(mask, dtype=bool) if mask.shape != rgb.shape[:2]: mask = cv2.resize(mask.astype(np.uint8), (rgb.shape[1], rgb.shape[0]), interpolation=cv2.INTER_NEAREST).astype(bool) out[mask] = (0.45 * out[mask] + 0.55 * np.asarray(color)).astype(np.uint8) contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(out, contours, -1, color, max(1, min(rgb.shape[:2]) // 256)) ys, xs = np.nonzero(mask) if len(xs): cv2.putText(out, name, (int(xs.min()), max(18, int(ys.min()) - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2, cv2.LINE_AA)
for name, (object_id, color, _) in OBJECTS.items(): item = initial[name] if item["box"] is None or frame_idx != item["frame"]: continue x1, y1, x2, y2 = (int(round(value)) for value in item["box"]) cv2.rectangle(out, (x1, y1), (x2, y2), color, 1, cv2.LINE_AA) cv2.putText(out, f"GDINO {name}", (x1 + 3, max(16, y1 - 4)), cv2.FONT_HERSHEY_SIMPLEX, 0.42, color, 1, cv2.LINE_AA) cv2.putText(out, f"SAM2 mask + GDINO init box | frame {frame_idx}", (10, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.65, (255, 255, 255), 2, cv2.LINE_AA) return out
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, default=DEFAULT_INPUT, help="Episode NPZ with camera RGB arrays or a video file") parser.add_argument("--out", type=Path, default=VISUAL_ROOT / "results/runtime_tracking") parser.add_argument("--camera", default="base_camera", help="Camera name for episode NPZ input") parser.add_argument("--device", default="cuda") parser.add_argument("--config", default="configs/sam2.1/sam2.1_hiera_s.yaml") parser.add_argument("--checkpoint", type=Path, default=VISUAL_ROOT / "checkpoints/sam2.1_hiera_small.pt") parser.add_argument("--threshold", type=float, default=0.1, help="Grounding DINO threshold used to initialize boxes") parser.add_argument("--stride", type=int, default=1, help="Track every Nth source frame and write those frames") parser.add_argument("--max-frames", type=int, default=None) parser.add_argument("--fps", type=float, default=None, help="Output fps; defaults to source fps / stride") parser.add_argument("--peg-prompt", default=None) parser.add_argument("--box-prompt", default=None) parser.add_argument("--hydra-override", action="append", default=[], help="SAM2 config override; may be passed more than once") args = parser.parse_args()
if args.stride < 1: parser.error("--stride must be at least 1") if args.fps is not None and args.fps <= 0: parser.error("--fps must be positive") if not args.input.is_file(): parser.error(f"input file does not exist: {args.input}") if not args.checkpoint.is_file(): parser.error(f"SAM2 checkpoint does not exist: {args.checkpoint}")
frames, input_kind, timestamps, source_fps = load_input(args.input, args.camera, parser) if frames.ndim != 4 or frames.shape[-1] != 3: parser.error(f"expected RGB frames with shape (T,H,W,3), got {frames.shape}") if timestamps is not None and len(timestamps) != len(frames): parser.error("timestamp and RGB frame counts differ") selected = list(range(0, len(frames), args.stride)) if args.max_frames is not None: selected = selected[:max(0, args.max_frames)] if not selected: parser.error("input contains no frames to track")
sampled = frames[selected] initial = initial_boxes(sampled, args) args.out.mkdir(parents=True, exist_ok=True) frames_dir = args.out / "frames" frames_dir.mkdir(parents=True, exist_ok=True) video_path = args.out / "tracking.mp4" if len(selected) > 1 else None output_fps = args.fps or source_fps / args.stride
tracker = SAM2Tracker(device=args.device, config=args.config, checkpoint=args.checkpoint, hydra_overrides=args.hydra_override) records = [] started = time.perf_counter() with tempfile.TemporaryDirectory(prefix="sam2_runtime_") as frame_dir: for local_idx, source_idx in enumerate(selected): frame_path = Path(frame_dir) / f"{local_idx:06d}.jpg" cv2.imwrite(str(frame_path), cv2.cvtColor(frames[source_idx], cv2.COLOR_RGB2BGR))
height, width = sampled.shape[1:3] masks_by_name = {name: np.zeros((len(selected), height, width), dtype=bool) for name in OBJECTS} first_group = [name for name in OBJECTS if initial[name]["frame"] == 0] groups = [(first_group, 0)] if first_group else [] groups += [([name], initial[name]["frame"]) for name in OBJECTS if initial[name]["frame"] not in (0, None)] for names, start in groups: boxes = {OBJECTS[name][0]: initial[name]["box"] for name in names} state = tracker.start(frame_dir, boxes, frame_idx=start) try: for local_idx, masks in tracker.track(state, start_frame=start): for name in names: mask = masks.get(OBJECTS[name][0]) if mask is None: continue if hasattr(mask, "detach"): mask = mask.detach().cpu().numpy() mask = np.asarray(mask, dtype=bool) if mask.shape != (height, width): mask = cv2.resize(mask.astype(np.uint8), (width, height), interpolation=cv2.INTER_NEAREST).astype(bool) masks_by_name[name][local_idx] = mask finally: tracker.reset(state)
np.savez_compressed(args.out / "masks.npz", **masks_by_name, source_frame=np.asarray(selected, dtype=np.int32)) writer_context = (imageio.get_writer(video_path, fps=output_fps, macro_block_size=1) if video_path else nullcontext(None)) with writer_context as writer: for local_idx, source_idx in enumerate(selected): masks = {OBJECTS[name][0]: values[local_idx] for name, values in masks_by_name.items()} rendered = render_frame(frames[source_idx], masks, initial, local_idx) cv2.imwrite(str(frames_dir / f"frame_{source_idx:05d}.png"), cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) if writer is not None: writer.append_data(rendered) records.append({"frame": int(source_idx), "objects": { name: {"object_id": object_id, "mask_pixels": int(masks_by_name[name][local_idx].sum())} for name, (object_id, _, _) in OBJECTS.items()}}) print(f"tracked frame {source_idx} ({local_idx + 1}/{len(selected)})", flush=True)
result = { "input": str(args.input.resolve()), "input_kind": input_kind, "camera": args.camera if input_kind == "episode" else None, "device": args.device, "config": args.config, "checkpoint": str(args.checkpoint.resolve()), "source_fps": source_fps, "output_fps": output_fps, "stride": args.stride, "frames_tracked": len(records), "elapsed_seconds": round(time.perf_counter() - started, 3), "initial_boxes": initial, "mask_file": str(args.out / "masks.npz"), "video": str(video_path) if video_path else None, "frames_dir": str(frames_dir), "results": records, } (args.out / "tracking.json").write_text(json.dumps(result, indent=2), encoding="utf-8") if video_path: print(f"saved video: {video_path}") print(f"saved frames: {frames_dir}") print(f"saved metadata: {args.out / 'tracking.json'}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259diff --git a/docs/visual-graph-integration/03_sampling.md b/docs/visual-graph-integration/03_sampling.mdindex acb3c0f..ac76cf2 100644--- a/docs/visual-graph-integration/03_sampling.md+++ b/docs/visual-graph-integration/03_sampling.md@@ -7,6 +7,10 @@ S4 depth-only 우선 선택은 이 조건에서 Peg 보존을 낮추고 가림· 이 수치는 **Tracker가 현재 관측한 reference 대비 Sampling 보존율**이다. 최종 detector, threshold, ratio 또는 feature 표현을 채택한 결과는 아니다. +후속 [Task03-D Box rim 병목 분석 Phase 1](03d_box_rim_bottleneck_phase1.md)은 저장된 frame 0/120의+관측·후보·priority·Surface coverage를 분리한다. Frame 0의 S3는 후보 coverage가 더 높지만+priority와 최종 coverage는 더 낮았다. 오염·원거리 depth·FPS 거리 경쟁의 인과 기여율은 미확인이다.+ 최종 run: `2551448b0fae4c6bbce3caf48774275f`. [전체 HTML](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.html), [전체 summary·설정·fidelity JSON](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json), [검증 기록](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/verification.json), [budget/ratio/false selection/latency 그림](../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/tradeoffs.png),diff --git a/visual/runtime/test/sampling_evaluation.py b/visual/runtime/test/sampling_evaluation.pyindex ea0f223..e242ecc 100644--- a/visual/runtime/test/sampling_evaluation.py+++ b/visual/runtime/test/sampling_evaluation.py@@ -44,6 +44,25 @@ class CoverageMatcher: @staticmethod def key(px,m): return f'{px:g}px_{m*1000:g}mm' + def reference_hits(self, selected_flat, px=2., m=.003):+ """Reference IDs and matched source nodes from the existing joint adjacency.++ IDs are row positions in the saved reference arrays, not rounded pixels.+ A node can cover multiple IDs; multiple nodes covering one ID count once.+ """+ selected_flat = np.asarray(selected_flat)+ if selected_flat.ndim != 1 or selected_flat.dtype.kind not in 'iu':+ raise ValueError('source indices must be a one-dimensional integer array')+ if len(np.unique(selected_flat)) != len(selected_flat):+ raise ValueError('duplicate source nodes')+ rows = np.searchsorted(self.flat, selected_flat)+ if len(rows) and ((rows >= len(self.flat)).any()+ or not np.array_equal(self.flat[rows], selected_flat)):+ raise ValueError('evaluation points outside observed support')+ adjacency = self.adjacencies[self.key(px, m)][rows]+ return (np.flatnonzero(adjacency.getnnz(axis=0)),+ selected_flat[adjacency.getnnz(axis=1) > 0])+ def score(self, selected_flat): rows = np.searchsorted(self.flat, selected_flat) if len(rows) and ((rows >= len(self.flat)).any() or not np.array_equal(self.flat[rows], selected_flat)):@@ -78,6 +97,61 @@ class CoverageMatcher: return out, arrays +def count_ratio(numerator, denominator):+ """Preserve raw counts, including undefined zero-denominator fractions."""+ return dict(numerator=int(numerator), denominator=int(denominator),+ value=numerator/denominator if denominator else None)+++def staged_reference_coverage(matcher, candidates, priority, surface, final):+ """Saved-set diagnosis only; no candidate extraction or selection is run.++ C/P are None for the General FPS control, rather than empty candidate sets.+ Set differences overlap and must not be summed as causal loss fractions.+ """+ if (candidates is None) != (priority is None):+ raise ValueError('candidate and priority applicability must agree')+ nodes = dict(X=matcher.flat, C=candidates, P=priority, S=surface, F=final)+ hits, stages = {}, {}+ for name, flat in nodes.items():+ if flat is None:+ hits[name] = None+ stages[name] = None+ continue+ ids, matched = matcher.reference_hits(flat)+ hits[name] = set(ids.tolist())+ stages[name] = dict(node_count=len(flat), matched_node_count=len(matched),+ unique_reference_count=len(ids))+ p = np.asarray(priority if priority is not None else [], dtype=np.int64)+ if np.intersect1d(p, surface).size or set(final) != set(p) | set(surface):+ raise ValueError('final nodes must be the disjoint priority/surface union')+ if candidates is not None and not set(p) <= set(candidates):+ raise ValueError('priority nodes outside candidate support')+ v, o = set(range(matcher.nref)), hits['X']+ c, p, s, f = hits['C'], hits['P'], hits['S'], hits['F']+ if not f <= o or (c is not None and not c <= o):+ raise AssertionError('covered references outside observable references')+ if f != (p or set()) | s:+ raise AssertionError('final reference union differs from priority/surface')+ differences = {'V_minus_O': v-o, 'O_minus_F': o-f}+ if c is not None:+ differences.update(O_minus_C=o-c, C_minus_P=c-p, C_minus_F=c-f,+ P_intersect_S=p&s, S_minus_P=s-p, S_minus_C=s-c,+ C_minus_P_intersect_S=(c-p)&s)+ else:+ differences.update({key: None for key in ('O_minus_C', 'C_minus_P', 'C_minus_F',+ 'P_intersect_S', 'S_minus_P', 'S_minus_C', 'C_minus_P_intersect_S')})+ coverage = dict(observation=count_ratio(len(o), len(v)))+ for name, key in [('C', 'candidate'), ('P', 'priority'), ('S', 'surface'), ('F', 'final_retention')]:+ coverage[key] = count_ratio(len(hits[name]), len(o)) if hits[name] is not None else None+ return dict(stages=stages, coverage=coverage,+ gt_final_coverage=count_ratio(len(f), len(v)),+ reference_ids={k: sorted(ids) if ids is not None else None+ for k, ids in dict(V=v, O=o, **hits).items()},+ differences={k: dict(count=len(ids), reference_ids=sorted(ids)) if ids is not None else None+ for k, ids in differences.items()})++ def evaluation_context(frame, evidence, gt, camera, robot_ids): """Reuse unchanged Task02 visible seam/rim definition; GT read after extraction.""" truths, regions, maps = real_truth(frame, evidence.frame, gt, camera)diff --git a/visual/runtime/test/test_sampling_evaluation.py b/visual/runtime/test/test_sampling_evaluation.pyindex 798172c..6975e66 100644--- a/visual/runtime/test/test_sampling_evaluation.py+++ b/visual/runtime/test/test_sampling_evaluation.py@@ -13,7 +13,10 @@ from visual.runtime.rgbd import PEG, BOX from visual.runtime.sampling import extract_sampling_evidence, sample_points, SamplingConfig from visual.runtime.test.normal_diagnostics import synthetic_frame, oracle, box_primitives, rim_region from visual.runtime.test.run_structural_edges import rim_reference-from visual.runtime.test.sampling_evaluation import CoverageMatcher+from visual.runtime.test.sampling_evaluation import CoverageMatcher, staged_reference_coverage+from visual.runtime.test.run_rim_bottleneck import (+ geometry_evidence, validate_saved_selection, occupancy, source_contract,+) from visual.runtime.test.run_sampling import conditions, evaluate @@ -110,4 +113,135 @@ class SamplingEvaluationTests(unittest.TestCase): with self.assertRaises(ValueError):evaluate(episode,masks,root/'out',camera='camera',selected=(),make_plots=False) +class StagedCoverageTests(unittest.TestCase):+ def fixture(self):+ mask = np.zeros((16, 16), bool)+ mask[5, [3, 6, 10]] = True+ k = np.array([[1000., 0, 8], [0, 1000., 8], [0, 0, 1]])+ frame = synthetic_frame(np.full((16, 16), .3, np.float32), k, mask)+ geometry = build_organized_geometry(frame)+ uv = np.array([[2., 5], [4.5, 5], [7., 5], [10., 5]])+ xyz = np.tile(geometry.xyz[5, 6], (4, 1))+ matcher = CoverageMatcher(geometry, PEG, (uv, xyz))+ return frame, geometry, matcher++ def test_reference_overlap_union_and_surface_outside_candidates(self):+ _, _, matcher = self.fixture()+ c, p, s, f = [np.array(a, np.int64) for a in ([83, 86], [83], [86, 90], [90, 83, 86])]+ row = staged_reference_coverage(matcher, c, p, s, f)+ self.assertEqual(row['reference_ids']['C'], [0, 1, 2])+ self.assertEqual(row['reference_ids']['P'], [0, 1])+ self.assertEqual(row['reference_ids']['S'], [1, 2, 3])+ self.assertEqual(row['reference_ids']['F'], [0, 1, 2, 3])+ self.assertEqual(row['stages']['C'], dict(node_count=2, matched_node_count=2, unique_reference_count=3))+ expected = dict(V_minus_O=0, O_minus_C=1, C_minus_P=1, C_minus_F=0,+ P_intersect_S=1, S_minus_P=2, S_minus_C=1,+ C_minus_P_intersect_S=1, O_minus_F=0)+ self.assertEqual({k: v['count'] for k, v in row['differences'].items()}, expected)+ self.assertEqual(row['coverage']['candidate'], dict(numerator=3, denominator=4, value=.75))++ def test_two_different_nodes_cannot_satisfy_one_reference_pair(self):+ frame, _, _ = self.fixture()+ intrinsic = frame.intrinsic.copy(); intrinsic[0, 0] = 100.+ geometry = build_organized_geometry(replace(frame, intrinsic=intrinsic))+ # Node 83 satisfies 2D only; node 90 satisfies 3D only.+ matcher = CoverageMatcher(geometry, PEG, (np.array([[3., 5]]), geometry.xyz[5, 10][None]))+ ids, matched = matcher.reference_hits(np.array([83, 90]))+ self.assertEqual((len(ids), len(matched)), (0, 0))++ def test_empty_points_zero_observation_and_zero_visible(self):+ frame, geometry, matcher = self.fixture()+ empty = np.array([], np.int64)+ row = staged_reference_coverage(matcher, empty, empty, empty, empty)+ self.assertEqual(row['coverage']['final_retention'], dict(numerator=0, denominator=4, value=0.))+ geometry = build_organized_geometry(replace(frame, masks={PEG: np.zeros_like(frame.depth, bool)}))+ for refs in ((matcher.ref_uv, matcher.ref_xyz), (np.empty((0, 2)), np.empty((0, 3)))):+ row = staged_reference_coverage(CoverageMatcher(geometry, PEG, refs), empty, empty, empty, empty)+ self.assertEqual(row['coverage']['final_retention'], dict(numerator=0, denominator=0, value=None))+ self.assertEqual(row['coverage']['observation']['numerator'], 0)+ self.assertEqual(row['coverage']['observation']['denominator'], len(refs[0]))++ def test_general_fps_candidate_and_priority_are_inapplicable(self):+ _, _, matcher = self.fixture()+ flat = matcher.flat+ row = staged_reference_coverage(matcher, None, None, flat, flat)+ for name in ('C', 'P'):+ self.assertIsNone(row['stages'][name])+ self.assertIsNone(row['coverage']['candidate'])+ self.assertIsNone(row['coverage']['priority'])+ self.assertIsNone(row['differences']['O_minus_C'])+ self.assertEqual(row['coverage']['surface'], row['coverage']['final_retention'])++ def test_invalid_nodes_and_non_partition_are_rejected(self):+ _, _, matcher = self.fixture()+ for flat in (np.array([0]), np.array([83, 83]), np.array([256]), np.array([-1]), np.array([83.])):+ with self.assertRaises(ValueError):+ matcher.reference_hits(flat)+ with self.assertRaises(ValueError):+ staged_reference_coverage(matcher, np.array([83]), np.array([86]), np.array([90]), np.array([86, 90]))+ with self.assertRaises(ValueError):+ staged_reference_coverage(matcher, matcher.flat, np.array([83]), np.array([83, 90]), np.array([83, 90]))+ with self.assertRaises(ValueError):+ staged_reference_coverage(matcher, matcher.flat, np.array([83]), np.array([90]), matcher.flat)++ def test_geometry_alignment_invalid_depth_overlap_and_pixel_centres(self):+ frame, _, _ = self.fixture()+ depth = frame.depth.copy()+ depth[5, 6] = 0+ depth[2, 2] = np.nan+ box = np.zeros_like(depth, bool)+ box[5, 10] = True # ambiguous in BOTH masks+ frame = replace(frame, depth=depth, masks={PEG: frame.masks[PEG], BOX: box})+ evidence = geometry_evidence(frame)+ geometry = evidence.frame.geometry+ self.assertEqual(np.flatnonzero(geometry.observed_mask(PEG)).tolist(), [83])+ self.assertFalse(geometry.observed_mask(BOX).any())+ self.assertTrue(np.isnan(geometry.xyz[5, 6]).all())+ z = float(depth[5, 3])+ np.testing.assert_allclose(geometry.xyz[5, 3], [(3.5-8)*z/1000, (5.5-8)*z/1000, z], rtol=1e-7)+ # Minimal evaluation adapter has exactly the existing validity ROI field.+ from visual.runtime.geometry import compute_geometric_features, GeometryParameters+ for oid in (PEG, BOX):+ features = compute_geometric_features(geometry, oid, np.full_like(geometry.xyz, np.nan),+ np.zeros_like(depth, bool), GeometryParameters())+ np.testing.assert_array_equal(evidence.frame.objects[oid].depth_validity_boundary,+ features.depth_validity_boundary)+ key = 'saved'+ archive = {'source_frame': np.array(frame.source_frame), 'shape': np.array(depth.shape),+ key+'/flat_index': np.array([83]), key+'/pixels_vu': np.array([[5, 3]]),+ key+'/object_id': np.array([PEG]), key+'/points': geometry.xyz[5, 3][None].copy(),+ key+'/priority_selected': np.array([False]), key+'/depth_priority_selected': np.array([False])}+ self.assertTrue(validate_saved_selection(archive, key, frame, geometry)['xyz_exact'])+ for field, corrupted in [('points', archive[key+'/points']+.001), ('pixels_vu', np.array([[5, 4]])),+ ('object_id', np.array([BOX]))]:+ with self.assertRaises((ValueError, AssertionError)):+ validate_saved_selection(dict(archive, **{key+'/'+field: corrupted}), key, frame, geometry)+ with self.assertRaises(ValueError):+ validate_saved_selection(dict(archive, source_frame=np.array(frame.source_frame+1)), key, frame, geometry)++ def test_negative_union_deduplicates_and_depth_bands_cover_paths(self):+ frame, _, matcher = self.fixture()+ a = np.zeros_like(frame.depth, bool); b = a.copy()+ a[5, [3, 6]] = True; b[5, [6, 10]] = True+ row = occupancy(frame, dict(X=matcher.flat, C=None, P=None, S=matcher.flat, F=matcher.flat), dict(a=a, b=b))+ roi = row['negative_roi']+ self.assertEqual(roi['a']['F']['count']+roi['b']['F']['count'], 4)+ self.assertEqual(roi['known_negative_union']['F']['count'], 3)+ self.assertIsNone(roi['known_negative_union']['P'])+ self.assertEqual(sum(v['numerator'] for v in row['depth_quantile_occupancy']['F'].values()), 3)++ def test_historical_evaluation_changes_fail_closed(self):+ import hashlib+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ relative = 'visual/runtime/test/sampling_evaluation.py'+ snapshot = root/'evaluated_source'/relative+ snapshot.parent.mkdir(parents=True)+ source = Path(relative).read_text().replace('<= m', '<= m*2', 1)+ snapshot.write_text(source)+ config = {'source_sha256': {relative: hashlib.sha256(snapshot.read_bytes()).hexdigest()}}+ with self.assertRaisesRegex(ValueError, 'historical evaluation definition'):+ source_contract(root, config)++ if __name__=='__main__':unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146"""Causal SAM2 -> PCA5 timing, excluding cached initial grounding and startup.
Only currently implemented geometry is produced; final Graph sampling/edgesare deliberately not fabricated. Reports queue growth at 20Hz without drops."""from __future__ import annotationsimport argparsefrom dataclasses import replaceimport importlibimport jsonfrom pathlib import Pathimport sysimport time
import numpy as npimport torch
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.rgbd import iter_saved_rgbdfrom visual.runtime.tracking import SAM2Trackerfrom visual.scripts.stream_v1 import CausalFrames, StreamTrackerfrom visual.runtime.test.pca_optimized import process_optimizedfrom visual.runtime.test.pca_torch import TorchPCA5from visual.runtime.test.normal_diagnostics import statsfrom visual.runtime.test.run_normal_diagnostics import save_json
class DeviceStreamTracker(StreamTracker): """Reuse causal tracking operations; supply the predictor's actual device.
The legacy StreamTracker initialization hardcodes CausalFrames' CUDA default. This harness only adapts its frame-buffer construction for CPU. """ def _init_state(self, rgb0): mod = importlib.import_module(type(self.p).__module__) h, w = rgb0.shape[:2] frames = CausalFrames(self.p.image_size, device=self.p.device, keep=self.keep_frames, preprocess=self.pre) frames.push(rgb0) original = mod.load_video_frames mod.load_video_frames = lambda **kw: (frames, h, w) try: state = self.p.init_state(video_path='<stream>') finally: mod.load_video_frames = original self.frames = frames return state
def benchmark(input_path, masks_path, tracking_path, checkpoint, *, device, count, output_root, backend='eigh', compile_image_encoder=False, cpu_parallel=False, encoder_warmup=0, tracker_warmup_steps=0): if count < 2: raise ValueError('count must include startup and at least one subsequent frame') input_path, masks_path, tracking_path, checkpoint = map(Path, (input_path,masks_path,tracking_path,checkpoint)) frames = list(iter_saved_rgbd(input_path,masks_path))[:count] tracking = json.loads(tracking_path.read_text()) boxes = {i+1:tracking['initial_boxes'][name]['box'] for i,name in enumerate(('peg','box'))} cfg = dict(task='pca5_streaming_budget',device=device,backend=backend,compile_image_encoder=compile_image_encoder,cpu_parallel=cpu_parallel,encoder_warmup=encoder_warmup,tracker_warmup_steps=tracker_warmup_steps,warmup_uses_only_first_rgb=True,frames=len(frames),target_period_ms=50, initial_grounding='cached initial boxes; grounding not run or timed',startup_excluded=True, checkpoint_sha256=digests(checkpoint)[1], input_sha256=digests(input_path)[1], tracker_config=tracking['config'],preprocess='gpu',initial_boxes=boxes, final_graph_handoff_implemented=False,frame_drops=0,geometry='optimized_analytic' if device=='cpu' else 'torch_float64_pca5', clock='scheduled 50ms arrivals; all frames processed causally; queue delay included in arrival-to-geometry-ready', source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in [Path(__file__),REPO/'visual/scripts/stream_v1.py',REPO/'visual/runtime/test/pca_torch.py',REPO/'visual/runtime/test/pca_optimized.py']}) with ExperimentLogger(team='visual',config=cfg,seed=0,model='pca5_causal_stream',job_type='evaluate') as logger: out=Path(output_root)/logger.run_id;out.mkdir(parents=True,exist_ok=False);print('Output:',out,flush=True) if device=='cuda' and not torch.cuda.is_available(): save_json(out/'streaming.json',dict(run_id=logger.run_id,config=cfg,status='not_executed',reason='CUDA unavailable')) logger.link_output(out/'streaming.json',kind='metrics');logger.record(gpu_executed=False);return out torch.set_num_threads(4) start=time.perf_counter() overrides=['++model.compile_image_encoder=True'] if compile_image_encoder else None predictor=SAM2Tracker(device=device,checkpoint=checkpoint,config=tracking['config'],hydra_overrides=overrides).predictor tracker=DeviceStreamTracker(predictor,preprocess='gpu',prune=True,keep_mem=16,keep_frames=2) processor=TorchPCA5(frames[0].intrinsic,frames[0].depth.shape,device=device,backend=backend) if device=='cuda' else None autocast = torch.autocast(device_type='cuda',dtype=torch.bfloat16,enabled=device=='cuda') rows=[];saved_masks=[] def sync(): if device=='cuda':torch.cuda.synchronize() with torch.inference_mode(),autocast: masks=tracker.start(frames[0].rgb,boxes) # Warm only the already available first RGB, without advancing or # resetting tracker state or accessing a future observation. for _ in range(encoder_warmup): predictor.image_encoder(tracker.frames[0][None]) for _ in range(tracker_warmup_steps): tracker.step(frames[0].rgb) if tracker_warmup_steps: tracker.reset() masks=tracker.start(frames[0].rgb,boxes) assert tracker.frames.latest==0 # fresh actual observation state if device=='cpu':process_optimized(replace(frames[0],masks={i-1:m.cpu().numpy() for i,m in masks.items()}),solver='analytic',parallel=cpu_parallel) else:processor(torch.as_tensor(frames[0].depth,device='cuda'),{i-1:m for i,m in masks.items()}) sync();startup=(time.perf_counter()-start)*1000 epoch=time.perf_counter() for idx,frame in enumerate(frames[1:]): arrival=epoch+idx*.05 delay=arrival-time.perf_counter() if delay>0:time.sleep(delay) sync();begin=time.perf_counter() fi,masks=tracker.step(frame.rgb);sync();after_tracking=time.perf_counter() if device=='cpu': masks={i-1:m.detach().cpu().numpy() for i,m in masks.items()};after_transfer=time.perf_counter() geometry=process_optimized(replace(frame,masks=masks),solver='analytic',parallel=cpu_parallel) points=sum(int(f.valid_points.sum()) for f in geometry.objects.values()) else: depth=torch.as_tensor(frame.depth,device='cuda'); masks={i-1:m for i,m in masks.items()};sync();after_transfer=time.perf_counter() geometry=processor(depth,masks) points=None # avoid a timed host reduction/synchronization for reporting sync();end=time.perf_counter() saved_masks.append(masks) rows.append(dict(source_frame=frame.source_frame,tracker_frame=fi,queue_wait_ms=(begin-arrival)*1000, tracking_ms=(after_tracking-begin)*1000,transfer_ms=(after_transfer-after_tracking)*1000, geometry_ms=(end-after_transfer)*1000,service_ms=(end-begin)*1000, arrival_to_geometry_ready_ms=(end-arrival)*1000,observed_points=points)) print('Stream frame',frame.source_frame,'service_ms',round(rows[-1]['service_ms'],2),flush=True) elapsed=time.perf_counter()-epoch tracker.reset() # Keep references during timing; transfer/serialize the masks afterward. arrays={name:np.stack([(m[i].detach().cpu().numpy() if device=='cuda' else m[i]) for m in saved_masks]) for name,i in [('peg',0),('box',1)]} np.savez_compressed(out/'tracked_masks.npz',source_frame=np.array([r['source_frame'] for r in rows]),**arrays) logger.link_output(out/'tracked_masks.npz',kind='trajectory') keys=['tracking_ms','transfer_ms','geometry_ms','service_ms','queue_wait_ms','arrival_to_geometry_ready_ms'] summary={k:stats([r[k] for r in rows]) for k in keys} data=dict(run_id=logger.run_id,config=cfg,status='executed',startup_excluded_ms=startup,summary=summary,frames=rows, achieved_hz=len(rows)/elapsed,service_over_50ms=sum(r['service_ms']>50 for r in rows), arrival_deadline_misses=sum(r['arrival_to_geometry_ready_ms']>50 for r in rows), final_graph_handoff_measured=False,scope='RGB available to implemented geometry ready; sampling/edges/Graph packaging absent') save_json(out/'streaming.json',data);logger.link_output(out/'streaming.json',kind='metrics') logger.log(summary,prefix='eval/streaming');logger.record(gpu_executed=device=='cuda',initial_grounding_excluded=True) return out
def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') p.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') p.add_argument('--tracking',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/tracking.json') p.add_argument('--checkpoint',type=Path,default=REPO/'visual/checkpoints/sam2.1_hiera_small.pt') p.add_argument('--device',choices=['cpu','cuda'],default='cpu');p.add_argument('--frames',type=int,default=12) p.add_argument('--backend',choices=['eigh','triton','triton_fused'],default='eigh') p.add_argument('--compile-image-encoder',action='store_true') p.add_argument('--cpu-parallel',action='store_true') p.add_argument('--encoder-warmup',type=int,default=0) p.add_argument('--tracker-warmup-steps',type=int,default=0) p.add_argument('--out',type=Path,default=REPO/'visual/results/pca_optimization') a=p.parse_args();print(benchmark(a.input,a.masks,a.tracking,a.checkpoint,device=a.device,count=a.frames,output_root=a.out,backend=a.backend,compile_image_encoder=a.compile_image_encoder,cpu_parallel=a.cpu_parallel,encoder_warmup=a.encoder_warmup,tracker_warmup_steps=a.tracker_warmup_steps))
if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""Observation-only adjacent-pixel evidence promoted unchanged from Task 02-C.
These are independent causes, never final structural labels or graph edges."""from dataclasses import dataclassimport numpy as npfrom visual.runtime.geometry import GeometryParametersPARAMETERS = GeometryParameters()
@dataclass(frozen=True)class PairEvidence: shape: tuple pixels: np.ndarray # [P,2] source flat indices, right/down neighbour once supported: np.ndarray # [P,2] unambiguous observed object endpoint mask_boundary: np.ndarray invalid_depth_boundary: np.ndarray # XOR depth validity, not zero-depth jump overlap: np.ndarray # [P,2], ambiguous tracker membership signed_depth_delta_m: np.ndarray # z(second)-z(first), NaN unless both valid depth_jump: np.ndarray normal_angle_deg: np.ndarray # NaN unless both normals available near_endpoint: np.ndarray # local pair endpoint 0/1, -1 unless a depth jump far_endpoint: np.ndarray
def endpoint_mask(self, selected, side=None): result = np.zeros(np.prod(self.shape), bool) for k in (0, 1): keep = selected & self.supported[:, k] if side is not None: keep &= side == k result[self.pixels[keep, k]] = True return result.reshape(self.shape)
def candidates(self, threshold): if not np.isfinite(threshold) or threshold < 0: raise ValueError('angle threshold must be finite and nonnegative') orientation = self.endpoint_mask(self.normal_angle_deg > threshold) depth = self.endpoint_mask(self.depth_jump) return dict(orientation=orientation, depth=depth, union=orientation | depth, occluding=self.endpoint_mask(self.depth_jump, self.near_endpoint), occluded=self.endpoint_mask(self.depth_jump, self.far_endpoint), invalid=self.endpoint_mask(self.invalid_depth_boundary), mask=self.endpoint_mask(self.mask_boundary))
def pair_evidence(geometry, object_id, normals, normal_valid, parameters=PARAMETERS): """Preserve all adjacent pairs touching the raw object mask, even invalids.
Mask transition, invalid depth and overlap flags are independent. An external finite-depth neighbour is retained to determine jump direction. Its XYZ is never included as an object normal support or an object candidate point. """ shape = geometry.valid_depth.shape indices = np.arange(np.prod(shape), dtype=np.int32).reshape(shape) mask = geometry.object_masks[object_id] support = geometry.observed_mask(object_id) parts = [] for a, b in (((slice(None), slice(None, -1)), (slice(None), slice(1, None))), ((slice(None, -1), slice(None)), (slice(1, None), slice(None)))): keep = mask[a] | mask[b] parts.append(np.column_stack((indices[a][keep], indices[b][keep]))) pixels = np.concatenate(parts) valid = geometry.valid_depth.ravel()[pixels] both = valid.all(1) z = geometry.xyz[..., 2].ravel()[pixels] delta = np.full(len(pixels), np.nan, np.float32) delta[both] = z[both, 1]-z[both, 0] jump = np.zeros(len(pixels), bool) jump[both] = np.abs(delta[both]) > (parameters.depth_jump_abs_m + parameters.depth_jump_rel*np.min(z[both], axis=1)) nv = normal_valid.ravel()[pixels].all(1) angles = np.full(len(pixels), np.nan, np.float32) n = normals.reshape(-1, 3)[pixels[nv]] angles[nv] = np.rad2deg(np.arctan2(np.linalg.norm(np.cross(n[:, 0], n[:, 1]), axis=1), np.einsum('ij,ij->i', n[:, 0], n[:, 1]))) near = np.full(len(pixels), -1, np.int8) near[jump] = np.argmin(z[jump], axis=1).astype(np.int8) far = np.where(jump, 1-near, -1).astype(np.int8) return PairEvidence(shape, pixels, support.ravel()[pixels], np.logical_xor(mask.ravel()[pixels[:, 0]], mask.ravel()[pixels[:, 1]]), valid[:, 0] ^ valid[:, 1], geometry.overlap_mask.ravel()[pixels], delta, jump, angles, near, far)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Task03-E contracts; FPS inputs are synthetic, real replay belongs to runner."""import copyimport inspectfrom pathlib import Pathfrom types import SimpleNamespaceimport unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.geometry import OrganizedGeometryfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_priority_fps_metric_control as controlfrom visual.runtime.test.sampling_evaluation import CoverageMatcher, staged_reference_coverage
def synthetic_case(): flat=np.arange(120,dtype=np.int64) points=np.column_stack((np.sin(flat*.21),np.cos(flat*.15),flat*.02)).astype(np.float32) candidates=flat[::2] return dict(candidate_flat=candidates,candidate_xyz=points[::2].copy(),support_flat=flat, support_xyz=points,first=8,seed=0,budget=70,saved_flat=flat[:70], saved_features={'normals':points[:70].copy(),'flag':flat[:70]%3==0})
class MetricSelectionTests(unittest.TestCase): def test_metric_squared_distance_formula_and_original_unchanged(self): points=np.array([[0,0,1],[3,4,9],[1,5,2]],np.float32); before=points.copy() for weight in control.LAMBDAS: metric=control.metric_coordinates(points,weight) self.assertFalse(np.shares_memory(metric,points)) diff=points.astype(float)[:,None]-points.astype(float)[None,:] expected=diff[...,0]**2+diff[...,1]**2+weight*diff[...,2]**2 np.testing.assert_array_equal(((metric[:,None]-metric[None,:])**2).sum(-1),expected) np.testing.assert_array_equal(points,before) with self.assertRaises(ValueError): control.metric_coordinates(points,.5)
def test_zero_weight_z_change_does_not_change_priority_with_xy_ties(self): case=synthetic_case(); points=case['candidate_xyz'].copy(); points[2,:2]=points[3,:2] altered=points.copy(); altered[:,2]=np.arange(len(points))**3 a=fps_indices(control.metric_coordinates(points,0.),32,initial=[4]) b=fps_indices(control.metric_coordinates(altered,0.),32,initial=[4]) np.testing.assert_array_equal(a,b) # Exact XY ties retain existing source-row argmax behaviour. tie=np.zeros((40,3)); tie[:,2]=np.arange(40) np.testing.assert_array_equal(fps_indices(control.metric_coordinates(tie,0.),4,initial=[8]),[8,0,1,2])
def test_lambda_one_matches_existing_priority_and_seeded_surface(self): case=synthetic_case(); original=copy.deepcopy(case) p=fps_indices(case['candidate_xyz'],32,initial=[4]) initial=np.searchsorted(case['support_flat'],case['candidate_flat'][p]) final=fps_indices(case['support_xyz'],70,initial=initial) selected=control.select(case,1.) np.testing.assert_array_equal(selected['P'],case['candidate_flat'][p]) np.testing.assert_array_equal(selected['F'],case['support_flat'][final]) for field in ('candidate_flat','candidate_xyz','support_flat','support_xyz'): np.testing.assert_array_equal(case[field],original[field])
def test_all_weights_fixed_initial_quota_original_xyz_surface_metric(self): case=synthetic_case(); original=copy.deepcopy(case) for w in control.LAMBDAS: with patch.object(control,'fps_indices',wraps=fps_indices) as calls: chosen=control.select(case,w) self.assertEqual(calls.call_count,2) np.testing.assert_array_equal(calls.call_args_list[0].args[0],control.metric_coordinates(case['candidate_xyz'],w)) np.testing.assert_array_equal(calls.call_args_list[1].args[0],case['support_xyz']) self.assertEqual(chosen['P'][0],case['first']); self.assertEqual(len(chosen['P']),32) self.assertEqual(len(chosen['S']),38); self.assertEqual(len(chosen['F']),70) self.assertEqual(len(np.unique(chosen['F'])),70) self.assertFalse(np.intersect1d(chosen['P'],chosen['S']).size) np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][chosen['F']]) for field in ('candidate_flat','candidate_xyz','support_flat','support_xyz'): np.testing.assert_array_equal(case[field],original[field])
def test_every_gate_required_before_either_control(self): cases={k:synthetic_case() for k in ('S2/peg','S2/box','S3/peg','S3/box')} for key in cases: gate={k:dict(status='PASS') for k in cases}; gate[key]['status']='FAIL' with patch.object(control,'select',side_effect=AssertionError('must not select')): with self.assertRaises(ValueError): control.execute_controls(cases,gate) with patch.object(control,'select',side_effect=AssertionError('must not select')): with self.assertRaises(ValueError): control.execute_controls(cases,{})
def test_gt_annotations_and_segment_labels_cannot_affect_selection(self): case=synthetic_case(); before=control.select(case,.25) # Change annotations/segment labels while holding selection inputs fixed. annotations=[dict(gt=np.ones((4,3)),segments=['a']*4),dict(gt=np.full((4,3),999),segments=['ambiguous']*4)] for annotation in annotations: case_with_extra=dict(case,**annotation) after=control.select(case_with_extra,.25) np.testing.assert_array_equal(before['F'],after['F']) np.testing.assert_array_equal(before['xyz'],after['xyz']) self.assertEqual(tuple(inspect.signature(control.select).parameters),('case','weight')) with self.assertRaises(TypeError): control.select(case,.25,gt={})
def test_feature_gather_exact_only_available_rows_no_placeholder(self): case=synthetic_case(); before=copy.deepcopy(case) available,positions,features=control.feature_rows(case,np.array([8,100,4,119,20])) np.testing.assert_array_equal(available,[True,False,True,False,True]) np.testing.assert_array_equal(positions,[0,2,4]) for name,value in features.items(): np.testing.assert_array_equal(value,case['saved_features'][name][[8,4,20]]) np.testing.assert_array_equal(case['saved_features'][name],before['saved_features'][name])
class LocalEvaluationTests(unittest.TestCase): def test_joint_matching_same_pair_dedup_and_staged_union(self): xyz=np.zeros((1,10,3),np.float32); xyz[0,3]=[.1,0,0] geometry=OrganizedGeometry(xyz,np.ones((1,10),bool),{0:np.ones((1,10),bool)},np.zeros((1,10),bool)) matcher=CoverageMatcher(geometry,0,(np.array([[0.,0.],[7.,0.],[7.5,0.]]),np.array([[.1,0,0],[0,0,0],[0,0,0]]))) ids,hit=matcher.reference_hits(np.array([0,3])) self.assertFalse(len(ids)); self.assertFalse(len(hit)) # One node covers two refs, and multiple nodes cover those same two refs. p=np.array([7]); s=np.array([6,8]); f=np.r_[p,s] row=staged_reference_coverage(matcher,f,p,s,f) self.assertEqual(row['stages']['P']['matched_node_count'],1) self.assertEqual(row['stages']['P']['unique_reference_count'],2) self.assertEqual(row['stages']['S']['matched_node_count'],2) self.assertEqual(row['differences']['S_minus_P']['count'],0) self.assertEqual(row['differences']['P_intersect_S']['count'],2) self.assertEqual(row['reference_ids']['F'],[1,2])
def test_peg_face_pair_endpoint_ambiguity_and_nonphysical_order_na(self): face=np.array([[0,0,2],[0,5,2]],np.int8); visible=np.ones_like(face,bool) seam=np.array([[False,True,True],[True,True,True]]) uv=np.column_stack(np.nonzero(seam))[:,::-1] labels,members=control.peg_labels(face,visible,seam,uv) self.assertIn('ambiguous',labels) self.assertTrue(any(len(m)>1 for m in members)) r=control.segment_spacing([.03,.01,.02],[False,True,True],[.015],order_verified=False) self.assertEqual(r['status'],'N/A') self.assertNotIn('actual_inter_node_gap_mm',r)
def test_rim_line_identity_from_existing_transform_and_corner_ambiguity(self): # Known line points with shuffled reference order. Corner stays ambiguous. xyz=np.array([[.1,-.01,0],[.1,.005,-.01],[.1,-.01,-.01],[.1,-.01,.005]]) pose=np.array([0,0,0,1,0,0,0],float) labels,specs,_=control.rim_labels(xyz,np.eye(4),pose,pose,.01) self.assertEqual(labels.tolist(),['rim_axis1_-1','rim_axis2_-1','ambiguous','rim_axis1_-1']) self.assertTrue(specs['rim_axis1_-1']['order_verified'])
def test_spacing_uses_actual_node_projections_not_covered_reference_centres(self): row=control.segment_spacing(np.array([.03,.01,.02,.04]),np.array([False,True,False,True]), np.array([.012,.038]),order_verified=True) np.testing.assert_allclose(row['actual_inter_node_gap_mm'],[26]) self.assertAlmostEqual(row['start_tail_to_first_node_mm'],2) self.assertAlmostEqual(row['end_tail_from_last_node_mm'],2) self.assertEqual(row['missing_reference_runs'][0]['reference_count'],2) self.assertAlmostEqual(row['missing_reference_run_total_span_mm'],10) self.assertIsNone(row['continuous_unpreserved_length_mm']) self.assertEqual(control.segment_spacing([.01],[True],[],order_verified=True)['status'],'N/A')
if __name__=='__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""Organized, observation-only NumPy geometry diagnostics (Task 01).
All arrays retain the source (v, u) image layout. This is an internal baseline,not structural classification, sampling, or the final Vision--Graph interface.No RGB values, object GT, erosion, outlier removal, or reconstruction are used."""
from __future__ import annotations
from dataclasses import dataclassfrom time import perf_counter
import numpy as np
from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFrame
@dataclass(frozen=True)class GeometryParameters: """Adjacent z jump > abs + rel * min(z1, z2), in metres.
These are diagnostic baseline thresholds, not edge-classification settings. The same gate prevents a normal stencil from crossing a detected z jump. """
depth_jump_abs_m: float = 0.01 depth_jump_rel: float = 0.02
def __post_init__(self) -> None: values = (self.depth_jump_abs_m, self.depth_jump_rel) if not np.isfinite(values).all() or min(values) < 0: raise ValueError("depth jump thresholds must be finite and nonnegative")
@dataclass(frozen=True)class OrganizedGeometry: """CV-camera XYZ in metres; invalid depth has three NaNs, never a point.
``xyz[v, u]`` corresponds to source pixel centre ``(u+.5, v+.5)``. Finite background geometry is retained, but only ``observed_mask(id)`` may be used as that object's points. Overlapping tracker masks are preserved and marked ambiguous; those pixels are excluded from BOTH object supports. """
xyz: np.ndarray valid_depth: np.ndarray object_masks: dict[int, np.ndarray] overlap_mask: np.ndarray
def observed_mask(self, object_id: int) -> np.ndarray: return self.object_masks[object_id] & self.valid_depth & ~self.overlap_mask
@dataclass(frozen=True)class GeometricFeatures: """Pixel-aligned diagnostics for one object, without semantic edge labels.
Unavailable floating features are NaN and have explicit validity masks. ``depth_jump_m`` compares a supported centre to ANY finite 4-neighbour, including other labels/background; it measures observation discontinuity. Mask, invalid-depth, and image boundaries are separate diagnostic flags. ``mask_boundary`` can include invalid/ambiguous mask pixels: it is NOT a point selection. Geometry selection always requires ``valid_points``. Normal variation is the maximum angle (radians) to supported same-object 4-neighbour normals; even a smooth curved surface can have a large value. """
object_mask: np.ndarray valid_points: np.ndarray normals: np.ndarray normal_valid: np.ndarray depth_jump_m: np.ndarray depth_pair_valid: np.ndarray depth_discontinuity: np.ndarray mask_boundary: np.ndarray depth_validity_boundary: np.ndarray image_boundary: np.ndarray normal_variation_rad: np.ndarray normal_variation_valid: np.ndarray normal_neighbor_count: np.ndarray
@dataclass(frozen=True)class GeometryFrame: source_frame: int camera: str frame_idx: int | None timestamp: float | None geometry: OrganizedGeometry objects: dict[int, GeometricFeatures] timings_ms: dict[str, float]
def build_organized_geometry(frame: TrackedRGBDFrame) -> OrganizedGeometry: """Adapt pointcloud.backproject's pixel-centre equations to dense layout.
Kept NumPy-only rather than importing the legacy plotting/SciPy module. No depth is filtered, filled, smoothed, or selected before feature analysis. """ depth = np.asarray(frame.depth) if depth.ndim != 2 or not min(depth.shape) or not np.issubdtype(depth.dtype, np.floating): raise ValueError("depth must be a nonempty floating point (H,W) array in metres") intrinsic = np.asarray(frame.intrinsic, dtype=np.float64) if (intrinsic.shape != (3, 3) or not np.isfinite(intrinsic).all() or intrinsic[0, 0] <= 0 or intrinsic[1, 1] <= 0): raise ValueError("intrinsic must be finite (3,3) with positive focal lengths") # The legacy equations assume the standard zero-skew CV pinhole intrinsic. if not np.allclose(intrinsic[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1]): raise ValueError("intrinsic must use the standard zero-skew CV pinhole form") if set(frame.masks) - {PEG, BOX}: raise ValueError("unknown output object ID; expected PEG=0 or BOX=1") masks = {} for object_id in (PEG, BOX): mask = np.asarray(frame.masks.get(object_id, np.zeros(depth.shape, dtype=bool))) if mask.shape != depth.shape or mask.dtype != np.bool_: raise ValueError("object masks must be boolean (H,W) arrays matching depth") masks[object_id] = mask.copy() valid = np.isfinite(depth) & (depth > 0) xyz = np.full((*depth.shape, 3), np.nan, dtype=np.float32) v, u = np.nonzero(valid) # Exactly the equations in visual/scripts/pointcloud.py::backproject. z = depth[v, u] xyz[v, u, 0] = (u + 0.5 - intrinsic[0, 2]) * z / intrinsic[0, 0] xyz[v, u, 1] = (v + 0.5 - intrinsic[1, 2]) * z / intrinsic[1, 1] xyz[v, u, 2] = z if not np.isfinite(xyz[valid]).all(): raise ValueError("finite positive depth/intrinsic must yield representable float32 XYZ") return OrganizedGeometry(xyz, valid, masks, masks[PEG] & masks[BOX])
def _pairs(): """Each in-image horizontal/vertical pair once; no wrap or padded neighbours.""" yield (slice(None), slice(None, -1)), (slice(None), slice(1, None)) yield (slice(None, -1), slice(None)), (slice(1, None), slice(None))
def _jump(z1: np.ndarray, z2: np.ndarray, parameters: GeometryParameters) -> np.ndarray: # Inputs have invalid z replaced by zero by callers, avoiding NaN/Inf math. return np.abs(z1 - z2) > ( parameters.depth_jump_abs_m + parameters.depth_jump_rel * np.minimum(z1, z2) )
def estimate_surface_normals( geometry: OrganizedGeometry, object_id: int, parameters: GeometryParameters,) -> tuple[np.ndarray, np.ndarray]: """Central cross product from a full, same-object 5-pixel (+) stencil.
Centre and four neighbours must have unambiguous valid depth, and none of the four centre-to-neighbour pairs may exceed the z-jump gate. No one-sided fallback or extrapolation is performed at holes, mask/image borders, or tiny fragments. Unit normals point towards the camera (n dot XYZ <= 0). """ xyz = geometry.xyz normals = np.full_like(xyz, np.nan) normal_valid = np.zeros(geometry.valid_depth.shape, dtype=bool) if min(normal_valid.shape) < 3: return normals, normal_valid support = geometry.observed_mask(object_id) centre = (slice(1, -1), slice(1, -1)) neighbours = ((slice(1, -1), slice(None, -2)), (slice(1, -1), slice(2, None)), (slice(None, -2), slice(1, -1)), (slice(2, None), slice(1, -1))) usable = support[centre].copy() z = np.where(geometry.valid_depth, xyz[..., 2], 0) for neighbour in neighbours: usable &= support[neighbour] & ~_jump(z[centre], z[neighbour], parameters) # Compute only complete stencils, so invalid XYZ never enters a cross product. v, u = np.nonzero(usable) v, u = v + 1, u + 1 dx = xyz[v, u + 1].astype(np.float64) - xyz[v, u - 1] dy = xyz[v + 1, u].astype(np.float64) - xyz[v - 1, u] cross = np.cross(dx, dy) length = np.linalg.norm(cross, axis=1) good = np.isfinite(length) & (length > 0) v, u, cross = v[good], u[good], cross[good] / length[good, None] cross[np.einsum("ij,ij->i", cross, xyz[v, u]) > 0] *= -1 normals[v, u] = cross.astype(np.float32) normal_valid[v, u] = True return normals, normal_valid
def compute_geometric_features( geometry: OrganizedGeometry, object_id: int, normals: np.ndarray, normal_valid: np.ndarray, parameters: GeometryParameters,) -> GeometricFeatures: """Measure separate 4-neighbour boundary causes and local normal variation.""" mask = geometry.object_masks[object_id] support = geometry.observed_mask(object_id) shape = mask.shape z = np.where(geometry.valid_depth, geometry.xyz[..., 2], 0) jump_m = np.zeros(shape, np.float32) pair_valid = np.zeros(shape, bool) discontinuity = np.zeros(shape, bool) mask_boundary = np.zeros(shape, bool) validity_boundary = np.zeros(shape, bool) variation = np.zeros(shape, np.float32) count = np.zeros(shape, np.uint8) for a, b in _pairs(): both_depth = geometry.valid_depth[a] & geometry.valid_depth[b] dz = np.abs(z[a] - z[b]) jumps = both_depth & _jump(z[a], z[b], parameters) both_normals = normal_valid[a] & normal_valid[b] angle = np.zeros(both_normals.shape, np.float32) n1, n2 = normals[a][both_normals], normals[b][both_normals] # atan2 is stable near zero, including identical rounded float32 normals. angle[both_normals] = np.arctan2( np.linalg.norm(np.cross(n1, n2), axis=1), np.einsum("ij,ij->i", n1, n2) ) for p, q in ((a, b), (b, a)): available = support[p] & both_depth pair_valid[p] |= available np.maximum(jump_m[p], np.where(available, dz, 0), out=jump_m[p]) discontinuity[p] |= support[p] & jumps mask_boundary[p] |= mask[p] & ~mask[q] validity_boundary[p] |= support[p] & ~geometry.valid_depth[q] np.maximum(variation[p], angle, out=variation[p]) count[p] += both_normals jump_m[~pair_valid] = np.nan variation_valid = normal_valid & (count > 0) variation[~variation_valid] = np.nan image_boundary = np.zeros(shape, bool) image_boundary[[0, -1], :] = mask[[0, -1], :] image_boundary[:, [0, -1]] = mask[:, [0, -1]] return GeometricFeatures( object_mask=mask, valid_points=support, normals=normals, normal_valid=normal_valid, depth_jump_m=jump_m, depth_pair_valid=pair_valid, depth_discontinuity=discontinuity, mask_boundary=mask_boundary, depth_validity_boundary=validity_boundary, image_boundary=image_boundary, normal_variation_rad=variation, normal_variation_valid=variation_valid, normal_neighbor_count=count, )
def process_geometry( frame: TrackedRGBDFrame, parameters: GeometryParameters | None = None,) -> GeometryFrame: """Process one current observation; no cache, final classification, or RGB features.""" parameters = parameters or GeometryParameters() start = perf_counter() geometry = build_organized_geometry(frame) after_geometry = perf_counter() normals = {object_id: estimate_surface_normals(geometry, object_id, parameters) for object_id in geometry.object_masks} after_normals = perf_counter() features = {object_id: compute_geometric_features( geometry, object_id, *normals[object_id], parameters, ) for object_id in geometry.object_masks} end = perf_counter() timings = dict(geometry=(after_geometry - start) * 1000, normals=(after_normals - after_geometry) * 1000, discontinuity_features=(end - after_normals) * 1000, total=(end - start) * 1000) return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timings)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445"""Evaluate saved tracker masks against GT and write a report plus depth video.
Run from the repository root::
WANDB_MODE=disabled .venv/bin/python visual/runtime/test/run_rgbd.py \ --input visual/data/step2/ep000.npz \ --masks visual/results/runtime_tracking/ep000/masks.npz
GT is read only here, after Visual output has been produced by rgbd.py."""
from __future__ import annotations
import argparseimport base64import hashlibimport htmlimport iofrom itertools import chainimport jsonfrom pathlib import Pathimport sys
import cv2import imageio.v2 as imageioimport numpy as npfrom scipy.spatial import cKDTree
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))
from utils.experiment_logger import ExperimentLogger # noqa: E402from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFrame, iter_saved_rgbd # noqa: E402from visual.scripts.pointcloud import backproject, to_world # noqa: E402
OBJECTS = {"peg": PEG, "box": BOX}COLORS = {"peg": (255, 100, 90), "box": (60, 205, 255)} # RGB
def compare_object(frame: TrackedRGBDFrame, object_id: int, gt_mask: np.ndarray) -> dict: """Compare masks and unfiltered visible surfaces; distances are in mm.
Geometry uses every pixel with finite positive depth, with no erosion, sampling, or pose fitting. Missing surfaces yield None, never zero error. """ predicted = frame.masks[object_id] if gt_mask.shape != frame.depth.shape or gt_mask.dtype != np.bool_: raise ValueError("GT mask must be boolean and match the depth resolution") predicted_pixels, gt_pixels = int(predicted.sum()), int(gt_mask.sum()) tp = int(np.count_nonzero(predicted & gt_mask)) union = predicted_pixels + gt_pixels - tp valid_depth = np.isfinite(frame.depth) & (frame.depth > 0) predicted_valid = predicted & valid_depth gt_valid = gt_mask & valid_depth row = dict( predicted_pixels=predicted_pixels, gt_pixels=gt_pixels, tp=tp, fp=predicted_pixels - tp, fn=gt_pixels - tp, iou=tp / union if union else None, precision=tp / predicted_pixels if predicted_pixels else None, recall=tp / gt_pixels if gt_pixels else None, predicted_depth_pixels=int(predicted_valid.sum()), gt_depth_pixels=int(gt_valid.sum()), predicted_valid_depth_fraction=float(predicted_valid.sum() / predicted_pixels) if predicted_pixels else None, median_depth_m=float(np.median(frame.depth[predicted_valid])) if predicted_valid.any() else None, centroid_error_mm=None, chamfer_mm=None, predicted_to_gt_mm=None, gt_to_predicted_mm=None, ) if predicted_valid.any() and gt_valid.any(): predicted_world = to_world( backproject(frame.depth, frame.intrinsic, predicted_valid), frame.cam2world ) gt_world = to_world( backproject(frame.depth, frame.intrinsic, gt_valid), frame.cam2world ) predicted_distance = cKDTree(gt_world).query(predicted_world)[0] gt_distance = cKDTree(predicted_world).query(gt_world)[0] row.update( centroid_error_mm=float(np.linalg.norm( predicted_world.mean(axis=0, dtype=np.float64) - gt_world.mean(axis=0, dtype=np.float64) ) * 1000), predicted_to_gt_mm=float(predicted_distance.mean() * 1000), gt_to_predicted_mm=float(gt_distance.mean() * 1000), chamfer_mm=float((predicted_distance.mean() + gt_distance.mean()) * 500), ) return row
def statistics(values) -> dict: values = np.asarray([value for value in values if value is not None], dtype=np.float64) if not len(values): return dict(count=0, mean=None, median=None, p95=None) return dict(count=len(values), mean=float(values.mean()), median=float(np.median(values)), p95=float(np.percentile(values, 95)))
def summarize(records: list[dict]) -> dict: summary = {} for name in OBJECTS: rows = [record["objects"][name] for record in records] tp, fp, fn = (sum(row[key] for row in rows) for key in ("tp", "fp", "fn")) visible = [row for row in rows if row["gt_pixels"] > 0] summary[name] = dict( frames=len(rows), visible_frames=len(visible), missed_visible_frames=sum(row["predicted_pixels"] == 0 for row in visible), invisible_frames=len(rows) - len(visible), false_positive_invisible_frames=sum( row["gt_pixels"] == 0 and row["predicted_pixels"] > 0 for row in rows ), geometry_unavailable_visible_frames=sum(row["chamfer_mm"] is None for row in visible), tp=tp, fp=fp, fn=fn, micro_iou=tp / (tp + fp + fn) if tp + fp + fn else None, micro_precision=tp / (tp + fp) if tp + fp else None, micro_recall=tp / (tp + fn) if tp + fn else None, visible_iou=statistics(row["iou"] for row in visible), centroid_error_mm=statistics(row["centroid_error_mm"] for row in rows), chamfer_mm=statistics(row["chamfer_mm"] for row in rows), predicted_to_gt_mm=statistics(row["predicted_to_gt_mm"] for row in rows), gt_to_predicted_mm=statistics(row["gt_to_predicted_mm"] for row in rows), ) return summary
def depth_colors(depth: np.ndarray, near: float, far: float) -> np.ndarray: """Fixed metre scale for the whole video; invalid depth is black.""" if not np.isfinite([near, far]).all() or not 0 <= near < far: raise ValueError("depth range must be finite and satisfy 0 <= near < far") valid = np.isfinite(depth) & (depth > 0) scaled = np.zeros(depth.shape, dtype=np.float32) scaled[valid] = np.clip((depth[valid] - near) / (far - near), 0, 1) colored = cv2.cvtColor( cv2.applyColorMap(np.rint(scaled * 255).astype(np.uint8), cv2.COLORMAP_TURBO), cv2.COLOR_BGR2RGB, ) colored[~valid] = 0 return colored
def _text(image, text, xy, scale=0.55, color=(235, 240, 245)): cv2.putText(image, text, xy, cv2.FONT_HERSHEY_SIMPLEX, scale, color, 1, cv2.LINE_AA)
def _outline(image, mask, color, thickness=1): contours, _ = cv2.findContours(mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(image, contours, -1, color, thickness)
def _number(value, decimals=2): return "n/a" if value is None else f"{value:.{decimals}f}"
def render_depth_frame(frame: TrackedRGBDFrame, gt_masks: dict[str, np.ndarray], metrics: dict, near: float, far: float) -> np.ndarray: """RGB tracking, RGB with depth overlay, and isolated object depth panels.""" colored = depth_colors(frame.depth, near, far) valid = np.isfinite(frame.depth) & (frame.depth > 0) rgb = frame.rgb.copy() overlay = frame.rgb.copy() overlay[valid] = (0.3 * overlay[valid] + 0.7 * colored[valid]).astype(np.uint8) union = frame.masks[PEG] | frame.masks[BOX] isolated = colored.copy() isolated[~union] = 0 for name, object_id in OBJECTS.items(): _outline(rgb, gt_masks[name], (255, 255, 255), 1) _outline(rgb, frame.masks[object_id], COLORS[name], 2) _outline(overlay, frame.masks[object_id], COLORS[name], 2) _outline(isolated, frame.masks[object_id], COLORS[name], 1)
# Keep labels readable for lower-resolution inputs too. panel_width = max(384, frame.rgb.shape[1]) panel_width += panel_width % 2 # H.264 yuv420 needs an even canvas width. panel_height = round(frame.rgb.shape[0] * panel_width / frame.rgb.shape[1]) panel_height += panel_height % 2 header, footer = 64, 144 canvas = np.full((header + panel_height + footer, panel_width * 3, 3), (18, 23, 32), dtype=np.uint8) titles = ("RGB | predicted masks + white GT", "RGB + depth overlay", "Tracked-object depth") for column, (panel, title) in enumerate(zip((rgb, overlay, isolated), titles)): x = column * panel_width canvas[header:header + panel_height, x:x + panel_width] = cv2.resize( panel, (panel_width, panel_height), interpolation=cv2.INTER_NEAREST ) _text(canvas, title, (x + 12, 23), 0.55) timing = f"source row {frame.source_frame} | step {frame.frame_idx} | t={_number(frame.timestamp, 3)}s | {frame.camera}" _text(canvas, timing, (12, 49), 0.5) top = header + panel_height for line, name in enumerate(OBJECTS): row = metrics[name] label = (f"{name.upper()} | IoU {_number(row['iou'], 3)}" f" | Chamfer {_number(row['chamfer_mm'])} mm" f" | centroid {_number(row['centroid_error_mm'])} mm" f" | median z {_number(row['median_depth_m'], 3)} m") _text(canvas, label, (12, top + 23 + 24 * line), 0.55, COLORS[name]) bar_width = panel_width - 32 gradient = np.linspace(near, far, bar_width, dtype=np.float32)[None, :] canvas[top + 66:top + 82, 16:16 + bar_width] = depth_colors( np.repeat(gradient, 16, axis=0), near, far ) _text(canvas, f"{near:.2f} m", (16, top + 104), 0.5) _text(canvas, f"{far:.2f} m", (bar_width - 38, top + 104), 0.5) _text(canvas, "Fixed CV camera z scale | black = invalid / unselected", (panel_width + 12, top + 80), 0.5) _text(canvas, "Colors clip at scale limits; metric calculations use all finite positive depths.", (panel_width + 12, top + 103), 0.46) _text(canvas, "Surface differences use the same recorded depth; no independent depth prediction is evaluated.", (12, top + 130), 0.5) return canvas
def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def write_report(path: Path, data: dict) -> None: """Write one portable HTML containing numerical tables, plots, and raw data.""" import matplotlib.pyplot as plt
records, summary = data["frames"], data["summary"] figure, axes = plt.subplots(2, 1, figsize=(11, 5.5), sharex=True, layout="constrained") steps = [row["source_frame"] for row in records] for name in OBJECTS: color = np.asarray(COLORS[name]) / 255 for axis, key in zip(axes, ("iou", "chamfer_mm")): values = [row["objects"][name][key] for row in records] axis.plot(steps, [np.nan if value is None else value for value in values], label=name, color=color, linewidth=1.5) axis.grid(alpha=0.2) axes[0].set(ylabel="Mask IoU", ylim=(-0.03, 1.03)) axes[1].set(ylabel="Visible-surface Chamfer (mm)", xlabel="Source episode row") axes[0].legend() chart = io.BytesIO() figure.savefig(chart, format="png", dpi=140) plt.close(figure) encoded_chart = base64.b64encode(chart.getvalue()).decode("ascii")
rows = [] for name, values in summary.items(): rows.append("<tr>" + "".join(f"<td>{value}</td>" for value in ( name, f"{values['visible_frames']} / {values['frames']}", _number(values["visible_iou"]["mean"], 4), _number(values["micro_iou"], 4), _number(values["micro_precision"], 4), _number(values["micro_recall"], 4), _number(values["centroid_error_mm"]["mean"]), _number(values["chamfer_mm"]["mean"]), _number(values["chamfer_mm"]["p95"]), values["chamfer_mm"]["count"], values["geometry_unavailable_visible_frames"], values["missed_visible_frames"], values["false_positive_invisible_frames"], )) + "</tr>")
frame_rows = [] for record in records: for name, values in record["objects"].items(): columns = (record["source_frame"], record["frame_idx"], name, values["gt_pixels"], values["predicted_pixels"], _number(values["iou"], 4), _number(values["precision"], 4), _number(values["recall"], 4), values["predicted_depth_pixels"], values["gt_depth_pixels"], _number(values["predicted_valid_depth_fraction"], 4), _number(values["median_depth_m"], 4), _number(values["centroid_error_mm"]), _number(values["chamfer_mm"]), _number(values["predicted_to_gt_mm"]), _number(values["gt_to_predicted_mm"])) frame_rows.append("<tr>" + "".join(f"<td>{value}</td>" for value in columns) + "</tr>")
def table(headers, content): return ("<div class='scroll'><table><thead><tr>" + "".join(f"<th>{header}</th>" for header in headers) + "</tr></thead><tbody>" + "".join(content) + "</tbody></table></div>")
totals = table(("Object", "GT visible / total", "Mean visible IoU", "Micro IoU", "Precision", "Recall", "Mean centroid mm", "Mean Chamfer mm", "p95 Chamfer mm", "3D frames", "Visible, no 3D", "Missed visible", "False positive invisible"), rows) per_frame = table(("Source row", "Step", "Object", "GT px", "Pred px", "IoU", "Precision", "Recall", "Pred depth px", "GT depth px", "Pred valid depth fraction", "Median z m", "Centroid mm", "Chamfer mm", "Pred→GT mm", "GT→pred mm"), frame_rows) # Escaping < also makes the embedded JSON safe when paths contain markup. raw_data = json.dumps(data, allow_nan=False, indent=2).replace("<", "\\u003c") details = html.escape(json.dumps({key: value for key, value in data.items() if key not in ("summary", "frames")}, indent=2)) document = f"""<!doctype html><html lang="ko"><meta charset="utf-8"><title>Visual RGB-D · GT 비교</title><style>body{{font:15px/1.6 system-ui,sans-serif;margin:32px auto;padding:0 24px;max-width:1400px;color:#202a38;background:#f6f8fb}}h1,h2{{line-height:1.25}} .scroll{{overflow:auto;background:white;border:1px solid #dde3ed;border-radius:8px}}table{{border-collapse:collapse;white-space:nowrap;width:100%;font-variant-numeric:tabular-nums}}td,th{{padding:9px 12px;text-align:right;border-bottom:1px solid #e5e9ef}}th{{background:#eaf0f8}}td:first-child,th:first-child{{text-align:left}}img{{max-width:100%;background:white;border-radius:8px}}code,pre{{background:#eaf0f8;padding:2px 5px;border-radius:4px}}pre{{overflow:auto;padding:16px}}details{{margin:20px 0}}.note{{padding:14px 18px;background:#e8eff9;border-left:4px solid #466eb9}}</style><h1>Visual RGB-D · GT 비교</h1><p>{len(records)} frames · {html.escape(data['camera'])} · run <code>{data['run_id']}</code></p><p><a href="depth.mp4">Depth 시각화 영상 (MP4)</a> · 원본 row {steps[0]}–{steps[-1]} · {data['video_fps']:.3f} fps</p><p class="note">예측 mask와 simulator GT segmentation을 비교합니다. 3D 오차는 각 mask를<strong>같은 기록 depth</strong>로 역투영한 가시 표면 간 거리이며, depth 센서 정확도나물체 pose 추정 오차를 의미하지 않습니다. 카메라 calibration과 TCP pose는 기록된 입력입니다.</p><h2>물체별 수치</h2>{totals}<h2>프레임별 변화</h2><img alt="Mask IoU and surface distance by source frame" src="data:image/png;base64,{encoded_chart}"><h2>지표 정의와 분모</h2><ul><li>GT visible: GT mask가 1 pixel 이상인 프레임. Mean visible IoU는 모든 visible 프레임의 평균이며 미검출은 0입니다.</li><li>Micro IoU / Precision / Recall: 전체 프레임의 TP·FP·FN을 합산해 계산합니다. GT가 없는 프레임의 오검출도 FP에 포함합니다.</li><li>GT와 예측이 모두 빈 mask이면 프레임 IoU는 n/a입니다. Precision·Recall도 해당 분모가 0이면 n/a입니다.</li><li>역투영: CV pixel centre (u+0.5, v+0.5), finite depth > 0, metre 단위. 기존 Visual backproject / to_world 함수를 재사용합니다.</li><li>Centroid: 예측·GT 가시 표면 centroid 간 Euclidean 거리(mm). Actor 중심에 대한 pose 오차가 아닙니다.</li><li>Chamfer: 0.5 × (예측→GT 평균 최근접 거리 + GT→예측 평균 최근접 거리), mm. 제곱 거리나 두 방향의 합이 아닙니다.</li><li>3D frames: 양쪽 모두 유효 depth point가 있는 프레임 수. 없는 경우 거리 오차는 n/a이며 평균에 포함하지 않습니다. Visible, no 3D와 Missed visible을 함께 확인해야 합니다.</li><li>3D 거리는 모든 유효 관측점을 사용하며 sampling·erosion·필터링을 하지 않습니다. p95는 프레임별 거리의 95 percentile입니다.</li><li>영상의 depth 범위는 {data['depth_range_m'][0]:.2f}–{data['depth_range_m'][1]:.2f} m로 고정합니다. 범위 밖 색은 clip하지만 수치 평가는 모든 finite positive depth를 사용합니다.</li><li>이 실행은 저장된 관측·mask의 CPU 평가입니다. Simulator와 SAM2 추론, CUDA backend는 실행하지 않습니다.</li></ul><details><summary>프레임별 전체 수치</summary>{per_frame}</details><details><summary>입력 출처·재현 설정</summary><pre>{details}</pre></details><script type="application/json" id="evaluation-data">{raw_data}</script></html>""" path.write_text(document, encoding="utf-8")
def evaluate(episode_path: Path, masks_path: Path, *, camera="base_camera", output_root: Path, near=0.05, far=1.0, fps=None) -> Path: """Produce exactly two primary artifacts in a fresh experiment run directory.""" episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() depth_colors(np.ones((1, 1), dtype=np.float32), near, far) if fps is not None and (not np.isfinite(fps) or fps <= 0): raise ValueError("fps must be finite and positive") with np.load(episode_path, allow_pickle=False) as archive: required = [f"{camera}/seg", "peg_id", "box_id"] missing = [key for key in required if key not in archive] if missing: raise ValueError(f"GT evaluation requires: {', '.join(missing)}") segmentation = archive[f"{camera}/seg"] gt_ids = {name: int(archive[f"{name}_id"].item()) for name in OBJECTS} if gt_ids["peg"] == gt_ids["box"]: raise ValueError("GT peg and box segmentation IDs must be distinct") seed = int(archive["seed"].item()) if "seed" in archive else None timestamps = archive["timestamp"] if "timestamp" in archive else None expected_shape = archive[f"{camera}/depth"].shape if segmentation.shape != expected_shape: raise ValueError("GT segmentation shape must match the episode depth array") with np.load(masks_path, allow_pickle=False) as archive: source = archive["source_frame"] if source.ndim != 1 or not np.issubdtype(source.dtype, np.integer) or not len(source): raise ValueError("source_frame must be a nonempty one-dimensional integer array") if np.any(source < 0) or np.any(source >= len(segmentation)) or np.any(np.diff(source.astype(np.int64)) <= 0): raise ValueError("video source_frame must be in range and strictly increasing") if timestamps is not None: if timestamps.shape != (len(segmentation),): raise ValueError("timestamp shape must match episode frame count") tracked_times = timestamps[source] if not np.isfinite(tracked_times).all() or np.any(np.diff(tracked_times) <= 0): raise ValueError("tracked timestamps must be finite and strictly increasing") else: tracked_times = None if fps is None: if tracked_times is None or len(tracked_times) < 2: raise ValueError("pass --fps when fewer than two tracked timestamps are available") fps = float(1 / np.median(np.diff(tracked_times))) fps_source = "inverse median tracked timestamp gap" else: fps_source = "explicit override"
metadata_path = masks_path.with_name("tracking.json") provenance = {} if metadata_path.is_file(): recorded = json.loads(metadata_path.read_text(encoding="utf-8")) if recorded.get("camera") not in (None, camera): raise ValueError("camera differs from the mask runner's tracking.json") recorded_input = recorded.get("input") if recorded_input and Path(recorded_input).is_file() and Path(recorded_input).resolve() != episode_path: if _sha256(Path(recorded_input)) != _sha256(episode_path): raise ValueError("episode differs from the mask runner's tracking.json") provenance = {key: recorded.get(key) for key in ("input", "camera", "device", "config", "checkpoint", "stride")} iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) first = next(iterator) # Validate the Visual observation boundary before creating outputs. config = dict(input=str(episode_path), masks=str(masks_path), camera=camera, depth_range_m=[near, far], video_fps=fps, fps_source=fps_source, input_sha256=_sha256(episode_path), masks_sha256=_sha256(masks_path), output_root=str(Path(output_root).resolve()), gt_segmentation_ids=gt_ids, output_object_ids=OBJECTS, tracker=provenance, geometry="all finite-positive-depth pixels, no sampling or filters") with ExperimentLogger(team="visual", config=config, seed=seed, model="saved_sam2_rgbd", job_type="evaluate") as experiment: output = Path(output_root).resolve() / experiment.run_id output.mkdir(parents=True, exist_ok=False) video_path = output / "depth.mp4" records = [] with imageio.get_writer(video_path, fps=fps, codec="libx264", macro_block_size=1, ffmpeg_params=["-crf", "18"]) as writer: for frame in chain((first,), iterator): gt_masks = {name: segmentation[frame.source_frame] == gt_ids[name] for name in OBJECTS} metrics = {name: compare_object(frame, object_id, gt_masks[name]) for name, object_id in OBJECTS.items()} record = dict(source_frame=frame.source_frame, frame_idx=frame.frame_idx, timestamp=frame.timestamp, objects=metrics) records.append(record) writer.append_data(render_depth_frame(frame, gt_masks, metrics, near, far)) if len(records) == 1 or len(records) % 20 == 0: print(f"evaluated {len(records)}/{len(source)} frames", flush=True) experiment.link_output(video_path, kind="rollouts") summary = summarize(records) report_path = output / "gt_report.html" data = dict(run_id=experiment.run_id, seed=seed, evaluation_device="cpu", git_commit=experiment.metadata.get("git_commit"), git_dirty=experiment.metadata.get("git_dirty"), **config, summary=summary, frames=records) write_report(report_path, data) experiment.link_output(report_path, kind="reports") experiment.log(summary, prefix="eval/rgbd") experiment.record(dataset_sha256=config["input_sha256"], masks_sha256=config["masks_sha256"], evaluated_frames=len(records), evaluation_device="cpu") return output
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True, help="Original recorded episode NPZ") parser.add_argument("--masks", type=Path, required=True, help="Runtime masks.npz") parser.add_argument("--camera", default="base_camera") parser.add_argument("--out", type=Path, default=REPO / "visual/results/runtime_rgbd", help="Output root; creates a fresh <run_id> subdirectory") parser.add_argument("--depth-min", type=float, default=0.05, help="Fixed video depth scale, metres") parser.add_argument("--depth-max", type=float, default=1.0, help="Fixed video depth scale, metres") parser.add_argument("--fps", type=float, default=None, help="Override median timestamp-gap playback fps") args = parser.parse_args() try: output = evaluate(args.input, args.masks, camera=args.camera, output_root=args.out, near=args.depth_min, far=args.depth_max, fps=args.fps) except (ValueError, KeyError, FileNotFoundError) as exc: parser.error(str(exc)) print(f"saved GT report: {output / 'gt_report.html'}") print(f"saved depth video: {output / 'depth.mp4'}")
if __name__ == "__main__": main()12"""Compatibility imports for the original Task 02-B experiments."""from visual.runtime.normal_estimators import METHODS, finite_difference, local_plane, _assign, _empty, _jump123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Grounding DINO inference for runtime visual pipelines.
Example::
detector = GDino() boxes, scores = detector(rgb, "red and white block")
``rgb`` is an H x W x 3 uint8 RGB image. ``boxes`` are pixel-coordinate``[x1, y1, x2, y2]`` boxes ordered by descending score."""
from __future__ import annotations
import time
import numpy as npfrom PIL import Image
GDINO_ID = "IDEA-Research/grounding-dino-tiny"CAND_THR = 0.1
class GDino: """Load Grounding DINO once, then detect prompted objects in RGB images.
Args: device: Torch device used for inference. Defaults to ``"cuda"`` to match the existing Visual pipeline. model_id: Hugging Face model identifier or local model directory. threshold: Box and text threshold passed to Transformers postprocessing. """
def __init__(self, device: str = "cuda", model_id: str = GDINO_ID, threshold: float = CAND_THR): import torch from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor
self._torch = torch self.device = device self.threshold = threshold self.proc = AutoProcessor.from_pretrained(model_id) self.model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device).eval() self.last_ms = {"pre": 0.0, "forward": 0.0, "post": 0.0}
def _synchronize(self) -> None: if self.device.startswith("cuda") and self._torch.cuda.is_available(): self._torch.cuda.synchronize(self.device)
def __call__(self, rgb: np.ndarray, prompt: str) -> tuple[list[list[float]], list[float]]: """Return score-sorted pixel boxes and scores for one text prompt.""" image = Image.fromarray(np.asarray(rgb, dtype=np.uint8))
t0 = time.perf_counter() inputs = self.proc( images=image, text=prompt.lower().strip() + ".", return_tensors="pt", ).to(self.device) self._synchronize() t1 = time.perf_counter()
with self._torch.inference_mode(): outputs = self.model(**inputs) self._synchronize() t2 = time.perf_counter()
detections = self.proc.post_process_grounded_object_detection( outputs, inputs.input_ids, threshold=self.threshold, text_threshold=self.threshold, target_sizes=[image.size[::-1]], )[0] boxes = detections["boxes"].detach().cpu().numpy() scores = detections["scores"].detach().cpu().numpy() self.last_ms = { "pre": (t1 - t0) * 1000, "forward": (t2 - t1) * 1000, "post": (time.perf_counter() - t2) * 1000, }
order = np.argsort(-scores) return boxes[order].tolist(), scores[order].tolist()
# Keep the descriptive spelling available to new callers while preserving the# short class name used in the existing Visual scripts.GroundingDINO = GDino
12"""Compatibility imports for the original PCA5 optimization experiments."""from visual.runtime.pca import (build_geometry, covariance_patches, smallest_eigenvector, local_plane_optimized, cropped_features, process_optimized, _bounds, _two_object_executor)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212{ "status": "PASS", "baseline_gate": { "S2/peg": { "status": "PASS", "priority_order_exact": true, "final_order_xyz_exact": true, "full_frame0_structural_metrics_exact": true, "surface_metrics_exact": true, "negative_roi_exact": true, "candidate_order_source_support_exact": true, "first": 213708, "priority_count": 32, "budget": 129, "candidate_sha256": "d9f8b4a4b66d7747fc4c297bae25456fc0e283cce2455d06ba1e3472399fcc0e", "support_sha256": "0132240d8a12dab8f25270991cd22ff759b1611a031ca6c70249906d6a4b1a42", "support_xyz_sha256": "a00d57cdafb4946e38c400955f6fc15dd445c580a5c025d0e2546afa0b1244e9" }, "S2/box": { "status": "PASS", "priority_order_exact": true, "final_order_xyz_exact": true, "full_frame0_structural_metrics_exact": true, "surface_metrics_exact": true, "negative_roi_exact": true, "candidate_order_source_support_exact": true, "first": 101598, "priority_count": 32, "budget": 127, "candidate_sha256": "5d5966fec4727631a8cb7dd8833e2d2273824e4c9f03ab4ca24b3b32092ad63e", "support_sha256": "c507237457ff906e97b2426160e3b3c4be440d159e07b10ae5d1e2910bb638d0", "support_xyz_sha256": "12cf981209dfcc457eab16cc580a08c6bc7cb8262572ec4236d6158fe402d222" }, "S3/peg": { "status": "PASS", "priority_order_exact": true, "final_order_xyz_exact": true, "full_frame0_structural_metrics_exact": true, "surface_metrics_exact": true, "negative_roi_exact": true, "candidate_order_source_support_exact": true, "first": 214225, "priority_count": 32, "budget": 129, "candidate_sha256": "38d77460fe10e336d6788884e36609d3d3abd03954a147a1f1159ec7f0d5690d", "support_sha256": "0132240d8a12dab8f25270991cd22ff759b1611a031ca6c70249906d6a4b1a42", "support_xyz_sha256": "a00d57cdafb4946e38c400955f6fc15dd445c580a5c025d0e2546afa0b1244e9" }, "S3/box": { "status": "PASS", "priority_order_exact": true, "final_order_xyz_exact": true, "full_frame0_structural_metrics_exact": true, "surface_metrics_exact": true, "negative_roi_exact": true, "candidate_order_source_support_exact": true, "first": 96553, "priority_count": 32, "budget": 127, "candidate_sha256": "57ba8b580c8bc00249a838df2323e5ae91ce66fd0ab2cc70059a7c12ae2e55bf", "support_sha256": "c507237457ff906e97b2426160e3b3c4be440d159e07b10ae5d1e2910bb638d0", "support_xyz_sha256": "12cf981209dfcc457eab16cc580a08c6bc7cb8262572ec4236d6158fe402d222" } }, "required_tests": { "summary": "Ran 56 tests in 0.726s; OK", "modules": [ "visual.runtime.test.test_priority_fps_metric_control", "visual.runtime.test.test_sampling", "visual.runtime.test.test_sampling_geometry", "visual.runtime.test.test_sampling_evaluation", "visual.runtime.test.test_priority_fps_trace", "visual.runtime.test.test_priority_fps_seed_control" ] }, "controls_executed": true, "real_fps_calls": { "baseline": 8, "controls": 16 }, "candidate_initial_support_quota_fixed": true, "original_selected_xyz_source_role_feature_alignment": true, "feature_unavailable_explicit": true, "npz_exact_readback": true, "source_input_hashes_unchanged": true, "preservation": { "status": "PASS", "protected_file_count": 1649, "all_sha256_unchanged": true }, "same_pair_joint_and_unique_reference_matching": true, "gt_and_segment_selection_independence": "synthetic tests; selection has no annotation arguments", "ambiguous_physical_spacing": "N/A", "production_policy_adopted": false, "skipped": [ "simulator", "renderer", "CUDA/GPU", "other frames/seeds/lambdas", "feature reconstruction", "production policy", "external upload", "dependency installation", "commit" ], "document_checks": { "html_local_targets": 24, "markdown_local_targets": 30, "png_decoded": { "spatial_xz.png": [ 1820, 1950, 4 ], "box_structural_zoom.png": [ 2240, 2100, 4 ], "html_preview.png": [ 1400, 1600, 3 ], "coverage_surface_tradeoff.png": [ 1500, 2100, 4 ], "local_reference_distances.png": [ 1820, 2380, 4 ], "peg_structural_zoom.png": [ 2240, 2100, 4 ], "box_line_node_spacing.png": [ 1680, 2100, 4 ], "selection_overview.png": [ 1920, 1800, 4 ] }, "status": "PASS" }, "report_only_refresh": { "real_fps_calls": 0, "raw_selection_npz_unchanged": true, "execution_sources": "source_snapshot; sources_before/after", "final_sources": "report_source_snapshot; report_generation_sources" }, "browser_image_loading": { "status": "PASS", "images": [ { "src": "selection_overview.png", "complete": true, "width": 1800, "height": 1920 }, { "src": "box_structural_zoom.png", "complete": true, "width": 2100, "height": 2240 }, { "src": "peg_structural_zoom.png", "complete": true, "width": 2100, "height": 2240 }, { "src": "local_reference_distances.png", "complete": true, "width": 2380, "height": 1820 }, { "src": "box_line_node_spacing.png", "complete": true, "width": 2100, "height": 1680 }, { "src": "coverage_surface_tradeoff.png", "complete": true, "width": 2100, "height": 1500 }, { "src": "spatial_xz.png", "complete": true, "width": 1950, "height": 1820 } ] }, "final_contract_tests": { "status": "PASS", "count": 12, "log": "tests_final.log" }, "source_input_hashes_scope": "sources_before/after compare actual selection execution period; final report-only source changes tracked separately"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""PCA5 optimization: paired fidelity, fixed GT evaluation and CPU latency.
Keeps existing outputs and estimators. Excludes initial grounding by using thesame saved masks; tracker-inclusive timing is a separate explicit benchmark."""from __future__ import annotations
import argparsefrom dataclasses import replacefrom pathlib import Pathimport platformfrom time import perf_counterimport sys
import numpy as np
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_logger import ExperimentLoggerfrom utils.experiment_artifacts import digestsfrom visual.runtime.geometry import GeometryFrame, GeometryParameters, build_organized_geometry, compute_geometric_featuresfrom visual.runtime.rgbd import iter_saved_rgbd, PEGfrom visual.runtime.test.normal_estimators import local_planefrom visual.runtime.test.normal_diagnostics import angular_error, quantize, rays, stats, synthetic_casefrom visual.runtime.test.pca_optimized import process_optimizedfrom visual.runtime.test.run_normal_comparison import Pool, real_truth, save_json
METHODS = ('reference_pca5', 'optimized_eigh', 'optimized_analytic', 'optimized_parallel')
def reference(frame): start = perf_counter(); geometry = build_organized_geometry(frame); t1 = perf_counter() p = GeometryParameters() normals = {i: local_plane(geometry, i, 5, p) for i in geometry.object_masks}; t2 = perf_counter() features = {i: compute_geometric_features(geometry, i, *normals[i], p) for i in geometry.object_masks}; end = perf_counter() return GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, dict(geometry=(t1-start)*1000, normals=(t2-t1)*1000, discontinuity_features=(end-t2)*1000, total=(end-start)*1000))
def run_method(frame, method, profile=None): if method=='optimized_parallel':return process_optimized(frame,solver='analytic',profile=profile,parallel=True) return reference(frame) if method=='reference_pca5' else process_optimized(frame, solver=method.removeprefix('optimized_'), profile=profile)
def fidelity(expected, actual): row = dict(validity_differences=0, other_field_differences=0, normal_max_deg=0., variation_max_deg=0., threshold_flips={str(t): 0 for t in (5, 10, 20, 30)}) np.testing.assert_array_equal(expected.geometry.xyz, actual.geometry.xyz) for oid, a in expected.objects.items(): b = actual.objects[oid] row['validity_differences'] += int(np.count_nonzero(a.normal_valid != b.normal_valid)) row['validity_differences'] += int(np.count_nonzero(a.normal_variation_valid != b.normal_variation_valid)) common = a.normal_valid & b.normal_valid if common.any(): row['normal_max_deg'] = max(row['normal_max_deg'], float(angular_error(a.normals[common], b.normals[common]).max())) vv = a.normal_variation_valid & b.normal_variation_valid if vv.any(): row['variation_max_deg'] = max(row['variation_max_deg'], float(np.rad2deg(np.abs(a.normal_variation_rad[vv]-b.normal_variation_rad[vv])).max())) for key in a.__dataclass_fields__: if key in ('normals', 'normal_variation_rad', 'normal_valid', 'normal_variation_valid'): continue aa, bb = getattr(a, key), getattr(b, key) equal = (aa == bb) | (np.isnan(aa) & np.isnan(bb)) if np.issubdtype(aa.dtype, np.floating) else aa==bb row['other_field_differences'] += int(np.count_nonzero(~equal)) for t in (5, 10, 20, 30): row['threshold_flips'][str(t)] += int(np.count_nonzero(vv & ((np.rad2deg(a.normal_variation_rad)>t) != (np.rad2deg(b.normal_variation_rad)>t)))) return row
def combine_fidelity(rows): return dict(samples=len(rows), validity_differences=sum(r['validity_differences'] for r in rows), other_field_differences=sum(r['other_field_differences'] for r in rows), normal_max_deg=max((r['normal_max_deg'] for r in rows), default=0.), variation_max_deg=max((r['variation_max_deg'] for r in rows), default=0.), threshold_flips={str(t):sum(r['threshold_flips'][str(t)] for r in rows) for t in (5, 10, 20, 30)})
def synthetic_observations(k): for kind in ('front', 'tilted', 'crease', 'step'): for z in (.2, .25, .35, .6, 1.): for phase in (0., .00025, .0005, .00075): f, truth, regions = synthetic_case(kind, k, z0=z, phase_m=phase) for mode in ('float', 'floor', 'nearest'): yield dict(geometry=kind, z0_m=z, phase_m=phase, quantization=mode), f if mode=='float' else replace(f, depth=quantize(f.depth, mode)), truth, regions for z in (.25, .6): for slope in (.2, .8): for azimuth in (0, 45, 90, 135): f, _, regions = synthetic_case('tilted', k, z0=z, phase_m=.00025) a, b = slope*np.cos(np.deg2rad(azimuth)), slope*np.sin(np.deg2rad(azimuth)) ray = rays(f.depth.shape, k) depth = ((z+.00025)/(1-a*ray[..., 0]-b*ray[..., 1])).astype(np.float32) f = replace(f, depth=depth) truth = np.broadcast_to(np.array([a, b, -1.])/np.sqrt(a*a+b*b+1), (*depth.shape, 3)) for mode in ('float', 'floor', 'nearest'): yield dict(geometry='direction', z0_m=z, slope=slope, azimuth_deg=azimuth, quantization=mode), f if mode=='float' else replace(f, depth=quantize(f.depth, mode)), truth, regions
def plot(output, frame, results): import matplotlib.pyplot as plt fig, axes = plt.subplots(2, len(METHODS)+1, figsize=(4*(len(METHODS)+1), 9), constrained_layout=True) axes[0, 0].imshow(frame.rgb); axes[0, 0].set_title('Same observation / saved tracking masks') axes[1, 0].imshow(frame.rgb); axes[1, 0].set_title('Normal valid=yellow / invalid=dark') for col, method in enumerate(METHODS, 1): var = np.full(frame.depth.shape, np.nan); valid = var.copy() for f in results[method].objects.values(): var[f.normal_variation_valid] = np.rad2deg(f.normal_variation_rad[f.normal_variation_valid]) valid[f.valid_points] = f.normal_valid[f.valid_points] axes[0, col].imshow(var, cmap=plt.get_cmap('turbo').with_extremes(bad='#cccccc'), vmin=0, vmax=45) axes[1, col].imshow(valid, cmap=plt.get_cmap('viridis').with_extremes(bad='#cccccc'), vmin=0, vmax=1) axes[0, col].set_title(method+' variation (0-45 deg)') axes[1, col].set_title(method+' normal validity') for ax in axes.ravel(): ax.axis('off') fig.suptitle(f'Source {frame.source_frame}: same PCA5 support; implementation optimization only') fig.savefig(output/f'f{frame.source_frame:04d}.png', dpi=120); plt.close(fig)
def evaluate(input_path, masks_path, output_root, *, repeats=5, synthetic=True): if repeats < 1: raise ValueError('repeats must be positive') input_path, masks_path = Path(input_path).resolve(), Path(masks_path).resolve() frames = list(iter_saved_rgbd(input_path, masks_path)) with np.load(input_path, allow_pickle=False) as a: gt = {k:a[k] for k in ['base_camera/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed']} sources = [Path(__file__), Path(__file__).with_name('pca_optimized.py'), Path(__file__).with_name('pca_torch.py'), Path(__file__).with_name('normal_estimators.py')] cfg = dict(task='pca5_optimization', input=str(input_path), masks=str(masks_path), repeats=repeats, methods=list(METHODS), input_sha256=digests(input_path)[1], masks_sha256=digests(masks_path)[1], source_sha256={str(p.relative_to(REPO)):digests(p)[1] for p in sources}, initial_grounding_excluded=True, tracking_included=False, final_graph_handoff_implemented=False, cpu_normal_target_p95_ms=10, cpu_geometry_target_p95_ms=25, final_target_period_ms=50, same_neighbourhood=True, pca_dtype='float64', synthetic=synthetic, python=platform.python_version(), platform=platform.platform(), numpy=np.__version__, timing='one warmup each, round-robin order, full per-method build/normal/features, no I/O/GT/metrics') with ExperimentLogger(team='visual', config=cfg, seed=int(gt['seed']), model='pca5_optimization', job_type='evaluate') as logger: output = Path(output_root)/logger.run_id; output.mkdir(parents=True, exist_ok=False) print('Output:',output,flush=True) source_dir=output/'source'; source_dir.mkdir() for p in sources: (source_dir/p.name).write_bytes(p.read_bytes()) for method in METHODS: run_method(frames[0], method) pool, records = Pool(), [] all_fidelity = {m:[] for m in METHODS[1:]} timings = {m:[] for m in METHODS} profiles = [] for idx, frame in enumerate(frames): results = {} for repeat in range(repeats): offset = (idx+repeat)%len(METHODS) for method in METHODS[offset:]+METHODS[:offset]: p = {} if method=='optimized_analytic' and repeat==0 else None result = run_method(frame, method, profile=p) timings[method].append(dict(source_frame=frame.source_frame, repeat=repeat, **result.timings_ms)) if repeat==0: results[method]=result if p is not None: profiles.append(dict(source_frame=frame.source_frame, objects=p)) truths, regions, _ = real_truth(frame, results['reference_pca5'], gt, 'base_camera') record = dict(source_frame=frame.source_frame, fidelity={}, metrics={}) for method in METHODS[1:]: f = fidelity(results['reference_pca5'], results[method]); record['fidelity'][method]=f; all_fidelity[method].append(f) for method in METHODS: rows = {} for name, oid in [('peg',0),('box',1)]: for key, region in regions[name].items(): rows[name+'/'+key] = pool.add(method+'/'+name+'/'+key, results[method].objects[oid], region, truths[name]['normals'] if key.startswith('plane_') else None) record['metrics'][method]=rows if frame.source_frame in (0, 15, 45, 80, 120): plot(output, frame, results) records.append(record) if idx==0 or (idx+1)%20==0: print('Real frames',idx+1,'/',len(frames),flush=True) summary = pool.summary() syn_rows=[]; syn_fidelity={m:[] for m in METHODS[1:]} if synthetic: from visual.runtime.test.run_normal_comparison import response_metrics for idx, (condition, frame, truth, regions) in enumerate(synthetic_observations(frames[0].intrinsic)): results = {m:run_method(frame,m) for m in METHODS} row=dict(condition=condition, methods={}, fidelity={}) for method in METHODS[1:]: f=fidelity(results['reference_pca5'],results[method]);syn_fidelity[method].append(f);row['fidelity'][method]=f for method in METHODS: row['methods'][method]={key:response_metrics(results[method].objects[PEG],region,truth) for key,region in regions.items()} syn_rows.append(row) if (idx+1)%48==0: print('Synthetic conditions',idx+1,'/288',flush=True) latency = {m:{k:stats([r[k] for r in timings[m]]) for k in ['geometry','normals','discontinuity_features','total']} for m in METHODS} fidelity_summary={m:combine_fidelity(all_fidelity[m]) for m in METHODS[1:]} syn_summary={m:combine_fidelity(syn_fidelity[m]) for m in METHODS[1:]} for part in [fidelity_summary, syn_summary] if synthetic else [fidelity_summary]: for r in part.values(): if r['validity_differences'] or r['other_field_differences'] or r['normal_max_deg']>.001 or r['variation_max_deg']>.001: raise AssertionError('same-estimator fidelity tolerance failed') data=dict(run_id=logger.run_id,config=cfg,evaluated_frames=len(frames),latency_ms=latency, fidelity=fidelity_summary,summary=summary,frames=records,profile=profiles,timing_samples=timings, synthetic=dict(conditions=len(syn_rows),fidelity=syn_summary,cases=syn_rows)) save_json(output/'optimization.json',data) body=''.join(f'<p><img style="width:100%" src="{p.name}"></p>' for p in sorted(output.glob('*.png'))) (output/'optimization.html').write_text(f'<!doctype html><meta charset="utf-8"><title>PCA5 optimization</title><h1>PCA5 optimization</h1><p>Run {logger.run_id}. Initial grounding excluded; saved tracking masks. Final Graph handoff is not implemented. <a href="optimization.json">Metrics, fidelity, latency, source hashes</a>.</p>'+body) for path in output.iterdir(): if path.is_file(): logger.link_output(path,kind='metrics' if path.suffix=='.json' else 'reports') logger.log(latency,prefix='eval/pca5_optimization/latency_ms');logger.log(fidelity_summary,prefix='eval/pca5_optimization/fidelity') logger.record(evaluation_device='cpu',gpu_executed=False,initial_grounding_excluded=True,evaluated_frames=len(frames)) return output
def main(): p=argparse.ArgumentParser(description=__doc__) p.add_argument('--input',type=Path,default=REPO/'visual/data/step2/ep000.npz') p.add_argument('--masks',type=Path,default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') p.add_argument('--out',type=Path,default=REPO/'visual/results/pca_optimization') p.add_argument('--repeats',type=int,default=5) p.add_argument('--no-synthetic',action='store_true') a=p.parse_args();print(evaluate(a.input,a.masks,a.out,repeats=a.repeats,synthetic=not a.no_synthetic))
if __name__=='__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266"""Current-observation Structural priority / Surface FPS, internal NumPy metadata.
No GT, cache, final node features, graph edges or Vision--Graph packaging. XYZremains in the source CV-camera frame. Selection roles are not semantic types."""from __future__ import annotations
from dataclasses import dataclass, fieldfrom numbers import Integralfrom time import perf_counter
import numpy as np
from visual.runtime.geometry import ( GeometryFrame, GeometryParameters, estimate_surface_normals,)from visual.runtime.pca import build_geometry, cropped_features, local_plane_optimizedfrom visual.runtime.normal_estimators import finite_differencefrom visual.runtime.edge_evidence import PairEvidence, pair_evidencefrom visual.runtime.rgbd import PEG, BOX, TrackedRGBDFrame
METHODS = ('S0', 'S1', 'S2', 'S3', 'S4')
def _integer(value, name): if not isinstance(value, Integral) or isinstance(value, (bool, np.bool_)) or value < 0: raise ValueError(f'{name} must be a nonnegative integer')
@dataclass(frozen=True)class SamplingConfig: """Experimental defaults, not adopted architecture/hyperparameters.
Reserve minimums first, then apportion remaining capacity by observed point counts (or their square roots). Largest remainder, capped by availability; exact ties use ascending object ID. Structural slots are a GLOBAL maximum floor(num_points*ratio), including independently capped S4 depth-only slots. """ num_points: int = 256 structural_ratio: float = .25 min_points: tuple[int, int] = (16, 16) allocation: str = 'observed_points' seed: int = 0 orientation_threshold_deg: float = 20. depth_priority_fraction: float = .25 sampling: str = 'fps'
def __post_init__(self): _integer(self.num_points, 'num_points'); _integer(self.seed, 'seed') if len(self.min_points) != 2: raise ValueError('min_points must contain Peg and Box minimums') for n in self.min_points: _integer(n, 'object minimum') if sum(self.min_points) > self.num_points: raise ValueError('sum of object minimums exceeds num_points') for name in ('structural_ratio', 'depth_priority_fraction'): x = getattr(self, name) if not np.isfinite(x) or not 0 <= x <= 1: raise ValueError(f'{name} must be finite in [0,1]') if not np.isfinite(self.orientation_threshold_deg) or not 0 <= self.orientation_threshold_deg <= 180: raise ValueError('orientation threshold must be in [0,180] degrees') if self.allocation not in ('observed_points', 'sqrt_observed_points'): raise ValueError('unknown allocation rule') if self.sampling != 'fps': raise ValueError('only fps sampling is supported')
def allocate_budget(total, capacities, minimums=(0, 0), weights=None): """Capped proportional integer apportionment, deterministic and availability aware.""" _integer(total, 'budget') cap = np.asarray(capacities) mins = np.asarray(minimums) if cap.shape != (2,) or mins.shape != (2,): raise ValueError('expected two object counts') for x in (*cap, *mins): _integer(x, 'capacity/minimum') if mins.sum() > total: raise ValueError('minimums exceed total budget') cap, mins = cap.astype(np.int64), mins.astype(np.int64) weight = cap.astype(float) if weights is None else np.asarray(weights, float) if weight.shape != (2,) or not np.isfinite(weight).all() or (weight < 0).any(): raise ValueError('weights must be two finite nonnegative values') out = np.minimum(cap, mins) left = min(total, int(cap.sum()))-int(out.sum()) while left: room = cap-out w = np.where(room > 0, weight, 0) if not w.any(): w = (room > 0).astype(float) quota = left*w/w.sum() take = np.minimum(room, np.floor(quota).astype(np.int64)) out += take; left -= int(take.sum()) # Largest fractional remainder; saturated objects are skipped. If a # quota exceeded capacity, the next pass redistributes the surplus. order = np.argsort(-(quota-np.floor(quota)), kind='stable') for i in order: if out[i] < cap[i] and left: out[i] += 1; left -= 1 return out
def fps_indices(points, count, *, seed=0, initial=()): """Legacy pointcloud.fps distance update, returning unique source row indices.
No random pre-reduction. Uniform seeded first row; argmax ties choose the first source row. An initial selection seeds distances for Surface coverage. All initial rows precede newly selected rows. Even coincident XYZ is never selected twice by row index. Computes squared distances in float64. """ _integer(count, 'FPS count'); _integer(seed, 'FPS seed') xyz = np.asarray(points, dtype=float) if xyz.ndim != 2 or xyz.shape[1] != 3 or not np.isfinite(xyz).all(): raise ValueError('FPS requires finite [N,3] observed coordinates') initial = np.asarray(initial, dtype=np.int64) if initial.ndim != 1 or len(np.unique(initial)) != len(initial) or ((initial < 0) | (initial >= len(xyz))).any(): raise ValueError('initial FPS rows must be distinct valid indices') count = min(count, len(xyz)) if len(initial) > count: raise ValueError('initial rows exceed FPS count') if not count: return np.empty(0, np.int64) chosen = list(initial) distance = np.full(len(xyz), np.inf) x, y, z = (np.ascontiguousarray(xyz[:, i]) for i in range(3)) def update(j): np.minimum(distance, (x-x[j])**2+(y-y[j])**2+(z-z[j])**2, out=distance) distance[j] = -np.inf for j in chosen: update(j) if not chosen: chosen.append(int(np.random.default_rng(seed).integers(len(xyz)))) update(chosen[-1]) while len(chosen) < count: j = int(distance.argmax()); chosen.append(j); update(j) return np.asarray(chosen, np.int64)
@dataclass(frozen=True)class SamplingEvidence: """Detector output before thresholding. Contains observations only.""" frame: GeometryFrame pairs: dict[int, PairEvidence] estimator: str timings_ms: dict[str, float]
@dataclass(frozen=True)class ObjectCandidates: """Only valid observed rows, in original raster order; all evidence stays aligned.""" flat_index: np.ndarray points: np.ndarray metadata: dict[str, np.ndarray]
@dataclass(frozen=True)class SampledPoints: """Internal selection, variable N; no padding, no final GNN feature encoding.
priority_selected / depth_priority_selected record selection paths, whereas metadata['structural_candidate'] records detector eligibility. Surface FPS may select more detector candidates than the structural priority slot cap. """ source_frame: int camera: str points: np.ndarray pixels_vu: np.ndarray flat_index: np.ndarray object_id: np.ndarray priority_selected: np.ndarray depth_priority_selected: np.ndarray metadata: dict[str, np.ndarray] object_budgets: dict[int, int] counts: dict[int, dict[str, int]] timings_ms: dict[str, float] = field(default_factory=dict)
def extract_sampling_evidence(frame: TrackedRGBDFrame, estimator='pca5', parameters=GeometryParameters()): """Reuse Task02 estimators and pair operator; optimized PCA5 analytic solver.""" if estimator not in ('baseline', 'fd2', 'pca5'): raise ValueError('unknown normal estimator') t0 = perf_counter(); geometry = build_geometry(frame); t1 = perf_counter() normals = {} for oid in (PEG, BOX): if estimator == 'baseline': normals[oid] = estimate_surface_normals(geometry, oid, parameters) elif estimator == 'fd2': normals[oid] = finite_difference(geometry, oid, 2, parameters) else: normals[oid] = local_plane_optimized(geometry, oid, parameters, solver='analytic') t2 = perf_counter() features = {i: cropped_features(geometry, i, *normals[i], parameters) for i in (PEG, BOX)} t3 = perf_counter() pairs = {i: pair_evidence(geometry, i, *normals[i], parameters) for i in (PEG, BOX)} t4 = perf_counter() timing = dict(geometry=(t1-t0)*1000, normals=(t2-t1)*1000, features=(t3-t2)*1000, pair_evidence=(t4-t3)*1000, extraction_total=(t4-t0)*1000) result = GeometryFrame(frame.source_frame, frame.camera, frame.frame_idx, frame.timestamp, geometry, features, timing) return SamplingEvidence(result, pairs, estimator, timing)
def extract_candidates(evidence: SamplingEvidence, config: SamplingConfig, method='S3'): """Threshold at observed pixels; boundary flags alone never imply eligibility.""" if method not in METHODS: raise ValueError('unknown sampling method') expected = dict(S1='baseline', S2='fd2', S3='pca5', S4='pca5') if method in expected and evidence.estimator != expected[method]: raise ValueError('method and normal estimator disagree') g = evidence.frame.geometry result = {} for oid in (PEG, BOX): idx = np.flatnonzero(g.observed_mask(oid)) f = evidence.frame.objects[oid] maps = evidence.pairs[oid].candidates(config.orientation_threshold_deg) metadata = {name: getattr(f, name).reshape((-1, 3) if name == 'normals' else (-1,))[idx].copy() for name in f.__dataclass_fields__} metadata.update({f'{name}_evidence': m.ravel()[idx] for name, m in maps.items() if name != 'union'}) orientation = maps['orientation'].ravel()[idx] depth_only = maps['depth'].ravel()[idx] & ~orientation metadata.update(orientation_score_deg=np.rad2deg(f.normal_variation_rad.ravel()[idx]), orientation_candidate=orientation, depth_only_candidate=depth_only, structural_candidate=orientation | (depth_only if method == 'S4' and config.depth_priority_fraction > 0 else False)) result[oid] = ObjectCandidates(idx, g.xyz.reshape(-1, 3)[idx].copy(), metadata) return result
def sample_points(evidence: SamplingEvidence, config=SamplingConfig(), *, method='S3'): """Object budgets -> Structural FPS -> remaining-support FPS seeded by priority.""" t0 = perf_counter(); objects = extract_candidates(evidence, config, method); t1 = perf_counter() available = np.array([len(objects[i].points) for i in (PEG, BOX)]) weights = np.sqrt(available) if config.allocation == 'sqrt_observed_points' else available budgets = allocate_budget(config.num_points, available, config.min_points, weights) cap = int(np.floor(config.num_points*config.structural_ratio)) if method != 'S0' else 0 capacities = np.array([min(budgets[i], int(objects[i].metadata['structural_candidate'].sum())) for i in (PEG, BOX)]) slots = allocate_budget(cap, capacities, weights=budgets) depth_cap = int(np.floor(cap*config.depth_priority_fraction)) if method == 'S4' else 0 depth_capacity = [min(slots[i], int(objects[i].metadata['depth_only_candidate'].sum())) for i in (PEG, BOX)] depth_slots = allocate_budget(depth_cap, depth_capacity, weights=budgets) t2 = perf_counter() selections, priority_sizes, depth_sizes = {}, {}, {} for i in (PEG, BOX): obj = objects[i]; m = obj.metadata # Each object always uses its own stream, invariant to missing other objects. seed = int(np.random.SeedSequence([config.seed, i]).generate_state(1)[0]) oi = np.flatnonzero(m['orientation_candidate']) di = np.flatnonzero(m['depth_only_candidate']) # Unused depth reservation can be used by orientation, never vice versa. dn = min(int(depth_slots[i]), len(di)) on = min(int(slots[i])-dn, len(oi)) orientation = oi[fps_indices(obj.points[oi], on, seed=seed)] depth = di[fps_indices(obj.points[di], dn, seed=seed,)] selections[i] = np.concatenate((orientation, depth)) priority_sizes[i], depth_sizes[i] = on+dn, dn t3 = perf_counter() for i in (PEG, BOX): seed = int(np.random.SeedSequence([config.seed, i]).generate_state(1)[0]) selections[i] = fps_indices(objects[i].points, int(budgets[i]), seed=seed, initial=selections[i]) t4 = perf_counter() flat, xyz, ids, priority, depth_priority, metadata = [], [], [], [], [], {} counts = {} for i in (PEG, BOX): obj = objects[i]; rows = selections[i]; n = len(rows); pn = priority_sizes[i]; dn = depth_sizes[i] flat.append(obj.flat_index[rows]); xyz.append(obj.points[rows]); ids.append(np.full(n, i, np.int64)) priority.append(np.arange(n) < pn) depth_priority.append((np.arange(n) >= pn-dn) & (np.arange(n) < pn)) for name, values in obj.metadata.items(): metadata.setdefault(name, []).append(values[rows]) counts[i] = dict(observed=len(obj.points), budget=int(budgets[i]), candidates=int(obj.metadata['structural_candidate'].sum()), priority=pn, orientation_priority=pn-dn, depth_priority=dn, surface_fps=n-pn, selected_candidates=int(obj.metadata['structural_candidate'][rows].sum()), selected=n) flat = np.concatenate(flat) timing = dict(candidate_selection=(t1-t0)*1000, budget_allocation=(t2-t1)*1000, structural_sampling=(t3-t2)*1000, surface_fps=(t4-t3)*1000) result = SampledPoints(evidence.frame.source_frame, evidence.frame.camera, np.concatenate(xyz), np.column_stack(np.unravel_index(flat, evidence.frame.geometry.valid_depth.shape)), flat, np.concatenate(ids), np.concatenate(priority), np.concatenate(depth_priority), {k: np.concatenate(v) for k, v in metadata.items()}, {i: int(budgets[i]) for i in (PEG, BOX)}, counts, timing) timing['sampling_total'] = (perf_counter()-t0)*1000 timing['geometry_sampling_total'] = evidence.timings_ms['extraction_total']+timing['sampling_total'] return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""Analytical GT error cases and the two-artifact RGB-D evaluation workflow."""
import jsonimport osfrom pathlib import Pathimport reimport tempfileimport unittestfrom unittest.mock import patch
import imageio.v2 as imageioimport numpy as np
from visual.runtime.rgbd import BOX, PEG, TrackedRGBDFramefrom visual.runtime.test.run_rgbd import compare_object, depth_colors, evaluate, summarizefrom utils.experiment_artifacts import plan_upload
def frame(predicted, depth=None): height, width = predicted.shape return TrackedRGBDFrame( source_frame=0, camera="test_camera", rgb=np.zeros((height, width, 3), dtype=np.uint8), depth=np.ones((height, width), dtype=np.float32) if depth is None else depth, intrinsic=np.array([[100, 0, 0], [0, 100, 0], [0, 0, 1]], dtype=np.float32), cam2world=np.eye(4, dtype=np.float32), tcp_pose=np.array([0, 0, 0, 1, 0, 0, 0], dtype=np.float32), masks={PEG: predicted, BOX: np.zeros_like(predicted)}, frame_idx=0, timestamp=0.0, )
class RGBDEvaluationTest(unittest.TestCase): def test_perfect_mask_has_unit_iou_and_zero_surface_error(self): mask = np.zeros((3, 4), dtype=bool) mask[1, 1:3] = True result = compare_object(frame(mask), PEG, mask) for key in ("iou", "precision", "recall"): self.assertEqual(result[key], 1) for key in ("centroid_error_mm", "chamfer_mm", "predicted_to_gt_mm", "gt_to_predicted_mm"): self.assertEqual(result[key], 0)
def test_shifted_pixel_has_analytical_ten_mm_error(self): predicted = np.zeros((3, 4), dtype=bool) gt = np.zeros_like(predicted) predicted[1, 2] = gt[1, 1] = True observation = frame(predicted) observation.cam2world[:3, :3] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]] observation.cam2world[:3, 3] = [1, 2, 3] result = compare_object(observation, PEG, gt) self.assertEqual(result["iou"], 0) self.assertAlmostEqual(result["chamfer_mm"], 10, places=3) self.assertAlmostEqual(result["centroid_error_mm"], 10, places=3)
def test_extra_pixel_checks_chamfer_normalization_and_direction(self): predicted = np.zeros((3, 4), dtype=bool) gt = np.zeros_like(predicted) predicted[1, 1:3] = True gt[1, 1] = True result = compare_object(frame(predicted), PEG, gt) self.assertEqual(result["iou"], 0.5) self.assertEqual(result["recall"], 1) self.assertAlmostEqual(result["predicted_to_gt_mm"], 5, places=4) self.assertEqual(result["gt_to_predicted_mm"], 0) self.assertAlmostEqual(result["chamfer_mm"], 2.5, places=4) self.assertAlmostEqual(result["centroid_error_mm"], 5, places=4)
def test_missing_predictions_are_not_hidden_as_zero_geometry_error(self): empty = np.zeros((3, 4), dtype=bool) gt = empty.copy() gt[1, 1] = True missed = compare_object(frame(empty), PEG, gt) absent = compare_object(frame(empty), BOX, empty) self.assertEqual(missed["iou"], 0) self.assertEqual(missed["recall"], 0) self.assertIsNone(missed["precision"]) self.assertIsNone(missed["chamfer_mm"]) self.assertIsNone(absent["iou"]) hallucinated = compare_object(frame(gt), PEG, empty) summary = summarize([ {"objects": {"peg": missed, "box": absent}}, {"objects": {"peg": hallucinated, "box": absent}}, ]) self.assertEqual(summary["peg"]["visible_iou"]["mean"], 0) self.assertEqual(summary["peg"]["missed_visible_frames"], 1) self.assertEqual(summary["peg"]["false_positive_invisible_frames"], 1) self.assertEqual(summary["peg"]["geometry_unavailable_visible_frames"], 1) self.assertEqual(summary["peg"]["chamfer_mm"]["count"], 0) self.assertIsNone(summary["peg"]["chamfer_mm"]["mean"])
def test_invalid_depth_is_excluded_and_video_uses_a_fixed_scale(self): depth = np.array([[0, -1, np.nan, np.inf], [0.5, 0.5, 1, 2]], dtype=np.float32) mask = np.ones(depth.shape, dtype=bool) result = compare_object(frame(mask, depth), PEG, mask) self.assertEqual(result["predicted_depth_pixels"], 4) self.assertEqual(result["predicted_valid_depth_fraction"], 0.5) self.assertEqual(result["chamfer_mm"], 0) colored = depth_colors(depth, 0.2, 1.5) self.assertFalse(colored[0].any()) np.testing.assert_array_equal(colored[1, 0], colored[1, 1]) np.testing.assert_array_equal(colored[1, 0], depth_colors(np.array([[0.5]]), 0.2, 1.5)[0, 0]) np.testing.assert_array_equal(colored[1, 3], depth_colors(np.array([[1.5]]), 0.2, 1.5)[0, 0]) self.assertFalse(np.array_equal(colored[1, 0], colored[1, 2]))
def test_report_and_decodable_video_follow_sparse_source_frames(self): count, height, width = 3, 24, 32 segmentation = np.zeros((count, height, width), dtype=np.int16) segmentation[:, 5:10, 3:8] = 18 segmentation[:, 10:16, 19:25] = 19 source = np.array([0, 2], dtype=np.int32) peg = segmentation[source] == 18 peg[1] = False # Only the second selected frame is missed. rgb = np.full((count, height, width, 3), 120, dtype=np.uint8) episode = { "test_camera/rgb": rgb, "test_camera/depth": np.ones((count, height, width), dtype=np.float32), "test_camera/intrinsic": np.repeat(np.array([[[100, 0, 16], [0, 100, 12], [0, 0, 1]]], dtype=np.float32), count, axis=0), "test_camera/cam2world": np.repeat(np.eye(4, dtype=np.float32)[None], count, axis=0), "test_camera/seg": segmentation, "tcp_pose": np.tile([0, 0, 0, 1, 0, 0, 0], (count, 1)).astype(np.float32), "frame_idx": np.array([10, 11, 12]), "timestamp": np.array([0, 0.05, 0.1]), "peg_id": 18, "box_id": 19, "seed": 42, } with tempfile.TemporaryDirectory() as root: root = Path(root) episode_path, masks_path = root / "episode.npz", root / "masks.npz" np.savez(episode_path, **episode) np.savez(masks_path, source_frame=source, peg=peg, box=segmentation[source] == 19) with patch.dict(os.environ, {"WANDB_MODE": "disabled", "EXPERIMENTS_DIR": str(root / "experiments")}): output = evaluate(episode_path, masks_path, camera="test_camera", output_root=root / "results") self.assertEqual({path.name for path in output.iterdir() if not path.name.endswith(".tracking.json")}, {"gt_report.html", "depth.mp4"}) report = (output / "gt_report.html").read_text() data = json.loads(re.search(r'id="evaluation-data">(.*?)</script>', report, re.S).group(1)) self.assertEqual([row["source_frame"] for row in data["frames"]], [0, 2]) self.assertEqual([row["frame_idx"] for row in data["frames"]], [10, 12]) self.assertEqual(data["gt_segmentation_ids"], {"peg": 18, "box": 19}) self.assertEqual(data["summary"]["peg"]["visible_iou"]["mean"], 0.5) self.assertEqual(data["summary"]["peg"]["chamfer_mm"]["count"], 1) self.assertEqual(data["summary"]["box"]["visible_iou"]["mean"], 1) self.assertEqual(data["video_fps"], 10) with imageio.get_reader(output / "depth.mp4") as video: self.assertEqual(video.count_frames(), 2) self.assertEqual(video.get_meta_data()["fps"], 10) rendered = video.get_data(0) self.assertEqual(rendered.shape[-1], 3) self.assertGreater(rendered.std(), 10) for artifact in ("gt_report.html", "depth.mp4"): link = json.loads((output / f"{artifact}.tracking.json").read_text()) self.assertEqual(link["run_id"], output.name) metadata = json.loads((root / "experiments" / output.name / "metadata.json").read_text()) self.assertEqual(metadata["team"], "visual") self.assertEqual(metadata["status"], "finished") self.assertEqual(metadata["evaluated_frames"], 2) plans = plan_upload(root / "experiments" / output.name, ["reports", "rollouts", "metrics"]) self.assertEqual(set(plans), {"rollouts"}) self.assertTrue(any(item.path.endswith("gt_report.html") for item in plans["rollouts"]["files"]))
if __name__ == "__main__": unittest.main()123version https://git-lfs.github.com/spec/v1oid sha256:59431ef2427510990adc4e994238de3552a0ff723905c6795b5cd9bae8a778a9size 213648612345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.sampling import fps_indicesfrom visual.runtime.test.run_priority_fps_trace import trace_order
class PriorityFPSTraceTests(unittest.TestCase): def test_exact_tie_and_preselection_competition(self): points = np.array([[0., 0., 0.], [1., 0., 0.], [-1., 0., 0.], [0., 2., 0.]]) order = np.array([0, 3, 1, 2]) refs = np.array([[0, 0], [1, 0], [0, 1], [0, 0]], bool) with patch('visual.runtime.test.run_priority_fps_trace.np.random.default_rng', side_effect=AssertionError('trace must not consume RNG')): trace = trace_order(points, order, np.arange(4), np.ones(4), refs) self.assertIsNone(trace[0]['argmax_value_m2']) self.assertEqual(trace[1]['rim_A']['max_min_squared_distance_m2'], 1.) self.assertEqual(trace[1]['uncovered_rim_B']['remaining_count'], 2) self.assertEqual(trace[2]['exact_tie_count'], 2) self.assertEqual(trace[2]['tied_local_indices'], [1, 2]) self.assertEqual(trace[2]['first_tied_local_index'], 1) self.assertEqual(trace[2]['new_reference_ids'], [0]) self.assertEqual(trace[-1]['cumulative_reference_count'], 2)
def test_wrong_tie_winner_fails(self): points = np.array([[0., 0., 0.], [1., 0., 0.], [-1., 0., 0.], [0., 2., 0.]]) with self.assertRaisesRegex(AssertionError, 'first argmax'): trace_order(points, [0, 3, 2, 1], np.arange(4), np.ones(4), np.zeros((4, 0), bool))
def test_fps_consumes_one_initial_integer_draw(self): points = np.array([[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) actual_factory = np.random.default_rng calls = {'factory': 0, 'integers': 0} class Spy: def __init__(self, seed): self.inner = actual_factory(seed) def integers(self, *args, **kwargs): calls['integers'] += 1 return self.inner.integers(*args, **kwargs) def factory(seed): calls['factory'] += 1 return Spy(seed) with patch('visual.runtime.sampling.np.random.default_rng', side_effect=factory): order = fps_indices(points, 4, seed=17) self.assertEqual(calls, {'factory': 1, 'integers': 1}) self.assertEqual(int(order[0]), int(actual_factory(17).integers(len(points))))
def test_duplicate_xyz_and_annotation_independence(self): points = np.array([[0., 0., 0.], [0., 0., 0.], [1., 0., 0.], [-1., 0., 0.]], np.float32) order = fps_indices(points, 4, seed=5) self.assertEqual(len(np.unique(order)), 4) flat = np.arange(4) refs_a = np.zeros((4, 2), bool) refs_b = np.ones((4, 2), bool) a = trace_order(points, order, flat, np.ones(4), refs_a) b = trace_order(points, order, flat, np.ones(4), refs_b, {'negative': np.ones(4, bool)}) self.assertEqual([x['candidate_local_index'] for x in a], [x['candidate_local_index'] for x in b]) self.assertEqual([x['argmax_value_m2'] for x in a], [x['argmax_value_m2'] for x in b]) np.testing.assert_array_equal(order, fps_indices(points, 4, seed=5))
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111"""Numerical contracts for evaluation truth, quantization and scale interventions."""from dataclasses import replaceimport unittest
import numpy as np
from visual.runtime.geometry import process_geometryfrom visual.runtime.test.normal_diagnostics import ( angular_error, box_primitives, metrics, normal_blockers, oracle, quantize, ray_box, real_regions, rim_region, subframe, synthetic_case, synthetic_frame,)
K = np.array([[256., 0, 256], [0, 256, 256], [0, 0, 1]])
class NormalDiagnosticsTest(unittest.TestCase): def test_paired_quantization_alone_creates_planar_variation(self): frame, truth, regions = synthetic_case('tilted', K, z0=.25, phase_m=.00025) before = frame.depth.copy() clean = metrics(process_geometry(frame).objects[0], regions['plane'], truth) q = replace(frame, depth=quantize(frame.depth)) noisy = metrics(process_geometry(q).objects[0], regions['plane'], truth) self.assertLess(clean['angular_error_deg']['p95'], .003) self.assertLess(clean['variation_deg']['p95'], .005) self.assertGreater(noisy['angular_error_deg']['p95'], 10) self.assertGreater(noisy['high_20_fraction_of_valid'], .1) self.assertEqual(clean['normals'], noisy['normals']) self.assertEqual(noisy['depth_discontinuity'], 0) np.testing.assert_array_equal(before, frame.depth) delta = q.depth.astype(float)-frame.depth self.assertLessEqual(delta.max(), 1e-7) self.assertGreaterEqual(delta.min(), -.0010001)
def test_front_plane_quantization_preserves_zero_variation(self): frame, truth, regions = synthetic_case('front', K, z0=.25025) result = process_geometry(replace(frame, depth=quantize(frame.depth))).objects[0] row = metrics(result, regions['plane'], truth) self.assertEqual(row['variation_deg']['max'], 0.) self.assertEqual(row['angular_error_deg']['max'], 0.)
def test_step_preserves_jump_with_missing_normals(self): frame, truth, regions = synthetic_case('step', K) f = process_geometry(frame).objects[0] row = metrics(f, regions['edge_band'], truth) self.assertEqual(row['depth_discontinuity'], 500) self.assertEqual(int(f.normal_valid[131:381, 255:257].sum()), 0) self.assertEqual(row['high_20_count'], 0) self.assertEqual(row['normal_valid_fraction'], 2/3)
def test_subsampling_keeps_source_pixel_centres_in_cv(self): frame, _, _ = synthetic_case('tilted', K) original = process_geometry(frame).geometry.xyz for stride in (2, 4): sub = subframe(frame, stride) np.testing.assert_array_equal(sub.depth, frame.depth[::stride, ::stride]) np.testing.assert_allclose(process_geometry(sub).geometry.xyz, original[::stride, ::stride], atol=0, rtol=0)
def test_ray_box_parallel_outside_and_signed_face(self): dirs = np.array([[0., 0, 1], [0, 1, 0], [0, 0, -1]]) z, face = ray_box(np.array([0., 0, -2]), dirs, np.zeros(3), np.ones(3)) self.assertEqual(z[0], 1.) self.assertEqual(face[0], 4) # -z face self.assertTrue(np.isnan(z[1:]).all())
def test_pose_oracle_and_plane_roi_do_not_depend_on_variation(self): k = np.array([[100., 0, 32], [0, 100, 32], [0, 0, 1]]) frame = synthetic_frame(np.full((64, 64), .3, np.float32), k, np.ones((64, 64), bool)) pose = np.array([0., 0, .4, 1, 0, 0, 0]) half = np.array([.07, .07, .1]) truth = oracle(frame, pose, [(np.zeros(3), half)]) gt = np.isfinite(truth['depth']) result = process_geometry(frame) regions, _, _ = real_regions(frame, result, gt, truth, 0, half) self.assertGreater(regions['plane_interior'].sum(), 100) np.testing.assert_allclose(truth['depth'][gt], .3, atol=1e-14) error = angular_error(result.objects[0].normals, truth['normals']) self.assertLess(np.nanmax(error[regions['plane_interior']]), 1e-5) result.objects[0].normal_variation_rad[:] = 2. regions2, _, _ = real_regions(frame, result, gt, truth, 0, half) np.testing.assert_array_equal(regions['plane_interior'], regions2['plane_interior'])
def test_hollow_box_oracle_has_open_hole_and_physical_rim(self): # Local x points toward camera, local y/z span the image. k = np.array([[100., 0, 64], [0, 100, 64], [0, 0, 1]]) frame = synthetic_frame(np.full((128, 128), .4, np.float32), k, np.ones((128, 128), bool)) # Rotation around local y by +90deg: world x<-local z, world z<- -local x. pose = np.array([0., 0, .5, np.sqrt(.5), 0, np.sqrt(.5), 0]) truth = oracle(frame, pose, box_primitives(.1, .025, np.array([0., 0.]))) self.assertTrue(np.isnan(truth['depth'][64, 64])) self.assertAlmostEqual(truth['depth'][64, 80], .4) visible = np.isfinite(truth['depth']) rim, _ = rim_region(frame, truth, visible, pose, .1, .025, np.array([0., 0.])) self.assertGreater(rim.sum(), 30) self.assertFalse(rim[64, 80]) # Outer face far from physical aperture edge. hidden, _ = rim_region(frame, truth, np.zeros_like(visible), pose, .1, .025, np.array([0., 0.])) self.assertEqual(hidden.sum(), 0)
def test_mask_cut_only_removes_support_and_reasons_cover_loss(self): frame, truth, _ = synthetic_case('front', K, z0=.25025) mask = frame.masks[0].copy(); mask[:, 256:] = False result = process_geometry(replace(frame, masks={0: mask})) row = metrics(result.objects[0], mask, truth) self.assertEqual(row['high_5_count'], 0) self.assertEqual(row['depth_discontinuity'], 0) blockers = normal_blockers(result, 0) self.assertEqual(blockers['unexplained'], 0) self.assertEqual(blockers['unavailable'], blockers['reasons_nonexclusive']['mask'])
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475"""Task 02-A: paired quantization and saved RGB-D normal reliability diagnostics.
CPU only, fresh UUID output directory, no inference, estimator changes or uploads.Run with WANDB_MODE=disabled for entirely local experiment tracking."""from __future__ import annotations
import argparsefrom dataclasses import fields, replaceimport htmlimport importlib.metadataimport jsonfrom pathlib import Pathimport platformimport sys
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltfrom matplotlib.patches import Patchimport numpy as np
REPO = Path(__file__).resolve().parents[3]sys.path.insert(0, str(REPO))from utils.experiment_artifacts import digestsfrom utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import GeometryParameters, process_geometryfrom visual.runtime.rgbd import BOX, PEG, iter_saved_rgbdfrom visual.runtime.test.normal_diagnostics import ( angular_error, box_primitives, dilate, endpoints, erode, metrics, normal_blockers, oracle, pose_rotation, quantize, real_regions, rim_region, scale_probe, stats, synthetic_case,)
OBJECTS = {'peg': PEG, 'box': BOX}COLORS = {'plane': '#00ffcc', 'seam': '#ff8000', 'rim': '#ffdd00', 'occlusion': '#ff55cc', 'contamination': '#ff2222', 'mask_cut': '#4488ff'}
def save_json(path, value): path.write_text(json.dumps(value, indent=2, allow_nan=False)+'\n', encoding='utf-8')
def summarize_rows(rows, values, errors=None): """Micro averages and pooled quantiles; no averaging per-frame percentiles.""" keys = ('region_pixels', 'points', 'normals', 'variation_valid', 'depth_discontinuity', 'mask_boundary', 'invalid_depth_boundary', 'incomplete_normal_neighbours', 'high_5_count', 'high_10_count', 'high_20_count', 'high_30_count', 'jump_or_high20_count') total = {k: sum(r[k] for r in rows) for k in keys} n, nv, vv = total['points'], total['normals'], total['variation_valid'] total.update(frames=len(rows), normal_valid_fraction=nv/n if n else None, variation_valid_fraction=vv/n if n else None, variation_deg=stats(np.concatenate(values))) rn = total['region_pixels'] total.update(observed_fraction_of_region=n/rn if rn else None, normal_fraction_of_region=nv/rn if rn else None, jump_or_high20_fraction_of_region=total['jump_or_high20_count']/rn if rn else None) total['variation_hist_5deg'] = np.sum([r['variation_hist_5deg'] for r in rows], axis=0).tolist() for t in (5, 10, 20, 30): total[f'high_{t}_fraction_of_valid'] = total[f'high_{t}_count']/vv if vv else None total[f'high_{t}_fraction_of_points'] = total[f'high_{t}_count']/n if n else None if errors is not None: total['angular_error_deg'] = stats(np.concatenate(errors)) return total
def synthetic_experiment(output, intrinsic): rows, primaries, scales = [], {}, [] for kind in ('front', 'tilted', 'crease', 'step'): for z in (.2, .25, .35, .6, 1.): for phase in (0., .00025, .0005, .00075): frame, truth, regions = synthetic_case(kind, intrinsic, z0=z, phase_m=phase) original = process_geometry(frame) float_feature = original.objects[PEG] runs = {'float': (frame, original)} for mode in ('floor', 'nearest'): changed = replace(frame, depth=quantize(frame.depth, mode)) runs[mode] = (changed, process_geometry(changed)) row = dict(geometry=kind, z0_m=z, phase_m=phase, conditions={}) for mode, (observation, result) in runs.items(): f = result.objects[PEG] row['conditions'][mode] = dict( regions={k: metrics(f, m, truth) for k, m in regions.items()}, all_support=metrics(f, f.valid_points, truth), depth_change_mm=stats((observation.depth-frame.depth)[frame.masks[PEG]]*1000)) rows.append(row) if z == .25 and phase == .00025: primaries[kind] = (frame, truth, regions, runs) if kind == 'tilted' and phase == .00025: qframe, qresult = runs['floor'] scales.append(dict(z0_m=z, rows=scale_probe(qframe, qresult.objects[PEG], PEG, regions['plane'], truth))) # Controls: observation cuts of an exactly flat surface do not create a corner. frame, truth, _ = synthetic_case('front', intrinsic, z0=.25025) mask = frame.masks[PEG].copy(); mask[:, 256:] = False cut = replace(frame, masks={PEG: mask}) hole_depth = frame.depth.copy(); hole_depth[240:272, 240:272] = 0 hole = replace(frame, depth=hole_depth) controls = {} for name, observation in [('mask_cut', cut), ('invalid_depth_hole', hole)]: result = process_geometry(observation) controls[name] = dict(metrics=metrics(result.objects[PEG], observation.masks[PEG], truth), blockers=normal_blockers(result, PEG)) synthetic_plot(output/'synthetic.png', primaries) return dict(primary_z0_m=.25, primary_phase_m=.00025, primary_quantization='floor', depth_sweep_m=[.2, .25, .35, .6, 1.], phase_sweep_m=[0, .00025, .0005, .00075], slope_xy=[.4, -.25], crease_slopes_xy=[[-.6, .15], [.6, .15]], step_m=.05, mask_bounds_vu=[128, 384, 128, 384], edge_band_half_width_px=3, planar_border_margin_px=3, controls=controls, cases=rows, scale_sweep=scales)
def synthetic_plot(path, primary): fig, axes = plt.subplots(4, 5, figsize=(18, 13), constrained_layout=True) for axs, (kind, (frame, truth, regions, runs)) in zip(axes, primary.items()): clean, q = runs['float'][1].objects[PEG], runs['floor'][1].objects[PEG] images = [np.where(frame.masks[PEG], frame.depth, np.nan)*1000, np.rad2deg(clean.normal_variation_rad), np.rad2deg(q.normal_variation_rad), angular_error(q.normals, truth), np.where(q.valid_points, q.normal_valid.astype(float)+2*q.depth_discontinuity, np.nan)] titles = [f'{kind}: float depth (mm)', 'Float variation (deg)', '1mm floor variation (deg)', '1mm floor normal error (deg)', 'Normal valid=1, depth jump=+2'] for j, (ax, a, title) in enumerate(zip(axs, images, titles)): im = ax.imshow(a, vmin=0 if j in (1, 2, 3, 4) else None, vmax=45 if j in (1, 2, 3) else 3 if j == 4 else None, cmap='turbo') ax.set(xlim=(122, 390), ylim=(390, 122), title=title); ax.axis('off') fig.colorbar(im, ax=ax, shrink=.7) fig.suptitle('Paired synthetic observations: same camera, masks and extractor; only depth quantized\n' 'fx=fy=256; z0=250.25mm; no noise or filtering', fontsize=14) fig.savefig(path, dpi=130); plt.close(fig)
def real_plot(path, frame, result, regions, maps, oracles): fig, axes = plt.subplots(3, 4, figsize=(18, 14), constrained_layout=True) axes = axes.ravel() axes[0].imshow(frame.rgb); axes[0].set_title('RGB with evaluation regions') plane = regions['peg']['plane_interior'] overlays = dict(plane=plane, seam=regions['peg']['face_seam_2px'], rim=regions['box']['hole_rim'], occlusion=regions['peg']['occlusion_2px']|regions['box']['occlusion_2px'], contamination=(result.objects[PEG].valid_points & regions['peg']['contamination'])| (result.objects[BOX].valid_points & regions['box']['contamination']), mask_cut=regions['peg']['same_plane_tracker_cut_2px']) for name, mask in overlays.items(): if mask.any(): axes[0].contour(mask, levels=[.5], colors=[COLORS[name]], linewidths=.65) axes[0].legend(handles=[Patch(color=COLORS[k], label=k) for k in COLORS], fontsize=8, loc='upper right') support = result.objects[PEG].valid_points | result.objects[BOX].valid_points d = np.where(support, frame.depth*1000, np.nan) im = axes[1].imshow(d, cmap='turbo', vmin=150, vmax=700) axes[1].set_title('Observed depth (mm), fixed scale'); fig.colorbar(im, ax=axes[1], shrink=.7) for name, base in [('peg', 2), ('box', 7)]: f = result.objects[OBJECTS[name]] var = np.rad2deg(f.normal_variation_rad) error = angular_error(f.normals, oracles[name]['normals']) error[~regions[name]['gt_visible']] = np.nan panel = [(var, 'normal variation (deg)', 45, 'turbo'), (np.where(f.valid_points, f.normal_valid, np.nan), 'normal validity', 1, 'viridis'), (error, 'normal error vs GT (deg)', 45, 'turbo')] for j, (a, title, vmax, cmap) in enumerate(panel): im = axes[base+j].imshow(a, cmap=cmap, vmin=0, vmax=vmax) axes[base+j].set_title(f'{name}: {title}'); fig.colorbar(im, ax=axes[base+j], shrink=.7) boundary = np.zeros((*frame.depth.shape, 3)) boundary[..., 0] = f.depth_discontinuity boundary[..., 1] = f.mask_boundary boundary[..., 2] = f.depth_validity_boundary axes[base+3].imshow(boundary) axes[base+3].set_title(f'{name}: jump / mask / invalid = R/G/B') # Peg-only zoom shows quantization terraces and selected broad planar interior. y, x = np.nonzero(plane) if len(x): lo_x, hi_x, lo_y, hi_y = max(0, x.min()-8), x.max()+8, max(0, y.min()-8), y.max()+8 else: lo_x, hi_x, lo_y, hi_y = 0, 511, 0, 511 f = result.objects[PEG] axes[6].imshow(np.where(f.valid_points, frame.depth*1000, np.nan), cmap='turbo') if plane.any(): axes[6].contour(plane, [.5], colors=['#00ffcc'], linewidths=.6) axes[6].set_title('Peg depth terraces; cyan=verified plane ROI') axes[6].set(xlim=(lo_x, hi_x), ylim=(hi_y, lo_y)) axes[11].imshow(np.rad2deg(f.normal_variation_rad), cmap='turbo', vmin=0, vmax=45) if plane.any(): axes[11].contour(plane, [.5], colors=['#00ffcc'], linewidths=.6) axes[11].set_title('Same Peg crop: variation (0-45 deg)') axes[11].set(xlim=(lo_x, hi_x), ylim=(hi_y, lo_y)) # Full panels share a fixed object viewport for comparisons between frames. for i, ax in enumerate(axes): if i not in (6, 11): ax.set(xlim=(0, 511), ylim=(511, 0)) ax.axis('off') fig.suptitle(f'Source {frame.source_frame}: observed features; GT used only to evaluate regions\n' 'Black validity=unavailable; NaN variation is missing, not zero. Scales fixed across frames.', fontsize=14) fig.savefig(path, dpi=130); plt.close(fig)
def boundary_plot(path, frame, result, regions): fig, axes = plt.subplots(2, 4, figsize=(16, 10), constrained_layout=True) for axs, (name, object_id) in zip(axes, OBJECTS.items()): f = result.objects[object_id] region = regions[name] axs[0].imshow(frame.rgb) for key, color in [('face_seam_2px', '#ff8000'), ('occlusion_2px', '#ff55cc'), ('same_plane_tracker_cut_2px', '#4488ff'), ('hole_rim', '#ffff00')]: if key in region and region[key].any(): axs[0].contour(region[key], [.5], colors=[color], linewidths=.8) axs[0].set_title(f'{name}: GT seam=orange, rim=yellow\nocclusion=pink, same-face mask cut=blue') im = axs[1].imshow(np.rad2deg(f.normal_variation_rad), cmap='turbo', vmin=0, vmax=45) axs[1].set_title('Observed normal variation (deg)'); fig.colorbar(im, ax=axs[1], shrink=.65) axs[2].imshow(np.where(f.valid_points, f.normal_valid, np.nan), cmap='viridis', vmin=0, vmax=1) axs[2].set_title('Normal valid: yellow=1, dark=0') boundary = np.stack((f.depth_discontinuity, f.mask_boundary, f.depth_validity_boundary), -1).astype(float) axs[3].imshow(boundary) axs[3].set_title('Observed jump / mask / invalid = R/G/B') contour = region.get('hole_rim', region['face_seam_2px']) if contour.any(): for ax in axs[1:]: ax.contour(contour, [.5], colors=['white'], linewidths=.65) y, x = np.nonzero(f.object_mask | region['gt_visible']) bounds = (max(0, x.min()-8), min(511, x.max()+8), min(511, y.max()+8), max(0, y.min()-8)) if len(x) else (0, 511, 511, 0) for ax in axs: ax.set(xlim=bounds[:2], ylim=bounds[2:]); ax.axis('off') fig.suptitle(f'Frame {frame.source_frame}: boundary detail; evaluation regions may overlap\n' 'White outline in feature maps: visible physical hole rim (Box) or face seam (Peg).', fontsize=13) fig.savefig(path, dpi=150); plt.close(fig)
def profile_plot(path, frame, result, regions, truth): # Dominant face and its longer image axis, selected independently of features. plane = regions['plane_interior'] if not plane.any(): return labels, counts = np.unique(truth['face'][plane], return_counts=True) face = labels[counts.argmax()] face_roi = plane & (truth['face'] == face) row_counts, col_counts = face_roi.sum(axis=1), face_roi.sum(axis=0) along_v = col_counts.max() > row_counts.max() fixed = int(np.argmax(col_counts if along_v else row_counts)) line_roi = face_roi[:, fixed] if along_v else face_roi[fixed] coords = np.flatnonzero(line_roi) lo, hi = int(coords.min()), int(coords.max()) coord = np.arange(lo, hi+1) vi, ui = (coord, fixed) if along_v else (fixed, coord) good = line_roi[coord] f = result.objects[PEG] fig, axes = plt.subplots(3, 1, figsize=(11, 7), sharex=True, constrained_layout=True) axes[0].plot(coord, frame.depth[vi, ui]*1000, '.-', label='observed 1mm depth', ms=3) axes[0].plot(coord, truth['depth'][vi, ui]*1000, label='analytic GT face, evaluation only', lw=1) axes[0].set_ylabel('Depth (mm)'); axes[0].legend(fontsize=8) for c, label in enumerate(('nx', 'ny', 'nz')): axes[1].plot(coord, np.where(good, f.normals[vi, ui, c], np.nan), label=label) axes[1].set_ylabel('CV unit normal'); axes[1].legend(fontsize=8, ncol=3) axes[2].plot(coord, np.where(good, np.rad2deg(f.normal_variation_rad[vi, ui]), np.nan), label='variation') axis_name, fixed_name = ('v', 'u') if along_v else ('u', 'v') axes[2].axhline(20, color='r', ls=':', lw=1) axes[2].set(ylabel='Variation (deg)', xlabel=f'Source {axis_name}') fig.suptitle(f'Frame {frame.source_frame}, {fixed_name}={fixed}, GT signed face {face}: verified planar pixels only') fig.savefig(path, dpi=140); plt.close(fig) return dict(varying_axis=axis_name, fixed_axis=fixed_name, fixed_index=fixed, signed_face=int(face), axis_min=lo, axis_max=hi, valid_planar_coordinates=coord[good].tolist())
def evaluate(episode_path, masks_path, *, output_root, camera='base_camera', selected=(0, 15, 45, 80, 120)): episode_path, masks_path = Path(episode_path).resolve(), Path(masks_path).resolve() # Check source identity before producing a new evaluation run. tracking_path = masks_path.with_name('tracking.json') if tracking_path.exists(): tracking = json.loads(tracking_path.read_text()) if tracking.get('camera') not in (None, camera): raise ValueError('camera differs from tracking.json') original = Path(tracking.get('input') or episode_path) if original.is_file() and original.resolve() != episode_path and digests(original)[1] != digests(episode_path)[1]: raise ValueError('episode differs from tracking.json') with np.load(episode_path, allow_pickle=False) as archive: required = [f'{camera}/seg', 'peg_id', 'box_id', 'peg_pose', 'box_pose', 'box_hole_pose', 'peg_half_sizes', 'box_hole_radii', 'seed'] missing = set(required)-set(archive.files) if missing: raise ValueError(f'evaluation GT missing: {sorted(missing)}') gt = {k: archive[k] for k in required} with np.load(masks_path, allow_pickle=False) as archive: sources = archive['source_frame'] if sources.ndim != 1 or not len(sources) or len(np.unique(sources)) != len(sources): raise ValueError('source_frame must be unique and nonempty') if set(selected)-set(sources.tolist()): raise ValueError('selected sources absent from tracking archive') iterator = iter_saved_rgbd(episode_path, masks_path, camera=camera) first = next(iterator) from itertools import chain config = dict(task='02-A', input=str(episode_path), masks=str(masks_path), camera=camera, input_sha256=digests(episode_path)[1], masks_sha256=digests(masks_path)[1], baseline_geometry_sha256=digests(REPO/'visual/runtime/geometry.py')[1], selected_sources=list(selected), intrinsic=first.intrinsic.tolist(), parameters=vars(GeometryParameters()), device='cpu', gpu_executed=False, python=platform.python_version(), numpy=np.__version__, platform=platform.platform(), scipy=importlib.metadata.version('scipy'), matplotlib=matplotlib.__version__, roi_depth_residual_m=.0015, roi_metric_edge_margin_m=.004, roi_raster_erosion_px=3, rim_metric_radius_m=.004, rim_raster_radius_px=2, high_variation_degrees=[5, 10, 20, 30], actual_feature_inputs='recorded depth, intrinsic and original tracker masks only', gt_use='evaluation regions, oriented angular truth, analytic depth residuals only') config['diagnostic_source_sha256'] = {str(p.relative_to(REPO)): digests(p)[1] for p in (Path(__file__), Path(__file__).with_name('normal_diagnostics.py'), Path(__file__).with_name('test_normal_diagnostics.py'))} with ExperimentLogger(team='visual', config=config, seed=int(gt['seed']), model='task02a_unchanged_organized_geometry', job_type='evaluate') as logger: output = Path(output_root).resolve()/logger.run_id output.mkdir(parents=True, exist_ok=False) print(f'Output: {output}', flush=True) synthetic = synthetic_experiment(output, first.intrinsic) records, pooled, pooled_errors = [], {}, {} for frame in chain((first,), iterator): s = frame.source_frame result = process_geometry(frame) # Actual feature computation: no GT. half = gt['peg_half_sizes'] box_rotation = pose_rotation(gt['box_pose'][s]) hole_centre = ((gt['box_hole_pose'][s, :3]-gt['box_pose'][s, :3]) @ box_rotation)[1:] boxes = box_primitives(float(half[0]), float(gt['box_hole_radii']), hole_centre) truths = dict(peg=oracle(frame, gt['peg_pose'][s], [(np.zeros(3), half)]), box=oracle(frame, gt['box_pose'][s], boxes)) record = dict(source_frame=s, frame_idx=frame.frame_idx, timestamp=frame.timestamp, overlap_pixels=int(result.geometry.overlap_mask.sum()), objects={}) selected_regions, maps, plane_base = {}, {}, None for name, object_id in OBJECTS.items(): f = result.objects[object_id] seg = gt[f'{camera}/seg'][s] == int(gt[f'{name}_id']) regions, base, boundary_maps = real_regions(frame, result, seg, truths[name], object_id, half=half if name == 'peg' else None) if name == 'peg': plane_base = base if name == 'box': rim, projected = rim_region(frame, truths[name], regions['gt_visible'], gt['box_pose'][s], float(half[0]), float(gt['box_hole_radii']), hole_centre) regions['hole_rim'] = rim regions['hole_rim_normal_valid'] = rim & f.normal_valid regions['hole_rim_normal_invalid'] = rim & ~f.normal_valid boundary_maps['rim_projection'] = projected selected_regions[name], maps[name] = regions, boundary_maps rows = {k: metrics(f, m, truths[name]['normals'] if k.startswith('plane_') else None) for k, m in regions.items()} visible = regions['gt_visible'] residual = (frame.depth-truths[name]['depth'])*1000 observed_z, analytic_z = frame.depth[visible], truths[name]['depth'][visible] expected_floor = (np.floor(truths[name]['depth']*1000)/1000).astype(np.float32) floor_agree_map = visible & (frame.depth == expected_floor) floor_agree = floor_agree_map[visible] row = dict(mask_pixels=int(f.object_mask.sum()), gt_pixels=int(seg.sum()), analytic_hit_gt_fraction=float(np.mean(np.isfinite(truths[name]['depth'][seg]))) if seg.any() else None, depth_consistent_gt_fraction=float(visible.sum()/seg.sum()) if seg.any() else None, depth_residual_mm=stats(residual[visible]), mm_grid_residual_m=stats(np.abs(observed_z-np.rint(observed_z.astype(float)*1000)/1000)), analytic_floor_match_fraction=float(floor_agree.mean()) if visible.any() else None, analytic_floor_match_count=int(floor_agree.sum()), regions=rows, blockers=normal_blockers(result, object_id)) if name == 'peg': plane = regions['plane_interior'] # Derivative geometry: 1-pixel lateral spacing at the same z. row['plane_depth_m'] = stats(frame.depth[plane]) row['plane_lateral_pixel_spacing_mm'] = stats(frame.depth[plane]/frame.intrinsic[0, 0]*1000) row['q_over_2pixel_lateral_span'] = stats(.001/(2*frame.depth[plane]/frame.intrinsic[0, 0])) vv = plane & f.normal_variation_valid matched = vv & erode(floor_agree_map, 2) high = vv & (np.rad2deg(f.normal_variation_rad) > 20) row['plane_floor_dependency_match'] = dict( variation_valid=int(vv.sum()), matched=int(matched.sum()), fraction=float(matched.sum()/vv.sum()) if vv.any() else None, high20=int(high.sum()), high20_matched=int((high & matched).sum()), high20_matched_fraction=float((high & matched).sum()/high.sum()) if high.any() else None) # Same-plane mask cuts and occlusions are evaluated separately. record['objects'][name] = row for region_name, roi in regions.items(): key = f'{name}/{region_name}' vv = roi & f.normal_variation_valid & f.valid_points pooled.setdefault(key, []).append(np.rad2deg(f.normal_variation_rad[vv])) if region_name.startswith('plane_'): nv = roi & f.normal_valid & f.valid_points pooled_errors.setdefault(key, []).append(angular_error(f.normals[nv], truths[name]['normals'][nv])) if s in selected: record['scale_probe'] = scale_probe(frame, result.objects[PEG], PEG, plane_base, truths['peg']['normals']) record['profile'] = profile_plot(output/f'f{s:04d}_profile.png', frame, result, selected_regions['peg'], truths['peg']) real_plot(output/f'f{s:04d}.png', frame, result, selected_regions, maps, truths) boundary_plot(output/f'f{s:04d}_boundaries.png', frame, result, selected_regions) arrays = dict(source_frame=np.array(s), depth_m=frame.depth, intrinsic=frame.intrinsic) for name, object_id in OBJECTS.items(): f = result.objects[object_id] arrays.update({f'{name}/{field.name}': getattr(f, field.name) for field in fields(f)}) arrays.update({f'evaluation/{name}/{k}': v for k, v in selected_regions[name].items()}) arrays[f'evaluation/{name}/analytic_depth_m'] = truths[name]['depth'] arrays[f'evaluation/{name}/face_id'] = truths[name]['face'] np.savez_compressed(output/f'f{s:04d}.npz', **arrays) records.append(record) if len(records) == 1 or len(records) % 20 == 0: print(f'Real frames: {len(records)}/{len(sources)}', flush=True) summary = {} for key, values in pooled.items(): name, region = key.split('/') summary[key] = summarize_rows([r['objects'][name]['regions'][region] for r in records], values, pooled_errors.get(key)) data = dict(run_id=logger.run_id, config=config, git_commit=logger.metadata['git_commit'], git_dirty=logger.metadata['git_dirty'], synthetic=synthetic, evaluated_frames=len(records), selected_source_frames=list(selected), summary=summary, frames=records) save_json(output/'diagnostics.json', data) distribution_plot(output/'distributions.png', data) scale_plot(output/'scale_probe.png', data) write_html(output/'diagnostics.html', data) for path in sorted(output.iterdir()): logger.link_output(path, kind='metrics' if path.suffix == '.json' else None) logger.log(summary, prefix='eval/task02a') logger.record(dataset_sha256=config['input_sha256'], masks_sha256=config['masks_sha256'], evaluation_device='cpu', evaluated_frames=len(records), gpu_executed=False) return output
def distribution_plot(path, data): fig, axes = plt.subplots(2, 2, figsize=(13, 9), constrained_layout=True) xs = np.arange(2.5, 180, 5) for name, ax in zip(('peg', 'box'), axes[0]): keys = ['all', 'plane_interior', 'contamination', 'face_seam_2px', 'occlusion_2px', 'hole_rim'] for key in keys: r = data['summary'].get(f'{name}/{key}') if r and r['variation_valid']: ax.plot(xs, np.array(r['variation_hist_5deg'])/r['variation_valid'], label=f'{key} (n={r["variation_valid"]})') ax.set(xlim=(0, 90), xlabel='Normal variation (deg)', ylabel='Fraction per 5 deg bin', title=f'{name}: pooled 121 frames') ax.legend(fontsize=7) sources = [r['source_frame'] for r in data['frames']] for key in ('all', 'plane_interior', 'contamination', 'face_seam_2px', 'occlusion_2px'): ys = [r['objects']['peg']['regions'][key]['high_20_fraction_of_valid'] for r in data['frames']] axes[1, 0].plot(sources, [np.nan if v is None else v for v in ys], label=key, lw=1) axes[1, 0].set(xlabel='Source frame', ylabel='Fraction >20 deg / valid variation', title='Peg: time distribution') axes[1, 0].legend(fontsize=7) for name, key in [('peg', 'all'), ('box', 'all'), ('box', 'hole_rim')]: ys = [r['objects'][name]['regions'][key]['normal_valid_fraction'] for r in data['frames']] axes[1, 1].plot(sources, [np.nan if v is None else v for v in ys], label=f'{name}/{key}') axes[1, 1].set(xlabel='Source frame', ylabel='Normals / observed points', title='Coverage (missing remains missing)', ylim=(-.05, 1.05)) axes[1, 1].legend(fontsize=8) fig.savefig(path, dpi=140); plt.close(fig)
def scale_plot(path, data): fig, axes = plt.subplots(1, 3, figsize=(15, 5), constrained_layout=True) for r in data['frames']: if 'scale_probe' not in r: continue rows = r['scale_probe'] x = [v['stride_px'] for v in rows] for ax, key in zip(axes[:2], ('angular_error_deg', 'variation_deg')): y = [v['larger_spacing'][key]['p95'] for v in rows] ax.plot(x, y, 'o-', label=f'f{r["source_frame"]}') axes[0].set(ylabel='p95 normal error (deg)', xlabel='Neighbour spacing (px)', title='Verified flat Peg ROI, shared safe region') axes[1].set(ylabel='p95 variation (deg)', xlabel='Neighbour spacing (px)', title='No averaging; same baseline extractor') for s in (1, 2, 4): rows = data['synthetic']['scale_sweep'] axes[2].plot([r['z0_m'] for r in rows], [next(v for v in r['rows'] if v['stride_px']==s)['larger_spacing']['variation_deg']['p95'] for r in rows], 'o-', label=f'synthetic stride={s}') axes[2].set(xlabel='Central depth (m)', ylabel='p95 variation (deg)', title='Tilted plane, fixed K and 1mm quantization') for ax in axes: ax.legend(fontsize=8); ax.grid(alpha=.2) fig.savefig(path, dpi=140); plt.close(fig)
def write_html(path, data): images = ['synthetic.png', 'distributions.png', 'scale_probe.png'] images += [f'f{s:04d}{suffix}.png' for s in data['selected_source_frames'] for suffix in ('', '_boundaries', '_profile')] body = ''.join(f'<p><a href="{p}"><img src="{p}" alt="{p}"></a></p>' for p in images if (path.parent/p).exists()) path.write_text(f'''<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task 02-A</title><style>body{{font:15px system-ui;max-width:1600px;margin:24px auto;padding:16px}}img{{width:100%}}pre{{white-space:pre-wrap}}</style><h1>Task 02-A — normal reliability and depth quantization</h1><p>Run {data['run_id']}; all {data['evaluated_frames']} saved frames; unchanged CPU NumPy extractor.<a href="diagnostics.json">Full numeric metrics, counts, histograms and parameters</a>.</p><p>Actual feature inputs are recorded depth, intrinsic and tracker masks only. GT defines evaluation regionsand oriented normal truth. Plane ROI: visible cuboid face, depth residual ≤1.5mm, 4mm from other faces,then 3px erosion independently per signed face. No selection by measured normal or variation.Hole rim requires analytic physical line proximity (4mm, 2px), not just a segmentation contour.</p><p>20° is a diagnostic threshold, not an edge class. All 5/10/20/30° rates and missing support are reported.Boundary ROIs can overlap; counts are not additive. Pooled values are pixel-frame weighted.Subsampling probes preserve pixel centres and compare baseline values on the same centres; they changeboth stencil span and normal-comparison separation. Only verified planar regions are compared.</p><p>GT annotations and analytic depth in NPZ are under evaluation/. They never replace observed depth.No smoothing, PCL, new production estimator, structural classification, sampling or Graph changes.</p>{body}<details><summary>Configuration</summary><pre>{html.escape(json.dumps(data['config'], indent=2))}</pre></details></html>''', encoding='utf-8')
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, default=REPO/'visual/data/step2/ep000.npz') parser.add_argument('--masks', type=Path, default=REPO/'visual/results/runtime_tracking/ep000/masks.npz') parser.add_argument('--camera', default='base_camera') parser.add_argument('--out', type=Path, default=REPO/'visual/results/normal_diagnostics') args = parser.parse_args() print(evaluate(args.input, args.masks, output_root=args.out, camera=args.camera))
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""Fused CUDA patch-local PCA5. Imported only for an explicit CUDA backend.
One warp per observed centre: exact 25-bit connectivity, float64 covariance,closed-form symmetric eigensystem, and a guarded Torch/LAPACK fallback."""import torchimport tritonimport triton.language as tlfrom triton.language.extra.cuda import libdevice
@triton.jitdef _pca5(XYZ, SUPPORT, CENTRES, NORMALS, VALID, COV, FALLBACK, H:tl.constexpr, W:tl.constexpr, ABS:tl.constexpr, REL:tl.constexpr): pid=tl.program_id(0) cv=tl.load(CENTRES+pid*2);cu=tl.load(CENTRES+pid*2+1) k=tl.arange(0,32);r=k//5;c=k%5 v=cv+r-2;u=cu+c-2 inside=(k<25)&(v>=0)&(v<H)&(u>=0)&(u<W) index=v*W+u available=tl.load(SUPPORT+index,inside,other=0) x=tl.load(XYZ+index*3,inside,other=0).to(tl.float64) y=tl.load(XYZ+index*3+1,inside,other=0).to(tl.float64) z=tl.load(XYZ+index*3+2,inside,other=0).to(tl.float64) right_inside=inside&(c<4)&(u+1<W) down_inside=inside&(r<4)&(v+1<H) rs=tl.load(SUPPORT+index+1,right_inside,other=0) ds=tl.load(SUPPORT+index+W,down_inside,other=0) rz=tl.load(XYZ+(index+1)*3+2,right_inside,other=0).to(tl.float64) dz=tl.load(XYZ+(index+W)*3+2,down_inside,other=0).to(tl.float64) right_ok=available&rs&right_inside&(tl.abs(z-rz)<=ABS+REL*tl.minimum(z,rz)) down_ok=available&ds&down_inside&(tl.abs(z-dz)<=ABS+REL*tl.minimum(z,dz)) bits=1<<k right=tl.sum(tl.where(right_ok,bits,0),0) down=tl.sum(tl.where(down_ok,bits,0),0) reached=1<<12 for _ in range(24): reached=reached|((reached&right)<<1)|((reached>>1)&right)|((reached&down)<<5)|((reached>>5)&down) component=(k<25)&((reached&bits)!=0) count=tl.sum(component.to(tl.int32),0) cx=tl.load(XYZ+(cv*W+cu)*3).to(tl.float64) cy=tl.load(XYZ+(cv*W+cu)*3+1).to(tl.float64) cz=tl.load(XYZ+(cv*W+cu)*3+2).to(tl.float64) dx=tl.where(component,x-cx,0);dy=tl.where(component,y-cy,0);ddz=tl.where(component,z-cz,0) den=tl.maximum(count,1).to(tl.float64) mx=tl.sum(dx,0)/den;my=tl.sum(dy,0)/den;mz=tl.sum(ddz,0)/den xx=tl.sum(dx*dx,0)/den-mx*mx;yy=tl.sum(dy*dy,0)/den-my*my;zz=tl.sum(ddz*ddz,0)/den-mz*mz xy=tl.sum(dx*dy,0)/den-mx*my;xz=tl.sum(dx*ddz,0)/den-mx*mz;yz=tl.sum(dy*ddz,0)/den-my*mz for j in tl.static_range(9): value=tl.where(j==0,xx,tl.where(j==1,xy,tl.where(j==2,xz,tl.where(j==3,xy,tl.where(j==4,yy,tl.where(j==5,yz,tl.where(j==6,xz,tl.where(j==7,yz,zz)))))))) tl.store(COV+pid*9+j,value) scale=tl.maximum(tl.maximum(tl.maximum(tl.abs(xx),tl.abs(yy)),tl.maximum(tl.abs(zz),tl.abs(xy))),tl.maximum(tl.abs(xz),tl.abs(yz))) s=tl.where(scale>0,scale,1.) a=xx/s;b=yy/s;d=zz/s;e=xy/s;f=xz/s;g=yz/s q=(a+b+d)/3. aa=a-q;bb=b-q;dd=d-q p=libdevice.sqrt((aa*aa+bb*bb+dd*dd+2*(e*e+f*f+g*g))/6.) pp=tl.where(p>0,p,1.) ca=aa/pp;cb=bb/pp;cd=dd/pp;ce=e/pp;cf=f/pp;cg=g/pp determinant=ca*(cb*cd-cg*cg)-ce*(ce*cd-cg*cf)+cf*(ce*cg-cb*cf) phi=libdevice.acos(tl.minimum(1.,tl.maximum(-1.,determinant/2.)))/3. largest=q+2*p*libdevice.cos(phi) smallest=q+2*p*libdevice.cos(phi+2.0943951023931953) middle=3*q-smallest-largest ra=a-smallest;rb=b-smallest;rd=d-smallest x1=e*g-f*rb;y1=f*e-ra*g;z1=ra*rb-e*e x2=e*rd-f*g;y2=f*f-ra*rd;z2=ra*g-e*f x3=rb*rd-g*g;y3=g*f-e*rd;z3=e*g-rb*f n1=x1*x1+y1*y1+z1*z1;n2=x2*x2+y2*y2+z2*z2;n3=x3*x3+y3*y3+z3*z3 use1=(n1>=n2)&(n1>=n3);use2=n2>=n3 nx=tl.where(use1,x1,tl.where(use2,x2,x3));ny=tl.where(use1,y1,tl.where(use2,y2,y3));nz=tl.where(use1,z1,tl.where(use2,z2,z3)) length=libdevice.sqrt(nx*nx+ny*ny+nz*nz) safe_length=tl.where(length>0,length,1.) nx=nx/safe_length;ny=ny/safe_length;nz=nz/safe_length rx=a*nx+e*ny+f*nz-smallest*nx ry=e*nx+b*ny+g*nz-smallest*ny rz=f*nx+g*ny+d*nz-smallest*nz residual=libdevice.sqrt(rx*rx+ry*ry+rz*rz) threshold=tl.maximum(1e-16,largest*scale*1e-8) rank=(middle*scale>threshold)&((middle-smallest)*scale>threshold) delicate=(middle*scale<=100*threshold)|((middle-smallest)*scale<=100*threshold) fallback=(count>=6)&((length<1e-10)|(residual>1e-10)|delicate|(residual!=residual)) good=(count>=6)&rank&~fallback flip=nx*cx+ny*cy+nz*cz>0 sign=tl.where(flip,-1.,1.) tl.store(NORMALS+(cv*W+cu)*3,nx*sign,good) tl.store(NORMALS+(cv*W+cu)*3+1,ny*sign,good) tl.store(NORMALS+(cv*W+cu)*3+2,nz*sign,good) tl.store(VALID+cv*W+cu,good) tl.store(FALLBACK+pid,fallback)
def fused_normals(xyz,support,parameters): h,w=support.shape normals=torch.full_like(xyz,float('nan'));valid=torch.zeros_like(support) # torch.nonzero commonly returns column-major strides (1,N); the kernel # explicitly consumes adjacent (v,u) pairs. centres=support.nonzero().contiguous() if not len(centres):return normals,valid covariance=torch.empty((len(centres),3,3),dtype=torch.float64,device=xyz.device) fallback=torch.empty((len(centres),),dtype=torch.bool,device=xyz.device) _pca5[(len(centres),)](xyz,support,centres,normals,valid,covariance,fallback,h,w, parameters.depth_jump_abs_m,parameters.depth_jump_rel,num_warps=1,enable_fp_fusion=False) idx=fallback.nonzero().flatten() if len(idx): values,basis=torch.linalg.eigh(covariance[idx]) threshold=torch.maximum(torch.full_like(values[:,2],1e-16),values[:,2]*1e-8) good=(values[:,1]>threshold)&(values[:,1]-values[:,0]>threshold)&torch.isfinite(values).all(1) vu=centres[idx[good]];vectors=basis[good,:,0] vectors/=torch.linalg.vector_norm(vectors,dim=1)[:,None] flip=(vectors*xyz[vu[:,0],vu[:,1]]).sum(1)>0 vectors=torch.where(flip[:,None],-vectors,vectors) normals[vu[:,0],vu[:,1]]=vectors.to(torch.float32);valid[vu[:,0],vu[:,1]]=True return normals,valid
@triton.jitdef _features(XYZ,VD,MASK,SUPPORT,NORMALS,NV,JM,PV,DISC,MB,VB,IB,VAR,VV,COUNT, H:tl.constexpr,W:tl.constexpr,ABS:tl.constexpr,REL:tl.constexpr,B:tl.constexpr): i=tl.program_id(0)*B+tl.arange(0,B);inside=i<H*W v=i//W;u=i%W vd=tl.load(VD+i,inside,other=0);mask=tl.load(MASK+i,inside,other=0) support=tl.load(SUPPORT+i,inside,other=0);nv=tl.load(NV+i,inside,other=0) z=tl.where(vd,tl.load(XYZ+i*3+2,inside,other=0),0.) nx=tl.where(nv,tl.load(NORMALS+i*3,inside,other=0),0.) ny=tl.where(nv,tl.load(NORMALS+i*3+1,inside,other=0),0.) nz=tl.where(nv,tl.load(NORMALS+i*3+2,inside,other=0),0.) jump_m=tl.full((B,),0.,tl.float32);variation=tl.full((B,),0.,tl.float32) pair_valid=tl.full((B,),False,tl.int1);disc=pair_valid;mb=pair_valid;vb=pair_valid count=tl.full((B,),0,tl.int32) for direction in tl.static_range(4): offset=tl.where(direction==0,-1,tl.where(direction==1,1,tl.where(direction==2,-W,W))) available=inside&tl.where(direction==0,u>0,tl.where(direction==1,u+1<W,tl.where(direction==2,v>0,v+1<H))) q=i+offset qvd=tl.load(VD+q,available,other=0);qm=tl.load(MASK+q,available,other=0) qnv=tl.load(NV+q,available,other=0) qz=tl.where(qvd,tl.load(XYZ+q*3+2,available,other=0),0.) dz=tl.abs(z-qz);both_depth=available&vd&qvd pv=support&both_depth pair_valid=pair_valid|pv jump_m=tl.maximum(jump_m,tl.where(pv,dz,0.)) threshold=tl.full((),ABS,tl.float32)+tl.full((),REL,tl.float32)*tl.minimum(z,qz) disc=disc|(support&both_depth&(dz>threshold)) mb=mb|(available&mask&~qm);vb=vb|(available&support&~qvd) qx=tl.where(qnv,tl.load(NORMALS+q*3,available,other=0),0.) qy=tl.where(qnv,tl.load(NORMALS+q*3+1,available,other=0),0.) qnz=tl.where(qnv,tl.load(NORMALS+q*3+2,available,other=0),0.) cx=ny*qnz-nz*qy;cy=nz*qx-nx*qnz;cz=nx*qy-ny*qx length=libdevice.sqrt(cx*cx+cy*cy+cz*cz) dot=nx*qx+ny*qy+nz*qnz both=available&nv&qnv angle=tl.where(both,libdevice.atan2(length,dot),0.) variation=tl.maximum(variation,angle);count=count+both.to(tl.int32) vv=nv&(count>0) image_boundary=mask&((v==0)|(v==H-1)|(u==0)|(u==W-1)) tl.store(JM+i,tl.where(pair_valid,jump_m,float('nan')),inside) tl.store(PV+i,pair_valid,inside);tl.store(DISC+i,disc,inside) tl.store(MB+i,mb,inside);tl.store(VB+i,vb,inside);tl.store(IB+i,image_boundary,inside) tl.store(VAR+i,tl.where(vv,variation,float('nan')),inside);tl.store(VV+i,vv,inside);tl.store(COUNT+i,count,inside)
def fused_features(xyz,valid_depth,mask,support,normals,normal_valid,parameters): shape=mask.shape result=dict(object_mask=mask,valid_points=support,normals=normals,normal_valid=normal_valid) names=['depth_jump_m','depth_pair_valid','depth_discontinuity','mask_boundary','depth_validity_boundary', 'image_boundary','normal_variation_rad','normal_variation_valid','normal_neighbor_count'] for name in names: dtype=torch.float32 if name in ('depth_jump_m','normal_variation_rad') else torch.uint8 if name=='normal_neighbor_count' else torch.bool result[name]=torch.empty(shape,dtype=dtype,device=xyz.device) _features[(triton.cdiv(mask.numel(),256),)](xyz,valid_depth,mask,support,normals,normal_valid, *[result[name] for name in names],*shape,parameters.depth_jump_abs_m,parameters.depth_jump_rel,256, num_warps=4,enable_fp_fusion=False) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""Phase3 contracts. All FPS calls here use synthetic points, never Task03 data."""import copyfrom types import SimpleNamespaceimport unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.rgbd import PEG, BOXfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_priority_fps_seed_control as controlfrom visual.runtime.test.sampling_evaluation import CoverageMatcher
class Archive(dict): @property def files(self): return list(self)
def synthetic_candidates(): # Common source pixels always point at exactly the same source XYZ. def method(flat): xyz = np.column_stack((np.sin(flat*.3), np.cos(flat*.2), flat*.01)).astype(np.float32) return dict(flat=flat, points=xyz) return dict(S2=method(np.arange(100, 148)), S3=method(np.arange(108, 156)))
def saved_fixture(): """Synthetic 256-row archives with the real shape/quota/field contracts.""" shape = (512, 512) flat = np.arange(np.prod(shape)) xyz = np.column_stack((flat*.001, flat*.002, np.ones(len(flat)))).astype(np.float32).reshape(*shape, 3) geometry = SimpleNamespace(xyz=xyz, observed_mask=lambda oid: (flat < 90000 if oid == PEG else flat >= 90000).reshape(shape)) frame = SimpleNamespace(source_frame=0, depth=np.ones(shape, np.float32)) archive = Archive(source_frame=np.array(0), shape=np.array(shape)) config, metrics, phase2 = dict(conditions={}), {}, dict(methods={}) field_names = ['object_mask', 'valid_points', 'normals', 'normal_valid', 'depth_jump_m', 'depth_pair_valid', 'depth_discontinuity', 'mask_boundary', 'depth_validity_boundary', 'image_boundary', 'normal_variation_rad', 'normal_variation_valid', 'normal_neighbor_count', 'orientation_evidence', 'depth_evidence', 'occluding_evidence', 'occluded_evidence', 'invalid_evidence', 'mask_evidence', 'orientation_score_deg', 'orientation_candidate', 'depth_only_candidate', 'structural_candidate'] for method, (estimator, _, count, _, _) in control.METHODS.items(): candidates = np.sort(np.r_[np.arange(90000, 90000+count-3), control.FIRST[method]]) archive[f'evidence/{estimator}/1/20/orientation_flat'] = candidates phase2['methods'][method] = dict(candidate_flat_indices=candidates.tolist()) for seed in (0, 1, 2): key = f'{method}_n256_r0.25_t20_s{seed}' config['conditions'][key] = dict(method=method, num_points=256, structural_ratio=.25, orientation_threshold_deg=20, seed=seed) first = control.FIRST[method][seed] selected = np.r_[np.arange(129), first, candidates[candidates != first][:126]] box = np.arange(256) >= 129 archive[key+'/flat_index'] = selected archive[key+'/points'] = xyz.reshape(-1, 3)[selected] archive[key+'/pixels_vu'] = np.column_stack(np.unravel_index(selected, shape)) archive[key+'/object_id'] = box.astype(np.int64) archive[key+'/priority_selected'] = np.r_[np.arange(129) < 32, np.arange(127) < 32] archive[key+'/depth_priority_selected'] = np.zeros(256, bool) for name in field_names: value = np.zeros((256, 3), np.float32) if name == 'normals' else np.zeros(256, bool) if name in ('object_mask', 'valid_points'): value[:] = True if name in ('orientation_candidate', 'structural_candidate'): value[box] = True archive[key+'/metadata/'+name] = value objects = {} for name, budget in [('peg', 129), ('box', 127)]: objects[name] = dict(counts=dict(budget=budget, selected=budget, priority=32, orientation_priority=32, depth_priority=0, surface_fps=budget-32)) n = control.FINAL[method][seed] objects['box']['structural'] = dict(tolerance={'2px_3mm': dict(gt_visible=103, sampled=n, gt_coverage=n/103)}) metrics[key] = dict(objects=objects) return archive, config, metrics, frame, geometry, phase2
class SharedInitialTests(unittest.TestCase): def select(self, candidates=None): return control.select_control(synthetic_candidates() if candidates is None else candidates, expected_shared=40, expected_initial=128)
def test_initial_included_total_32_exact_local_global_no_rng(self): candidates = synthetic_candidates() before = copy.deepcopy(candidates) with patch.object(control, 'fps_indices', wraps=fps_indices) as calls: orders, info = self.select(candidates) self.assertEqual(calls.call_count, 2) self.assertEqual(info['candidate_local_index'], {'S2': 28, 'S3': 20}) self.assertEqual(info['initial_rng_draws'], 0) for method, row in orders.items(): self.assertEqual(len(row['flat']), 32) self.assertEqual(len(set(row['flat'])), 32) self.assertEqual(row['flat'][0], 128) np.testing.assert_array_equal(candidates[method]['flat'][row['local']], row['flat']) np.testing.assert_array_equal(candidates[method]['points'][row['local']], row['xyz']) for field in ('flat', 'points'): np.testing.assert_array_equal(candidates[method][field], before[method][field]) np.testing.assert_array_equal(orders['S2']['xyz'][0], orders['S3']['xyz'][0])
def test_initial_path_never_constructs_rng_even_when_seed_changes(self): points = synthetic_candidates()['S2']['points'] with patch('visual.runtime.sampling.np.random.default_rng', side_effect=AssertionError('RNG draw')): a = fps_indices(points, 32, seed=0, initial=[28]) b = fps_indices(points, 32, seed=98765, initial=[28]) np.testing.assert_array_equal(a, b) self.assertEqual(a[0], 28)
def test_intersection_and_initial_mismatch_stop_before_fps(self): for kwargs in (dict(expected_shared=39, expected_initial=128), dict(expected_shared=40, expected_initial=127)): with patch.object(control, 'fps_indices', side_effect=AssertionError('must stop before FPS')): with self.assertRaises(ValueError): control.select_control(synthetic_candidates(), **kwargs)
def test_order_xyz_and_short_count_mismatch_stop_before_fps(self): for mutation in ('order', 'xyz', 'count'): c = synthetic_candidates() if mutation == 'order': c['S2']['flat'] = c['S2']['flat'][::-1] elif mutation == 'xyz': c['S3']['points'][20, 0] += .001 else: c['S2'] = {k: v[:31] for k, v in c['S2'].items()} with patch.object(control, 'fps_indices', side_effect=RuntimeError('must stop before FPS')): with self.assertRaises((ValueError, AssertionError)): self.select(c)
def test_invalid_fps_order_is_rejected(self): for order in (np.zeros(32, np.int64), np.arange(31), np.r_[28, np.arange(30), 999]): with patch.object(control, 'fps_indices', return_value=order): with self.assertRaises(ValueError): self.select() with patch.object(control, 'fps_indices', return_value=np.arange(32)): with self.assertRaisesRegex(ValueError, 'initial included'): self.select()
def test_gt_annotation_change_cannot_change_control_selection(self): candidates = synthetic_candidates() orders_a, _ = self.select(candidates) xyz = np.zeros((1, 200, 3), np.float32) geometry = SimpleNamespace(valid_depth=np.ones((1, 200), bool), xyz=xyz, observed_mask=lambda oid: np.ones((1, 200), bool)) frame = SimpleNamespace(depth=np.ones((1, 200), np.float32)) annotations = [((np.array([[128., 0.]]), np.zeros((1, 3))), np.zeros((1, 200), bool)), ((np.array([[999., 999.]]), np.ones((1, 3))*100), np.ones((1, 200), bool))] scores = [] for refs, negative in annotations: matcher = CoverageMatcher(geometry, BOX, refs) scores.append(control.score_control(orders_a, matcher, frame, {'negative': negative})) orders_b, _ = self.select(candidates) # synthetic repeat only for method in control.METHODS: np.testing.assert_array_equal(orders_a[method]['flat'], orders_b[method]['flat']) self.assertNotEqual(scores[0][method]['negative_roi'], scores[1][method]['negative_roi']) with self.assertRaises(TypeError): control.select_control(candidates, gt={})
class SavedAnalysisTests(unittest.TestCase): def test_source_feature_role_alignment_without_fps(self): fixture = saved_fixture() with control.forbid_sampling(): candidates, selected, checks = control.load_saved(*fixture) self.assertEqual(len(checks), 6) for method in control.METHODS: self.assertEqual(len(candidates[method]['flat']), control.METHODS[method][2]) for seed in (0, 1, 2): self.assertEqual(selected[method][seed]['flat'][0], control.FIRST[method][seed]) self.assertTrue(all(c['feature_and_role_alignment'] for c in checks.values()))
def test_corrupt_source_feature_role_or_order_fails(self): key = 'S2_n256_r0.25_t20_s1' for field in ('points', 'metadata/normals', 'metadata/orientation_candidate', 'priority_selected', 'pixels_vu'): fixture = saved_fixture() array = fixture[0][key+'/'+field] fixture[0][key+'/'+field] = array.copy() array = fixture[0][key+'/'+field] if field == 'metadata/normals': array[0, 0] = 1 # same source pixel, inconsistent saved feature elif field == 'priority_selected': array[129] = False elif field == 'metadata/orientation_candidate': array[129] = False else: array[0, 0] += 1 with control.forbid_sampling(), self.assertRaises((ValueError, AssertionError)): control.load_saved(*fixture)
def test_seed0_reused_and_only_seed1_2_matched_without_fps(self): flat = np.arange(32, dtype=np.int64) xyz = np.zeros((32, 3), np.float32) frame = SimpleNamespace(depth=np.ones((1, 32), np.float32)) negatives = dict(negative=np.zeros((1, 32), bool)) rows = {m: {s: dict(flat=flat, xyz=xyz, final=dict(sampled=10, gt_coverage=10/103)) for s in (0, 1, 2)} for m in control.METHODS} trace = [dict(xyz_m=p.tolist(), flat_index=int(f), depth_m=1., rim_reference_matched=i == 1, matched_rim_reference_ids=[2, 3] if i == 1 else [], selected_negative_roi=dict(negative=False, known_negative_union=False)) for i, (p, f) in enumerate(zip(xyz, flat))] phase2 = dict(methods={m: dict(stored_priority_flat_indices=flat.tolist(), trace=trace, priority_reference_ids=[2, 3], priority_reference_count=2) for m in control.METHODS}) phase1 = dict(frames=[dict(conditions={m: dict(reference_ids=dict(P=[2, 3])) for m in control.METHODS})]) calls = [] def match(selected, **kwargs): calls.append(selected.copy()) self.assertEqual(kwargs, dict(px=2., m=.003)) return np.array([2, 3]), selected[1:2] with control.forbid_sampling(): result = control.summarize_saved(rows, phase1, phase2, SimpleNamespace(reference_hits=match), frame, negatives) self.assertEqual(len(calls), 4) for method in control.METHODS: self.assertEqual(result[method]['0']['priority_reference_ids'], [2, 3]) self.assertEqual(result[method]['0']['rim_matching_node_count'], 1) self.assertEqual(result[method]['0']['final_sampling']['numerator'], 10) phase2['methods']['S2']['priority_reference_ids'] = [2, 4] with control.forbid_sampling(), self.assertRaisesRegex(ValueError, 'Phase1/2 IDs'): control.summarize_saved(rows, phase1, phase2, SimpleNamespace(reference_hits=match), frame, negatives)
def test_joint_same_pair_and_reference_dedup(self): shape = (1, 10) xyz = np.zeros((*shape, 3), np.float32) xyz[0, 3] = [.1, 0, 0] geometry = SimpleNamespace(valid_depth=np.ones(shape, bool), xyz=xyz, observed_mask=lambda oid: np.ones(shape, bool)) # Selected nodes: 0 is near ref 0 only in 2D, 3 only in XYZ. refs = (np.array([[0., 0.], [7., 0.]]), np.array([[.1, 0, 0], [0, 0, 0]])) matcher = CoverageMatcher(geometry, BOX, refs) ids, hits = matcher.reference_hits(np.array([0, 3], np.int64)) self.assertEqual(ids.tolist(), []) self.assertEqual(hits.tolist(), []) ids, hits = matcher.reference_hits(np.array([6, 7, 8], np.int64)) self.assertEqual(ids.tolist(), [1]) self.assertEqual(len(hits), 3) frame = SimpleNamespace(depth=np.ones(shape, np.float32)) a = np.zeros(shape, bool); b = a.copy(); a[0, [6, 7]] = True; b[0, [7, 8]] = True summary = control.point_summary(np.array([6, 7, 8]), frame, dict(a=a, b=b), ids, hits, xyz[0, [6, 7, 8]]) self.assertEqual(summary['negative_roi']['known_negative_union']['count'], 3) self.assertEqual(summary['priority_reference_count'], 1) with self.assertRaisesRegex(ValueError, 'deduplicated'): control.point_summary(np.array([6, 7, 8]), frame, dict(a=a), [1, 1], hits, xyz[0, [6, 7, 8]])
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Device-resident Torch PCA5 comparison, independent of the NumPy adapter.
Depth and tracker masks stay on the selected device. Float64 PCA preserves thereference policy; CUDA measurements require an actual CUDA host. CPU Torch isused for executable numerical contract tests, not claimed as a fast backend."""from __future__ import annotations
import numpy as npimport torch
from visual.runtime.geometry import GeometryParametersfrom visual.runtime.rgbd import PEG, BOX
class TorchPCA5: def __init__(self, intrinsic, shape, *, device='cuda', parameters=GeometryParameters(), backend='eigh'): k = np.asarray(intrinsic, float) if (k.shape != (3, 3) or not np.isfinite(k).all() or min(k[0, 0], k[1, 1]) <= 0 or not np.allclose(k[[0, 1, 2, 2, 2], [1, 0, 0, 1, 2]], [0, 0, 0, 0, 1])): raise ValueError('invalid zero-skew intrinsic') self.device = torch.device(device) if self.device.type == 'cuda' and self.device.index is None: self.device = torch.device('cuda', torch.cuda.current_device()) if self.device.type == 'mps': raise ValueError('MPS cannot preserve the float64 PCA contract; use CPU or CUDA') self.shape, self.parameters = tuple(shape), parameters if backend not in ('eigh', 'triton', 'triton_fused'): raise ValueError('unknown Torch PCA backend') if backend.startswith('triton') and self.device.type!='cuda': raise ValueError('Triton backend requires CUDA') self.backend=backend h, w = self.shape if h < 1 or w < 1: raise ValueError('shape must be positive') self.ux = (torch.arange(w, dtype=torch.float64, device=self.device)+.5-k[0, 2])[None] self.vy = (torch.arange(h, dtype=torch.float64, device=self.device)+.5-k[1, 2])[:, None] self.fx, self.fy = float(k[0, 0]), float(k[1, 1]) dv, du = torch.meshgrid(torch.arange(-2, 3, device=self.device), torch.arange(-2, 3, device=self.device), indexing='ij') self.dv, self.du = dv, du self.bits = (torch.ones(25, dtype=torch.int64, device=self.device) << torch.arange(25, device=self.device)).reshape(5, 5)
def _jump(self, a, b): return (a-b).abs() > self.parameters.depth_jump_abs_m+self.parameters.depth_jump_rel*torch.minimum(a, b)
def _normals(self, xyz, support): if self.backend.startswith('triton'): from visual.runtime.test.pca_triton import fused_normals return fused_normals(xyz,support,self.parameters) h, w = self.shape normals = torch.full_like(xyz, float('nan')) valid = torch.zeros_like(support) centres = support.nonzero() if not len(centres): return normals, valid v = centres[:, 0, None, None]+self.dv u = centres[:, 1, None, None]+self.du inside = (v >= 0) & (v < h) & (u >= 0) & (u < w) v, u = v.clamp(0, h-1), u.clamp(0, w-1) available = inside & support[v, u] points = xyz[v, u].to(torch.float64) z = torch.where(available, points[..., 2], 0) right_links = available[:, :, :-1] & available[:, :, 1:] & ~self._jump(z[:, :, :-1], z[:, :, 1:]) down_links = available[:, :-1] & available[:, 1:] & ~self._jump(z[:, :-1], z[:, 1:]) right = (right_links*self.bits[:, :-1]).sum((1, 2)) down = (down_links*self.bits[:-1]).sum((1, 2)) reached = torch.full((len(centres),), 1 << 12, dtype=torch.int64, device=self.device) # A simple path in a 25-vertex patch has <=24 edges. Fixed iterations # avoid a host .item()/synchronization at every flood-fill iteration. for _ in range(24): reached = reached | ((reached & right) << 1) | ((reached >> 1) & right) | ((reached & down) << 5) | ((reached >> 5) & down) component = (reached[:, None, None] & self.bits) != 0 count = component.sum((1, 2)) idx = (count >= 6).nonzero().flatten() centres, points, component, count = centres[idx], points[idx], component[idx], count[idx] delta = torch.where(component[..., None], points-xyz[centres[:, 0], centres[:, 1]][:, None, None], 0) mean = delta.sum((1, 2))/count[:, None] flat = delta.flatten(1, 2) covariance = flat.transpose(1, 2).bmm(flat)/count[:, None, None]-mean[:, :, None]*mean[:, None, :] values, basis = torch.linalg.eigh(covariance) threshold = torch.maximum(torch.full_like(values[:, 2], 1e-16), values[:, 2]*1e-8) good = (values[:, 1] > threshold) & (values[:, 1]-values[:, 0] > threshold) & torch.isfinite(values).all(1) centres, vectors = centres[good], basis[good, :, 0] vectors = vectors/torch.linalg.vector_norm(vectors, dim=1)[:, None] camera_dot = (vectors*xyz[centres[:, 0], centres[:, 1]]).sum(1) vectors = torch.where((camera_dot > 0)[:, None], -vectors, vectors) normals[centres[:, 0], centres[:, 1]] = vectors.to(torch.float32) valid[centres[:, 0], centres[:, 1]] = True return normals, valid
def _features(self, xyz, valid_depth, mask, support, normals, normal_valid): shape, dev = self.shape, self.device z = torch.where(valid_depth, xyz[..., 2], 0) jump_m = torch.zeros(shape, dtype=torch.float32, device=dev) pair_valid = torch.zeros_like(support); discontinuity = torch.zeros_like(support) mask_boundary = torch.zeros_like(support); validity_boundary = torch.zeros_like(support) variation = torch.zeros_like(jump_m) count = torch.zeros(shape, dtype=torch.uint8, device=dev) safe_normals = torch.nan_to_num(normals) pairs = [((slice(None), slice(None, -1)), (slice(None), slice(1, None))), ((slice(None, -1), slice(None)), (slice(1, None), slice(None)))] for a, b in pairs: both_depth = valid_depth[a] & valid_depth[b] dz = (z[a]-z[b]).abs() jumps = both_depth & self._jump(z[a], z[b]) both_normals = normal_valid[a] & normal_valid[b] n1, n2 = safe_normals[a], safe_normals[b] angle = torch.atan2(torch.linalg.vector_norm(torch.linalg.cross(n1, n2), dim=-1), (n1*n2).sum(-1)) angle = torch.where(both_normals, angle, 0) for p, q in ((a, b), (b, a)): available = support[p] & both_depth pair_valid[p] |= available jump_m[p] = torch.maximum(jump_m[p], torch.where(available, dz, 0)) discontinuity[p] |= support[p] & jumps mask_boundary[p] |= mask[p] & ~mask[q] validity_boundary[p] |= support[p] & ~valid_depth[q] variation[p] = torch.maximum(variation[p], angle) count[p] += both_normals.to(torch.uint8) variation_valid = normal_valid & (count > 0) image_boundary = torch.zeros_like(support) image_boundary[[0, -1], :] = mask[[0, -1], :] image_boundary[:, [0, -1]] = mask[:, [0, -1]] return dict(object_mask=mask, valid_points=support, normals=normals, normal_valid=normal_valid, depth_jump_m=torch.where(pair_valid, jump_m, float('nan')), depth_pair_valid=pair_valid, depth_discontinuity=discontinuity, mask_boundary=mask_boundary, depth_validity_boundary=validity_boundary, image_boundary=image_boundary, normal_variation_rad=torch.where(variation_valid, variation, float('nan')), normal_variation_valid=variation_valid, normal_neighbor_count=count)
@torch.inference_mode() def __call__(self, depth_m, masks): if depth_m.shape != self.shape or depth_m.device != self.device or not depth_m.is_floating_point(): raise ValueError('depth must be floating (H,W) on the configured device') if set(masks)-{PEG, BOX}: raise ValueError('unknown object ID') masks = {i: masks.get(i, torch.zeros(self.shape, dtype=torch.bool, device=self.device)) for i in (PEG, BOX)} if any(m.dtype != torch.bool or m.shape != self.shape or m.device != self.device for m in masks.values()): raise ValueError('masks must be bool (H,W) on the configured device') depth_m=depth_m.contiguous() masks={i:m.contiguous() for i,m in masks.items()} valid_depth = torch.isfinite(depth_m) & (depth_m > 0) z = torch.where(valid_depth, depth_m, 0).to(torch.float64) xyz = torch.stack((self.ux*z/self.fx, self.vy*z/self.fy, z), dim=-1).to(torch.float32) xyz = torch.where(valid_depth[..., None], xyz, float('nan')) overlap = masks[PEG] & masks[BOX] objects = {} for oid, mask in masks.items(): support = mask & valid_depth & ~overlap normals, normal_valid = self._normals(xyz, support) if self.backend=='triton_fused': from visual.runtime.test.pca_triton import fused_features objects[oid]=fused_features(xyz,valid_depth,mask,support,normals,normal_valid,self.parameters) else: objects[oid] = self._features(xyz, valid_depth, mask, support, normals, normal_valid) return dict(xyz=xyz, valid_depth=valid_depth, overlap_mask=overlap, objects=objects)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833"""Task03-E: offline distance-only Priority FPS ablation on saved ep000 Frame 0.
WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_priority_fps_metric_control \ --baseline /tmp/task03e_baseline/baseline.json
No geometry, features, candidates, allocation, GT geometry or normals are regenerated.All four exact baseline gates precede either control. Selection accepts no annotations."""from __future__ import annotations
import argparseimport hashlibimport htmlfrom html.parser import HTMLParserimport jsonimport osfrom pathlib import Pathimport platformimport reimport shutilimport subprocessimport sysfrom types import SimpleNamespace
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport numpy as npfrom scipy.spatial import cKDTree
from utils.experiment_logger import ExperimentLoggerfrom visual.runtime.geometry import OrganizedGeometryfrom visual.runtime.rgbd import PEG, BOX, iter_saved_rgbdfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test.normal_diagnostics import pose_rotation, statsfrom visual.runtime.test.run_priority_fps_trace import fps_seedfrom visual.runtime.test.run_rim_bottleneck import ( require_equal, source_contract, validate_saved_selection, occupancy, write_json,)from visual.runtime.test.run_structural_edges import negative_regionsfrom visual.runtime.test.sampling_evaluation import CoverageMatcher, staged_reference_coverage
REPO = Path(__file__).resolve().parents[3]SOURCE_RUN = '2551448b0fae4c6bbce3caf48774275f'TASK01 = REPO/'visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a'NORMAL = REPO/'visual/results/normal_comparison/4b1c377ae2044344a4f596b249627d89/f0000.npz'EDGES = REPO/'visual/results/structural_edges/b622e76deceb419ab9c5aa80a8f8280c/f0000_pairs.npz'REPORT = REPO/'docs/visual-graph-integration/03e_priority_fps_metric_control.md'STEM = 'priority_fps_metric_control'METHODS = {'S2': 'fd2', 'S3': 'pca5'}OBJECTS = {'peg': PEG, 'box': BOX}BUDGET = {'peg': 129, 'box': 127}EXPECTED = {('S2', 'peg'): (870, 213708), ('S3', 'peg'): (703, 214225), ('S2', 'box'): (297, 101598), ('S3', 'box'): (599, 96553)}LAMBDAS = (1., .25, 0.)TEST_MODULES = ['visual.runtime.test.'+n for n in ( 'test_priority_fps_metric_control', 'test_sampling', 'test_sampling_geometry', 'test_sampling_evaluation', 'test_priority_fps_trace', 'test_priority_fps_seed_control')]
def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def hashes(paths): return {str(p.relative_to(REPO)): sha(p) for p in sorted(set(map(Path, paths)))}
def array_sha(a): a = np.asarray(a) return hashlib.sha256(str(a.dtype).encode()+str(a.shape).encode()+a.tobytes()).hexdigest()
def verify_preserved(baseline): require_equal(hashes([REPO/p for p in baseline['hashes']]), baseline['hashes'], 'protected original files') return dict(status='PASS', protected_file_count=len(baseline['hashes']), all_sha256_unchanged=True)
def metric_coordinates(points, weight): if weight not in LAMBDAS: raise ValueError('only lambda 1/.25/0 is authorized') metric = np.array(points, dtype=np.float64, copy=True) if metric.ndim != 2 or metric.shape[1] != 3 or not np.isfinite(metric).all(): raise ValueError('finite [N,3] coordinates required') metric[:, 2] *= np.sqrt(weight) return metric
def select(case, weight): """Only candidate/support geometry, fixed initial/quota and metric enter FPS.""" flat, xyz = case['candidate_flat'], case['candidate_xyz'] support, support_xyz = case['support_flat'], case['support_xyz'] first = int(case['first']) local = np.flatnonzero(flat == first) if len(local) != 1 or not np.all(flat[:-1] < flat[1:]) or not np.all(support[:-1] < support[1:]): raise ValueError('invalid initial or source order') p_rows = fps_indices(metric_coordinates(xyz, weight), 32, seed=case['seed'], initial=local) p = flat[p_rows] rows = np.searchsorted(support, p) np.testing.assert_array_equal(support[rows], p) np.testing.assert_array_equal(support_xyz[rows], xyz[p_rows]) f_rows = fps_indices(support_xyz, case['budget'], seed=case['seed'], initial=rows) f = support[f_rows] require_equal(len(p), 32, 'priority budget') require_equal(len(f), case['budget'], 'final budget') require_equal(len(np.unique(f)), len(f), 'unique source rows') np.testing.assert_array_equal(f[:32], p) return dict(P=p.copy(), S=f[32:].copy(), F=f.copy(), priority_local=p_rows, final_support_rows=f_rows, xyz=support_xyz[f_rows].copy())
def selection_input(case): return {k: case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz','first','seed','budget')}
def execute_controls(cases, gate): """Fail closed even when called independently of the runner.""" if set(gate) != set(cases) or not all(v.get('status') == 'PASS' for v in gate.values()): raise ValueError('all four baseline gates must pass before controls') return {key: {str(w): select(selection_input(c), w) for w in (.25, 0.)} for key, c in cases.items()}
def load_inputs(source): comparison = json.loads((source/'comparison.json').read_text()) config = comparison['config'] require_equal(comparison['run_id'], SOURCE_RUN, 'Task03 run') contracts = source_contract(source, config) task01 = json.loads((TASK01/'geometry.json').read_text()) for key in ('input_sha256', 'masks_sha256', 'camera'): require_equal(task01['config'][key], config[key], 'Task01/03 '+key) for field, digest in (('input', 'input_sha256'), ('masks', 'masks_sha256')): require_equal(sha(config[field]), config[digest], 'original '+field) frame = next(iter_saved_rgbd(config['input'], config['masks'], camera=config['camera'])) with np.load(TASK01/'f0000.npz', allow_pickle=False) as a: require_equal(int(a['source_frame']), 0, 'Task01 frame') require_equal(str(a['camera']), config['camera'], 'camera') for key in ('intrinsic', 'cam2world'): np.testing.assert_array_equal(a[key], getattr(frame, key)) geometry = OrganizedGeometry(a['xyz'], a['valid_depth'], {oid: a[name+'/object_mask'] for name, oid in OBJECTS.items()}, a['overlap_mask']) for name, oid in OBJECTS.items(): np.testing.assert_array_equal(geometry.object_masks[oid], frame.masks[oid]) np.testing.assert_array_equal(a[name+'/valid_points'], geometry.observed_mask(oid)) np.testing.assert_array_equal(a['valid_depth'], np.isfinite(frame.depth) & (frame.depth > 0)) np.testing.assert_array_equal(geometry.xyz[..., 2][geometry.valid_depth], frame.depth[geometry.valid_depth]) np.testing.assert_array_equal(geometry.overlap_mask, frame.masks[PEG] & frame.masks[BOX]) samples = np.load(source/'f0000_samples.npz', allow_pickle=False) metrics = json.loads((source/'f0000_metrics.json').read_text()) edges = np.load(EDGES, allow_pickle=False) normal = np.load(NORMAL, allow_pickle=False) np.testing.assert_array_equal(edges['depth_m'], frame.depth) np.testing.assert_array_equal(normal['depth_m'], frame.depth) for archive in (edges, normal): np.testing.assert_array_equal(archive['intrinsic'], frame.intrinsic) require_equal(int(archive['source_frame']), 0, 'evaluation frame') cases = {} for method, estimator in METHODS.items(): key = method+'_n256_r0.25_t20_s0' require_equal(config['conditions'][key], dict(method=method, num_points=256, structural_ratio=.25, orientation_threshold_deg=20, seed=0), 'condition') validate_saved_selection(samples, key, frame, geometry) for name, oid in OBJECTS.items(): candidate = samples[f'evidence/{estimator}/{oid}/20/orientation_flat'].copy() count, first = EXPECTED[method, name] require_equal(len(candidate), count, method+'/'+name+' candidates') if candidate.dtype.kind not in 'iu' or not np.all(candidate[:-1] < candidate[1:]): raise ValueError('candidate source order invalid') support = np.flatnonzero(geometry.observed_mask(oid)) if not np.isin(candidate, support).all(): raise ValueError('candidate outside original support') choose = samples[key+'/object_id'] == oid saved_flat = samples[key+'/flat_index'][choose] p = samples[key+'/priority_selected'][choose] np.testing.assert_array_equal(p, np.arange(BUDGET[name]) < 32) require_equal(int(saved_flat[0]), first, 'stored first point') # The fixed initial also agrees with the original RNG stream, without a new selection. require_equal(int(candidate[np.random.default_rng(fps_seed(0, oid)).integers(len(candidate))]), first, 'original seeded initial') saved_counts = metrics[key]['objects'][name]['counts'] for field, value in dict(observed=len(support), budget=BUDGET[name], priority=32, orientation_priority=32, depth_priority=0, surface_fps=BUDGET[name]-32, selected=BUDGET[name], candidates=count).items(): require_equal(saved_counts[field], value, 'stored allocation '+field) feature_names = sorted(k.split('/metadata/')[1] for k in samples.files if k.startswith(key+'/metadata/')) require_equal(len(feature_names), 23, 'saved feature fields') features = {n: samples[key+'/metadata/'+n][choose].copy() for n in feature_names} for flag in ('orientation_candidate', 'structural_candidate'): np.testing.assert_array_equal(features[flag], np.isin(saved_flat, candidate)) if features['depth_only_candidate'][p].any() or not (features['valid_points'].all() and features['object_mask'].all()): raise ValueError('stored feature support/role mismatch') cases[method+'/'+name] = dict(method=method, name=name, oid=oid, candidate_flat=candidate, candidate_xyz=geometry.xyz.reshape(-1, 3)[candidate].copy(), support_flat=support, support_xyz=geometry.xyz.reshape(-1, 3)[support].copy(), first=first, seed=fps_seed(0, oid), budget=BUDGET[name], saved_flat=saved_flat.copy(), saved_xyz=samples[key+'/points'][choose].copy(), saved_features=features, stored_metrics=metrics[key]['objects'][name], candidate_sha256=array_sha(candidate), support_sha256=array_sha(support), support_xyz_sha256=array_sha(geometry.xyz.reshape(-1,3)[support])) return frame, geometry, samples, edges, normal, cases, config, contracts
def evaluation_inputs(frame, geometry, samples, edges, normal): """Saved annotations only, after geometry-only baseline replay.""" contexts = {} for name, oid in OBJECTS.items(): ref = tuple(samples[f'evaluation/{name}/reference_{s}'] for s in ('uv', 'xyz')) label = 'seam' if name == 'peg' else 'rim' for suffix, value in zip(('uv', 'xyz'), ref): np.testing.assert_array_equal(value, edges[f'evaluation/{name}/{label}_{suffix}']) matcher = CoverageMatcher(geometry, oid, ref) observable = matcher.adjacencies['2px_3mm'].getnnz(axis=0) > 0 require_equal((len(ref[0]), int(observable.sum())), (464, 462) if name == 'peg' else (103,103), 'GT/observed references') region = {k.split('/')[-1]: edges[k] for k in edges.files if k.startswith('evaluation/'+name+'/') and edges[k].shape == frame.depth.shape} other = (tuple(edges[f'evaluation/{name}/seam_{s}'] for s in ('uv', 'xyz'))) all_ref = tuple(np.concatenate([ref[i], other[i]]) for i in (0,1)) negatives = negative_regions(region, {}, all_ref, frame.depth.shape) if name == 'peg': # Verify saved seam is exactly the reference pixel set using existing raster helper. np.testing.assert_array_equal(np.column_stack(np.nonzero(normal['evaluation/peg/seam_endpoints']))[:, ::-1], ref[0]) contexts[name] = dict(matcher=matcher, reference=ref, observable=observable, negatives=negatives) return contexts
def baseline_gate(cases, contexts, replays): """All four lambda=1 selections and stored Frame0 metrics must be exact.""" gate, selections = {}, {} for key, case in cases.items(): chosen = replays[key] np.testing.assert_array_equal(chosen['P'], case['saved_flat'][:32], err_msg=key+' Priority order') np.testing.assert_array_equal(chosen['F'], case['saved_flat'], err_msg=key+' Final order') np.testing.assert_array_equal(chosen['xyz'], case['saved_xyz'], err_msg=key+' XYZ') context = contexts[case['name']] score, _ = context['matcher'].score(chosen['F']) require_equal(score, case['stored_metrics']['structural'], key+' all saved structural metrics') nearest = cKDTree(chosen['xyz']).query(case['support_xyz'])[0]*1000 require_equal(stats(nearest), case['stored_metrics']['surface']['all']['distance_mm'], key+' saved Surface distances') nodes = dict(X=case['support_flat'], C=case['candidate_flat'], P=chosen['P'], S=chosen['S'], F=chosen['F']) occ = occupancy(SimpleNamespace(depth=contexts['depth']), nodes, context['negatives']) for roi, counts in case['stored_metrics']['negative'].items(): for stage, saved in (('X','observed'), ('P','priority'), ('F','selected')): require_equal(occ['negative_roi'][roi][stage]['count'], counts[saved], key+' stored ROI '+roi) gate[key] = dict(status='PASS', priority_order_exact=True, final_order_xyz_exact=True, full_frame0_structural_metrics_exact=True, surface_metrics_exact=True, negative_roi_exact=True, candidate_order_source_support_exact=True, first=case['first'], priority_count=32, budget=case['budget'], candidate_sha256=case['candidate_sha256'], support_sha256=case['support_sha256'], support_xyz_sha256=case['support_xyz_sha256']) selections[key] = {'1.0': chosen} return gate, selections
def peg_labels(face, visible, seam, ref_uv): """Existing four-neighbour visible face transitions; ambiguous endpoints stay explicit.""" pairs_by_pixel = {} for dv, du in ((1,0),(0,1)): h, w = face.shape a = (slice(0,h-dv), slice(0,w-du)); b = (slice(dv,h), slice(du,w)) hit = visible[a] & visible[b] & (face[a] != face[b]) for v, u in zip(*np.nonzero(hit)): pair = tuple(sorted((int(face[v,u]), int(face[v+dv,u+du])))) for pixel in ((v,u),(v+dv,u+du)): pairs_by_pixel.setdefault(pixel, set()).add(pair) rebuilt = np.zeros_like(seam) for v,u in pairs_by_pixel: rebuilt[v,u] = True np.testing.assert_array_equal(rebuilt, seam) labels, memberships = [], [] for u, v in np.asarray(ref_uv, int): pairs = sorted(pairs_by_pixel.get((v,u), set())) memberships.append(['face_%s_%s'%p for p in pairs]) labels.append('face_%s_%s'%pairs[0] if len(pairs) == 1 else 'ambiguous') return np.asarray(labels), memberships
def rim_labels(ref_xyz, cam2world, box_pose, hole_pose, radius): """Invert the existing rim_reference transform to identify its four lines.
No samples/GT coordinates are created. 1e-8m is roundoff validation of line identity only; joint matching remains the unchanged 2px AND 3mm matcher. """ rot = pose_rotation(box_pose) centre = ((hole_pose[:3]-box_pose[:3]) @ rot)[1:] world_to_cv = np.linalg.inv(cam2world) world = (ref_xyz-world_to_cv[:3,3]) @ np.linalg.inv(world_to_cv[:3,:3].T) local = (world-box_pose[:3]) @ np.linalg.inv(rot.T) labels = np.full(len(local), 'ambiguous', dtype='<U32') specs = {} hits = [] for axis, other, c, oc in ((1,2,centre[0],centre[1]), (2,1,centre[1],centre[0])): for sign in (-1,1): label = f'rim_axis{axis}_{sign:+d}' hit = np.abs(local[:,axis]-(c+sign*radius)) <= 1e-8 hit &= np.abs(local[:,other]-oc) <= radius+1e-8 hits.append(hit) specs[label] = dict(axis=other, fixed_axis=axis, sign=sign, unit='metres', order_verified=True, domain='visible saved reference span only', local=local[:,other]) matrix = np.column_stack(hits) for i, label in enumerate(specs): labels[matrix[:,i] & (matrix.sum(axis=1) == 1)] = label # Physical corner references can belong to two lines and are kept ambiguous. return labels, specs, dict(rot=rot, box_pose=box_pose, world_to_cv=world_to_cv)
def segment_spacing(t_reference, covered, t_nodes, *, order_verified): """Measured line projections and missing-reference runs, never array-order arcs.""" if not order_verified or len(t_reference) < 2: return dict(status='N/A', reason='physical single-line order unverified or fewer than two references') order = np.argsort(t_reference, kind='stable') t = np.asarray(t_reference)[order]; hit = np.asarray(covered)[order] # Retain actual node projections; do not substitute covered reference centres. nodes = np.sort(np.asarray(t_nodes)) lo, hi = float(t[0]), float(t[-1]) within = nodes[(nodes >= lo) & (nodes <= hi)] gaps = np.diff(within)*1000 missing = np.flatnonzero(~hit) runs = np.split(missing, np.flatnonzero(np.diff(missing)>1)+1) if len(missing) else [] missing_runs = [dict(start_m=float(t[r[0]]), end_m=float(t[r[-1]]), reference_count=len(r), span_mm=float((t[r[-1]]-t[r[0]])*1000)) for r in runs] return dict(status='verified line', reference_span_mm=(hi-lo)*1000, selected_node_projection_m=nodes.tolist(), selected_nodes_within_reference_span=len(within), actual_inter_node_gap_mm=gaps.tolist(), gap_stats_mm=stats(gaps), start_tail_to_first_node_mm=float((within[0]-lo)*1000) if len(within) else None, end_tail_from_last_node_mm=float((hi-within[-1])*1000) if len(within) else None, missing_reference_runs=missing_runs, missing_reference_run_total_span_mm=sum(r['span_mm'] for r in missing_runs), continuous_unpreserved_length_mm=None, length_caveat='Missing spans join consecutive uncovered saved references only; singleton span=0. ' 'No continuous coverage/visibility interpolation. Tails/gaps use actual node projections.')
def feature_rows(case, flat): """Only the exact baseline condition's saved feature rows are available.
Compact available-only arrays avoid placeholders masquerading as features. """ lookup = {int(f): i for i,f in enumerate(case['saved_flat'])} positions = np.array([i for i,f in enumerate(flat) if int(f) in lookup], dtype=np.int64) source_rows = np.array([lookup[int(flat[i])] for i in positions], dtype=np.int64) features = {name: value[source_rows].copy() for name,value in case['saved_features'].items()} available = np.isin(np.arange(len(flat)), positions) for name, value in features.items(): np.testing.assert_array_equal(value, case['saved_features'][name][source_rows]) return available, positions, features
def score_case(case, chosen, context, frame, labels, specs, transform): matcher = context['matcher']; ref_uv, ref_xyz = context['reference'] stages = dict(C=case['candidate_flat'], P=chosen['P'], S=chosen['S'], F=chosen['F']) coverage = staged_reference_coverage(matcher, stages['C'], stages['P'], stages['S'], stages['F']) arrays, details = {}, {} obs = context['observable'] for stage, flat in stages.items(): rows = np.searchsorted(matcher.flat, flat) adj = matcher.adjacencies['2px_3mm'][rows] covered = adj.getnnz(axis=0)>0 hit_count = adj.getnnz(axis=1) matched = hit_count > 0 uv, xyz = matcher.uv[rows], matcher.xyz[rows] arrays.update({f'{stage}/flat_index': flat, f'{stage}/xyz': xyz, f'{stage}/pixels_vu': uv[:, ::-1], f'{stage}/object_id': np.full(len(flat),case['oid'],np.int64), f'{stage}/covered': covered, f'{stage}/matched_node': matched, f'{stage}/reference_count_per_node': hit_count}) near_stats = {} for group, use in (('all', np.ones(len(flat), bool)), ('structural', matched)): for unit, points, refs, scale in (('px',uv,ref_uv,1),('mm',xyz,ref_xyz,1000)): distance, nearest = cKDTree(points[use]).query(refs) if use.any() else (np.full(len(refs),np.nan),np.full(len(refs),-1,int)) distance = distance*scale source = flat[use][nearest] if use.any() else np.full(len(refs),-1,np.int64) arrays[f'{stage}/nearest_{group}_{unit}'] = distance arrays[f'{stage}/nearest_{group}_{unit}_source'] = source near_stats[f'{group}_{unit}'] = stats(distance[obs]) if use.any() else dict(status='N/A',count=0) node_labels = [] for i in range(len(flat)): lab = set(labels[adj[i].indices]) node_labels.append(next(iter(lab)) if len(lab)==1 and 'ambiguous' not in lab else 'ambiguous' if lab else 'unmatched') node_labels = np.asarray(node_labels) arrays[f'{stage}/node_segment'] = node_labels segs = {} for label in sorted(set(labels)): mask = labels == label tnodes = [] if label in specs and transform is not None: wt = transform['world_to_cv']; rot = transform['rot'] world = (xyz[node_labels == label]-wt[:3,3]) @ np.linalg.inv(wt[:3,:3].T) local = (world-transform['box_pose'][:3]) @ np.linalg.inv(rot.T) tnodes = local[:,specs[label]['axis']] segs[label] = dict(gt_references=int(mask.sum()), observed_references=int((mask&obs).sum()), covered_reference_ids=np.flatnonzero(mask&covered).tolist(), missing_observed_reference_ids=np.flatnonzero(mask&obs&~covered).tolist(), coverage_count=int((mask&covered).sum()), matching_node_count=int((node_labels == label).sum()), node_flat_indices=flat[node_labels == label].tolist(), nearest_structural_px=stats(arrays[f'{stage}/nearest_structural_px'][mask&obs]) if matched.any() else None, nearest_structural_mm=stats(arrays[f'{stage}/nearest_structural_mm'][mask&obs]) if matched.any() else None, spacing=segment_spacing(specs[label]['local'][mask] if label in specs else [], covered[mask], tnodes, order_verified=label in specs and label != 'ambiguous')) coo = adj.tocoo() arrays[f'{stage}/joint_node_row'] = coo.row arrays[f'{stage}/joint_reference_id'] = coo.col nearest_node_dist = {} for unit, points, scale in (('px',uv,1), ('mm',xyz,1000)): d = cKDTree(points[matched]).query(points[matched],k=2)[0][:,1]*scale if matched.sum()>1 else np.empty(0) nearest_node_dist[unit] = stats(d) details[stage] = dict(selected_flat_indices=flat.tolist(), selected_xyz_m=xyz.tolist(), selected_pixels_vu=uv[:,::-1].tolist(), node_count=len(flat), structural_matching_nodes=int(matched.sum()), matching_flat_indices=flat[matched].tolist(), unique_reference_count=int(covered.sum()), nodes_covering_multiple_references=int((hit_count>1).sum()), references_covered_by_multiple_nodes=int((adj.getnnz(axis=0)>1).sum()), reference_count_per_matching_node=hit_count[matched].tolist(), covered_reference_ids=np.flatnonzero(covered).tolist(), missing_observed_reference_ids=np.flatnonzero(obs&~covered).tolist(), nearest_observed_reference_distance=near_stats, matched_node_nearest_euclidean_distance=nearest_node_dist, segments=segs, quadrant_origin='existing matcher median UV halves', reference_quadrants=matcher.score(flat)[0]['tolerance']['2px_3mm']['reference_quadrants']) surface_distance = cKDTree(chosen['xyz']).query(case['support_xyz'])[0]*1000 arrays['surface_support_to_final_mm'] = surface_distance nodes = dict(X=case['support_flat'], **stages) occ = occupancy(frame, nodes, context['negatives']) # Selection-rate denominator is the same candidate depth band, not all candidates. zc = frame.depth.ravel()[stages['C']]; zp = frame.depth.ravel()[stages['P']] med, p95 = (occ['depth_band_bounds_m'][k] for k in ('median','p95')) def bands(z): return (z<=med, (z>med)&(z<=p95), z>p95) occ['candidate_band_priority_selection_rates'] = [dict(candidate_nodes=int(c.sum()),priority_nodes=int(p.sum()), rate=float(p.sum()/c.sum()) if c.any() else None) for c,p in zip(bands(zc),bands(zp))] available, positions, features = feature_rows(case, chosen['F']) arrays.update({'F/feature_available':available, 'F/feature_available_positions':positions, 'F/selection_role':np.where(np.arange(len(chosen['F']))<32,'Priority','Surface')}) for name,value in features.items(): arrays['F/available_features/'+name] = value for stage in ('P','S'): sl = slice(0,32) if stage == 'P' else slice(32,None) arrays[stage+'/feature_available'] = available[sl] arrays[stage+'/selection_role'] = np.full(len(chosen[stage]), 'Priority' if stage == 'P' else 'Surface') return dict(coverage=coverage, stages=details, surface_distance_mm=stats(surface_distance), occupancy=occ, feature_availability=dict(fields=23, exact_available_rows=int(available.sum()), unavailable_rows=int((~available).sum()), source='same-estimator Task03 n256/r.25/t20/seed0 stored rows only', storage='F/available_features uses F/feature_available_positions; unavailable rows have no feature values', baseline_feature_alignment_exact=True, dense_pca_cache_used=False)), arrays
def create_plots(output, frame, cases, selections, result, arrays, contexts): plt.rcParams.update({'font.size':9}) for object_name in ('peg','box'): refs = contexts[object_name]['reference'][0] fig, axes = plt.subplots(4,3,figsize=(15,16), constrained_layout=True) for mi, method in enumerate(METHODS): key = method+'/'+object_name for si, stage in enumerate(('P','F')): for wi, w in enumerate(LAMBDAS): prefix = key+'/'+str(w)+'/'+stage ax = axes[mi*2+si,wi] ax.imshow(frame.rgb) flat = selections[key][str(w)][stage] uv = np.column_stack(np.unravel_index(flat,frame.depth.shape))[:,::-1] hit = arrays[prefix+'/matched_node'] covered = arrays[prefix+'/covered'] # Hollow nodes stay visible when one node covers many reference markers. ax.scatter(*refs[~covered].T,s=15,c='#e42b67',marker='x',label='missing GT reference',zorder=3) ax.scatter(*refs[covered].T,s=12,c='#2be4bb',marker='.',label='covered GT reference',zorder=3) ax.scatter(*uv[~hit].T,s=35,facecolors='none',edgecolors='#edb53f',label='other selected node',zorder=4) ax.scatter(*uv[hit].T,s=85,facecolors='none',edgecolors='#4b8aff',linewidths=1.8,label='joint matching node',zorder=5) margin = 12 if object_name == 'box' else 10 ax.set(xlim=(refs[:,0].min()-margin,refs[:,0].max()+margin), ylim=(refs[:,1].max()+margin,refs[:,1].min()-margin), title=f'{method} {stage}, lambda={w:g}: {hit.sum()} nodes / {covered.sum()} refs',xlabel='u (px)',ylabel='v (px)') if mi==0 and si==0 and wi==0: ax.legend(fontsize=7,loc='upper left') fig.suptitle(f'{object_name.title()} structural closeup: actual nodes and unique references (P=Priority, F=Final)') fig.savefig(output/f'{object_name}_structural_zoom.png',dpi=140); plt.close(fig) fig, axes = plt.subplots(4,3,figsize=(15,16),constrained_layout=True) fig3, axes3 = plt.subplots(4,3,figsize=(15,14),constrained_layout=True) for row,(key,case) in enumerate(cases.items()): for col,w in enumerate(LAMBDAS): chosen = selections[key][str(w)]; ax=axes[row,col]; ax3=axes3[row,col] ax.imshow(frame.rgb) for stage,color in (('S','#36cccd'),('P','#ff9b24')): f=chosen[stage]; uv=np.column_stack(np.unravel_index(f,frame.depth.shape))[:,::-1] ax.scatter(*uv.T,s=14,c=color,label=stage,alpha=.9) xyz=case['support_xyz'][np.searchsorted(case['support_flat'],f)] ax3.scatter(xyz[:,0]*1000,xyz[:,2]*1000,s=12,c=color,label=stage) ax.set(title=f'{key}, lambda={w:g}',xlabel='u (px)',ylabel='v (px)') support=case['support_xyz'] ax3.scatter(support[:,0]*1000,support[:,2]*1000,s=.5,c='#69788d',alpha=.13,zorder=0) ax3.set(title=f'{key}, lambda={w:g}',xlabel='camera X (mm)',ylabel='camera Z (mm)') ax3.set_xlim(support[:,0].min()*1000-5,support[:,0].max()*1000+5) ax3.set_ylim(support[:,2].max()*1000+5,support[:,2].min()*1000-5) ax.legend(); ax3.legend() fig.suptitle('All selected pixels: Priority orange, Surface cyan; all 256 points per estimator/lambda') fig.savefig(output/'selection_overview.png',dpi=120); plt.close(fig) fig3.suptitle('Actual Camera X/Z distribution; depth is never scaled in output geometry') fig3.savefig(output/'spatial_xz.png',dpi=130); plt.close(fig3) fig, axes=plt.subplots(2,2,figsize=(14,10),constrained_layout=True) for i,(key,case) in enumerate(cases.items()): ax=axes.ravel()[i]; values=result['cases'][key]['conditions']; x=np.arange(3) for stage,offset,color in (('P',-.15,'#ef9834'),('F',.15,'#147da4')): ax.bar(x+offset,[values[str(w)]['stages'][stage]['unique_reference_count'] for w in LAMBDAS],.28,label=stage+' unique refs',color=color) second=ax.twinx() second.plot(x,[values[str(w)]['surface_distance_mm']['mean'] for w in LAMBDAS],'-o',c='#9b238e',label='Surface mean mm') second.plot(x,[values[str(w)]['surface_distance_mm']['p95'] for w in LAMBDAS],'--o',c='#9b238e',label='Surface p95 mm') ax.set(title=key,xticks=x,xticklabels=['1','.25','0'],xlabel='lambda',ylabel='unique references',ylim=(0,464 if case['name']=='peg' else 103)) second.set_ylabel('support to Final distance (mm)'); ax.legend(loc='upper left'); second.legend(loc='upper right') fig.savefig(output/'coverage_surface_tradeoff.png',dpi=150); plt.close(fig) # Per-reference UV positions above avoid implying reference-ID order is physical. # Here the explicit sort is image u then v and is labelled as such, not arc length. fig, axes=plt.subplots(4,2,figsize=(17,13),constrained_layout=True) for i,(key,case) in enumerate(cases.items()): refs=contexts[case['name']]['reference'][0]; order=np.lexsort((refs[:,1],refs[:,0])) matrix=np.array([arrays[key+'/'+str(w)+'/'+s+'/covered'][order] for w in LAMBDAS for s in ('P','F')]) axes[i,0].imshow(matrix,aspect='auto',interpolation='nearest',cmap='RdYlGn',vmin=0,vmax=1) axes[i,0].set(title=key+' joint reference coverage',xlabel='reference sorted by image u, then v (NOT physical order)', yticks=range(6),yticklabels=[f'{w:g} {s}' for w in LAMBDAS for s in ('P','F')]) for w in LAMBDAS: d=arrays[key+'/'+str(w)+'/F/nearest_structural_mm'][order] axes[i,1].plot(np.arange(len(d)),d,label=f'{w:g}',alpha=.8) axes[i,1].set(title=key+' Final: nearest actual structural node',xlabel='same image-coordinate sort',ylabel='3D distance (mm)') axes[i,1].legend(title='lambda') fig.savefig(output/'local_reference_distances.png',dpi=140); plt.close(fig) # Actual selected projections, not the centres of references covered by a node. fig, axes=plt.subplots(4,1,figsize=(15,12),constrained_layout=True) for i,(method,stage) in enumerate((('S2','P'),('S2','F'),('S3','P'),('S3','F'))): ax=axes[i]; lines=sorted(result['segment_definitions']['box']['labels']) for j,label in enumerate(lines): if label=='ambiguous': continue for wi,w in enumerate(LAMBDAS): spacing=result['cases'][method+'/box']['conditions'][str(w)]['stages'][stage]['segments'][label]['spacing'] if spacing['status']=='N/A': continue ax.scatter(np.asarray(spacing['selected_node_projection_m'])*1000, np.full(len(spacing['selected_node_projection_m']),j+wi*.22),marker='|',s=180,label=f'{w:g}' if j==0 else None) ax.set(title=f'{method} Box {stage}: actual node projections by verified rim line', yticks=np.arange(len(lines))+.22,yticklabels=lines,xlabel='box-local coordinate along each line (mm); each row is independent') ax.legend(title='lambda') fig.savefig(output/'box_line_node_spacing.png',dpi=140); plt.close(fig)
def summary_table(result): lines=['| 조건 | λ | P nodes / refs | F nodes / refs | Surface 추가 / overlap refs | Surface mean / p95 mm | P depth median / p95 m | Negative union P |', '| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |'] for key,row in result['cases'].items(): for w in LAMBDAS: r=row['conditions'][str(w)]; p=r['stages']['P']; f=r['stages']['F']; d=r['surface_distance_mm'] diff=r['coverage']['differences']; z=r['occupancy']['depth_m']['P'] neg=r['occupancy']['negative_roi']['known_negative_union']['P']['count'] lines.append(f"| {key} | {w:g} | {p['structural_matching_nodes']} / {p['unique_reference_count']} | " f"{f['structural_matching_nodes']} / {f['unique_reference_count']} | {diff['S_minus_P']['count']} / {diff['P_intersect_S']['count']} | " f"{d['mean']:.3f} / {d['p95']:.3f} | {z['median']:.4f} / {z['p95']:.4f} | {neg}/32 |") return lines
def create_report(output, result, test_summary): rel=lambda p: os.path.relpath(p, REPORT.parent) lines=['# Task03-E — Depth-Weighted Structural FPS & Local Geometry Preservation','', f"실행 UUID: `{result['run_id']}`. ep000 Frame 0의 geometry-level offline ablation을 완료했다. 네 조합의 λ=1 exact reproduction 관문은 모두 PASS다.", '', '## 고정 조건과 baseline 관문','', '- S2(FD2), S3(PCA5), Peg/Box, num_points=256, structural_ratio=.25, threshold=20°, seed=0. λ는 1/.25/0만 실행했다.', '- 기존 `fps_indices()`에 `[x,y,sqrt(λ)z]`를 Priority 거리 계산용으로만 전달했다. Camera XY-only는 normalized image UV FPS와 다르다.', '- 후보 source index·raster 순서·support·첫 점·quota를 유지했다. Peg 32+97=129, Box 32+95=127, estimator/λ마다 256점이다.', '- Task01/03 episode·mask hash, camera/intrinsic/cam2world, dense Z와 원본 depth, validity·mask·overlap 및 선택 XYZ/pixel/object가 exact 일치한다. Backprojection·normal·candidate·allocation은 재계산하지 않았다.', '- 네 λ=1 Priority 32점 및 기존 Priority 초기 집합을 포함한 3D Surface/Final 순서·XYZ가 exact 일치한다. Frame0의 모든 저장 structural tolerance/거리/quadrant 지표, 전체 Surface 거리 통계, negative ROI 수치도 exact 재현했다. 기준 tolerance 변경은 없다.', '- 원본 orientation 배열은 저장 후보를 그대로 복사하며 count/order hash와 저장 metadata의 candidate membership을 검증했다. 독립적인 normal 재계산에 의한 후보 재검출은 수행하지 않았다.', '', '| 조건 | 후보 | 첫 flat index | Final budget |', '| --- | ---: | ---: | ---: |'] for key,row in result['cases'].items(): g=result['baseline_gate'][key]; lines.append(f"| {key} | {row['candidate_count']} | {g['first']} | {g['budget']} |") lines += ['', '## Structural retention과 Surface trade-off','', '아래 nodes는 실제 joint-matching 선택 node 수이며 refs는 unique reference 수다. P 실제 선택 수는 32, F는 Peg 129/Box 127이다. 분모는 Peg observed 462(GT 464), Box observed/GT 103이다. Candidate와 Surface의 전체 수·matching node·reference ID 및 P/S 교집합은 JSON/NPZ에 별도 보존했다.', '', *summary_table(result),'', '## 질문별 판단',''] for i,answer in enumerate(result['answers_ko'],1): lines += [f'{i}. {answer}', ''] lines += ['## 국소 분포와 물리적 간격','', 'GT와 구간 label은 sampler의 입력이 아니다. Reference 배열 순서는 물리적 순서로 쓰지 않았다. 아래 coverage는 관측 reference 분모이며 corner의 복수 귀속은 ambiguous로 보존한다. Segment node 수는 해당 node가 매칭한 모든 reference가 하나의 label에 속할 때만 집계한다. 여러 label에 걸친 node는 ambiguous로 기록하므로 구간별 node 수를 전체 matching node 수로 단순 합산하지 않는다.', '', '| 조건 | 구간 | observed | P covered λ=1/.25/0 | F covered λ=1/.25/0 | F actual nodes λ=1/.25/0 |', '| --- | --- | ---: | --- | --- | --- |'] for key,case in result['cases'].items(): conditions=case['conditions']; labels=conditions['1.0']['stages']['F']['segments'] for label,seg in labels.items(): def values(stage,field): return ' / '.join(str(conditions[str(w)]['stages'][stage]['segments'][label][field]) for w in LAMBDAS) lines.append(f"| {key} | {label} | {seg['observed_references']} | {values('P','coverage_count')} | {values('F','coverage_count')} | {values('F','matching_node_count')} |") lines += ['', '- Peg: 기존 visible face map의 4-neighbour face transition과 seam_endpoints가 exact 일치한다. 각 reference의 face-pair membership과 모서리 복수 귀속을 저장했다. Raster seam의 두께·접점을 물리적 선분의 중심선으로 바꾸지 않았으므로 face-pair의 물리적 순서·간격·미보존 길이는 **N/A**다. 새 GT geometry나 큰 helper 구현은 범위에서 제외했다.', '- Box: 기존 `rim_reference`가 사용한 pose/centre/radius와 transform을 역변환해 확인 가능한 네 선분 label을 붙였다. 새 reference를 생성하지 않았다. 1e-8m line identity 검사는 부동소수점 roundoff 확인이며 matching tolerance와 무관하다. 물리적 corner·복수 귀속은 ambiguous이며 spacing은 N/A다.', '- 확인된 Box 선분에서는 실제 matching node XYZ를 해당 축에 투영해 정렬했다. 실제 인접 node 간격·끝부분 node 미배치 span과 연속 missing-reference run의 양 끝 span(mm)을 JSON에 기록했다. 분석 domain은 저장된 visible reference의 min–max span이다. 전체 물리 선분의 occluded 부분 길이는 평가하지 않았다.', '- Missing-reference run span은 연속으로 누락된 저장 reference의 첫/끝 좌표 차이다. 단일 누락 reference의 span은 0이다. 연속적인 구조의 미보존 길이를 보간하지 않았으므로 continuous_unpreserved_length_mm은 null(N/A)이다. 이 값으로 실제 미보존 길이의 부재를 주장하지 않는다.', '- Reference별 nearest pixel/3D 거리·nearest source index는 전체 선택점과 실제 structural matching node 집합을 나누어 P/F 각각 저장했다. 두 독립 최근접점으로 joint match를 합성하지 않는다. observed reference의 mean/median(p50)/p95/max, covered/missing ID, image quadrants도 저장했다. Peg 미관측 2개 ID는 별도 mask로 남겼다.', '- 한 node가 여러 reference를 덮는 joint pair 목록, node별 reference 수, 여러 node에 덮이는 reference 수를 별도 기록했다. 높은 reference coverage를 촘촘한 실제 node 배치로 해석하지 않는다.', '', '## Feature 대응과 제약','', '모든 선택 XYZ/pixel/source index/object ID/역할은 원본 관측과 exact 대응한다. Baseline과 겹치는 저장 행에서 23 metadata field를 source index로 gather하고 정렬을 검증했다. 이 구현은 같은 estimator·동일 baseline condition의 행만 exact available로 간주하는 보수적인 범위다. 다른 저장 condition의 feature를 임의 병합하지 않는다. `F/feature_available_positions`가 compact `F/available_features/*`의 대상 행을 가리키며, unavailable 행에는 feature 값을 만들지 않는다. P/S availability mask도 별도 저장한다. 과거 dense PCA5 feature cache 대체·feature 재추출·optimized PCA·Vision Tensor packaging은 미실행이다.', '', '| 조건 | λ | exact feature rows / Final | unavailable |', '| --- | ---: | ---: | ---: |'] for key,case in result['cases'].items(): for w in LAMBDAS: a=case['conditions'][str(w)]['feature_availability']; lines.append(f"| {key} | {w:g} | {a['exact_available_rows']} / {BUDGET[key.split('/')[1]]} | {a['unavailable_rows']} |") lines += ['', '## 검증·재현과 완료 범위','', f'- 필수 신규/기존 테스트 PASS: `{test_summary}`. [tests.log]({rel(output/"tests.log")}). λ 거리식, λ=0 Z 불변, source/feature alignment, GT·구간 label 독립성, 관문 실패 시 control 차단, budget/중복, same-pair·dedup 및 N/A 계약을 포함한다.', f'- [verification.json]({rel(output/"verification.json")})에 실제 데이터의 네 exact baseline, source/input hash 보존, 모든 λ의 동일 후보·초기점·quota, 원본 XYZ/역할/feature 대응 및 상대 링크·PNG decode 결과를 기록했다.', '- 기존 ExperimentLogger(team=visual, job_type=evaluate)를 WANDB_MODE=disabled로 재사용했다. UUID/project/group 규칙은 바꾸지 않았다. 기존 파일·source·artifact sidecar를 보존하고 새 산출물만 등록했다.', '- CPU NumPy/SciPy offline 평가만 실행했다. Simulator·renderer·CUDA/GPU/backend는 이 작업에서 실행하지 않았다. 독립 episode/frame/seed, 추가 λ, production 정책 채택, 학습·GNN/BC·PCL·GPU 최적화·외부 upload·dependency 설치·commit은 미실행이다.', '- Production sampling/normal/allocation/tracking 및 기존 Phase1–3 구현은 변경하지 않았다. Git 시작 상태가 dirty이므로 commit만으로 재현할 수 없으며 source snapshot·input hashes·implementation diff를 함께 보관한다.', '', '재실행: `WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_priority_fps_metric_control --baseline <새 실행 전 baseline.json>`; 기존 보고서를 덮어쓰지 않는다. 각 실행은 새 UUID를 만든다. 결과 보고 후 다음 알고리즘 변경 없이 중단한다.', '', '## 산출물',''] for name in (STEM+'.html',STEM+'.json',STEM+'.npz','selection_overview.png','box_structural_zoom.png', 'peg_structural_zoom.png','spatial_xz.png','coverage_surface_tradeoff.png','local_reference_distances.png', 'box_line_node_spacing.png','verification.json','source_hashes.json','implementation.patch','git_start.json','git_end.json'): lines.append(f'- [{name}]({rel(output/name)})') lines += ['', '## 기존 근거','', '- [승인 전 계획](03e_priority_fps_metric_control_plan.md)', f'- [Task03 원본 comparison](../../visual/results/sampling/{SOURCE_RUN}/comparison.json), [Frame0 NPZ](../../visual/results/sampling/{SOURCE_RUN}/f0000_samples.npz)', '- [Task01 dense geometry](../../visual/results/runtime_geometry/f9b0da8588734a28996a38f3724da16a/f0000.npz)', '- [Phase1](../../experiments/d3f14ee494894daabb8ba2fab8e1b00c/diagnostic.json), [Phase2](../../experiments/aa5d71078e0841fd886b5026d6030ebc/priority_fps_trace.json), [Phase3](../../experiments/f36f1e9e2bb64866b8d6c792db158635/priority_fps_seed_control.json)', '- [runner](../../visual/runtime/test/run_priority_fps_metric_control.py), [tests](../../visual/runtime/test/test_priority_fps_metric_control.py)', ''] REPORT.write_text('\n'.join(lines),encoding='utf-8') shutil.copyfile(REPORT,output/'report_snapshot.md')
def create_html(output,result): links=[STEM+'.json',STEM+'.npz','verification.json','source_hashes.json','tests.log','implementation.patch', 'report_snapshot.md',os.path.relpath(REPORT,output), os.path.relpath(REPO/'visual/results/sampling'/SOURCE_RUN/'comparison.json',output), os.path.relpath(REPO/'visual/results/sampling'/SOURCE_RUN/'f0000_samples.npz',output)] parts=['<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task03-E metric control</title>', '<style>body{font:16px system-ui;margin:24px auto;max-width:1500px;padding:0 20px;color:#182538}img{width:100%;height:auto}a{color:#075ca8}pre{white-space:pre-wrap}li{margin:.6em 0}</style>', '<h1>Task03-E — Depth-weighted Priority FPS</h1>', f"<p>Run {result['run_id']}; ep000 Frame 0; S2/S3; λ=1/.25/0. All four exact baseline gates PASS. Geometry-level ablation.</p>", '<p>Priority=32/object; Final Peg=129, Box=127. Actual XYZ and 3D Surface metric retained. GT/segment annotations enter evaluation only.</p>', '<nav>'+' | '.join(f'<a href="{html.escape(p)}">{html.escape(Path(p).name)}</a>' for p in links)+'</nav>', '<ol>'+''.join('<li>'+html.escape(a)+'</li>' for a in result['answers_ko'])+'</ol>', '<pre>'+html.escape('\n'.join(summary_table(result)))+'</pre>'] for name,title in [('selection_overview.png','S2/S3 and lambda: all selected positions'), ('box_structural_zoom.png','Box rim: actual nodes vs covered references'), ('peg_structural_zoom.png','Peg seam: actual nodes vs covered references'), ('local_reference_distances.png','Local reference coverage and nearest structural-node distances'), ('box_line_node_spacing.png','Verified Box line projections; Peg physical order/spacing N/A'), ('coverage_surface_tradeoff.png','Structural retention and general Surface trade-off'), ('spatial_xz.png','Actual X/Z distribution')]: parts += [f'<h2>{title}</h2>',f'<a href="{name}"><img src="{name}" alt="{title}"></a>'] parts += ['<p>One node can cover multiple references. Reference-ID or image-u order is not arc length. ' 'Peg physical spacing and continuous unpreserved length: N/A. Box missing-reference run spans are discrete measured spans only. ' 'Unavailable original features are explicit; no dense PCA substitute. No production policy adopted.</p></html>'] (output/(STEM+'.html')).write_text('\n'.join(parts),encoding='utf-8')
def verify_links(output): targets=[] class Links(HTMLParser): def handle_starttag(self,tag,attrs): targets.extend(value for attr,value in attrs if attr in ('href','src') and value) Links().feed((output/(STEM+'.html')).read_text()) for target in targets: if '://' in target or not (output/target).is_file(): raise ValueError('bad HTML local target '+target) md=re.findall(r'\]\(([^)]+)\)',REPORT.read_text()) for target in md: if not (REPORT.parent/target).is_file(): raise ValueError('bad Markdown target '+target) pngs={} for p in output.glob('*.png'): pixels=plt.imread(p) if pixels.ndim!=3 or min(pixels.shape[:2])<400 or float(pixels.std())<.01: raise ValueError('invalid/empty PNG '+str(p)) pngs[p.name]=list(pixels.shape) return dict(html_local_targets=len(targets),markdown_local_targets=len(md),png_decoded=pngs,status='PASS')
def answers(result): def values(key,stage,field): return '/'.join(str(result['cases'][key]['conditions'][str(w)]['stages'][stage][field]) for w in LAMBDAS) change=[] for key,case in result['cases'].items(): change.append(key+' '+ '/'.join(str(case['conditions'][str(w)]['paired_vs_lambda1']['priority_replaced_nodes']) for w in (.25,0.))+'점') return [ 'Z 가중치를 낮추면 실제 Priority 위치가 달라진다. λ=.25/0에서 baseline 대비 교체된 Priority node 수는 '+', '.join(change)+ '이다. 초기점과 후보는 그대로이며 선택 위치와 깊이의 변화는 overlay·XZ 그림 및 source index 순서로 확인할 수 있다.', 'Box rim의 Priority unique reference coverage(λ=1/.25/0)는 S2 '+values('S2/box','P','unique_reference_count')+ ', S3 '+values('S3/box','P','unique_reference_count')+'/103이다. Final은 S2 '+values('S2/box','F','unique_reference_count')+ ', S3 '+values('S3/box','F','unique_reference_count')+'/103이다. 이 수치와 실제 matching node 수를 함께 보며 개선을 모든 estimator에 일반화하지 않는다.', 'Peg seam의 Priority coverage는 S2 '+values('S2/peg','P','unique_reference_count')+', S3 '+values('S3/peg','P','unique_reference_count')+ '/462, Final은 S2 '+values('S2/peg','F','unique_reference_count')+', S3 '+values('S3/peg','F','unique_reference_count')+ '/462다. 개별 face-pair별 증감과 실제 matching node 수가 서로 다르므로 총 coverage만으로 모든 구간이 촘촘해졌다고 판단할 수 없다. 물리적 중심선 간격은 저장 정보로 검증되지 않아 N/A다.', 'Rim/seam과 일반 Surface 사이의 손익은 위 표의 실제 3D support→Final mean/p95를 같은 분모로 비교한다. ' 'Priority가 달라지면 이어지는 3D Surface FPS도 달라지므로 Final 개선을 Priority 수치만으로 설명할 수 없다. ' 'Depth 분위수와 negative ROI union은 설명용이며 filtering이나 일반 평면의 오선택 판정으로 사용하지 않았다.', 'Z 가중치 조정 후에도 모든 조건에서 누락된 관측 reference와 제한된 실제 structural node 배치가 남는다. ' '전역 FPS의 국소 누락이 이 frame에서 해소되었다는 근거는 없다. 한 frame의 최적 λ나 production sampling 정책을 채택하지 않는다.' ]
def diagnose(source, output_root, baseline_path): if os.environ.get('WANDB_MODE')!='disabled': raise ValueError('WANDB_MODE=disabled required') if REPORT.exists(): raise FileExistsError('refuse to overwrite Task03-E report') baseline=json.loads(Path(baseline_path).read_text()); verify_preserved(baseline) inputs=[source/'comparison.json',source/'f0000_samples.npz',source/'f0000_metrics.json', TASK01/'geometry.json',TASK01/'f0000.npz',NORMAL,EDGES, REPO/'experiments/d3f14ee494894daabb8ba2fab8e1b00c/diagnostic.json', REPO/'experiments/aa5d71078e0841fd886b5026d6030ebc/priority_fps_trace.json', REPO/'experiments/f36f1e9e2bb64866b8d6c792db158635/priority_fps_seed_control.json'] task03_config=json.loads((source/'comparison.json').read_text())['config'] inputs += [Path(task03_config[k]) for k in ('input','masks')] before=hashes(inputs) sources=list((REPO/'visual/runtime').glob('*.py'))+list((REPO/'visual/runtime/test').glob('*.py'))+[ REPO/'utils/experiment_logger.py',REPO/'utils/experiment_artifacts.py'] source_hashes=hashes(sources) config=dict(task='03-E',source_run_id=SOURCE_RUN,episode='ep000',frame=0,methods=METHODS, lambdas=list(LAMBDAS),num_points=256,structural_ratio=.25,threshold_deg=20,seed=0, priority_count=32,budgets=BUDGET,metric='dx^2+dy^2+lambda*dz^2 (Priority only)', surface_metric='original 3D Euclidean',gt_selection_input=False,device='cpu', simulator_executed=False,gpu_executed=False,input_sha256=before,source_sha256=source_hashes, python=platform.python_version(),numpy=np.__version__) with ExperimentLogger(team='visual',config=config,seed=0,model='task03e_priority_fps_metric_control', job_type='evaluate',root=output_root) as logger: output=logger.directory write_json(output/'git_start.json',baseline) shutil.copyfile(Path(baseline_path).with_name('git_start.diff'),output/'git_start.diff') for path in sources: dest=output/'source_snapshot'/path.relative_to(REPO); dest.parent.mkdir(parents=True,exist_ok=True) shutil.copyfile(path,dest) with (output/'tests.log').open('w') as log: test=subprocess.run([sys.executable,'-m','unittest',*TEST_MODULES,'-v'],cwd=REPO,stdout=log,stderr=subprocess.STDOUT) if test.returncode: write_json(output/'verification.json',dict(status='FAIL',reason='required tests failed',controls_executed=False)) logger.link_output(output/'verification.json',kind='reports'); logger.link_output(output/'tests.log',kind='reports') raise RuntimeError('required tests failed; no real selections executed: '+str(output)) test_summary=next(s for s in (output/'tests.log').read_text().splitlines() if s.startswith('Ran '))+'; OK' print('Tests PASS. Loading saved inputs for four baseline gates.',flush=True) try: frame,geometry,samples,edges,normal,cases,old_config,contracts=load_inputs(source) replays={key:select(selection_input(case),1.) for key,case in cases.items()} contexts=evaluation_inputs(frame,geometry,samples,edges,normal) contexts['depth']=frame.depth gate,selections=baseline_gate(cases,contexts,replays) except Exception as exc: write_json(output/'verification.json',dict(status='FAIL',reason=str(exc),controls_executed=False, baseline_gate='failed; no tolerance/source/sampler adjustments')) write_json(output/(STEM+'.json'),dict(run_id=logger.run_id,status='baseline failed',reason=str(exc),controls_executed=False)) REPORT.write_text('# Task03-E — Baseline reproduction 실패\n\n'+str(exc)+'\n\nλ=.25/0 control은 실행하지 않았다. 기존 sampler/source/tolerance를 변경하지 않고 중단한다.\n'+ f'\n[verification]({os.path.relpath(output/"verification.json",REPORT.parent)})\n',encoding='utf-8') for p in (output/'verification.json',output/(STEM+'.json')): logger.link_output(p,kind='reports') raise RuntimeError('baseline failed; controls blocked; '+str(output)) from exc write_json(output/'baseline_gate.json',gate) print('All four baseline gates PASS. Executing only lambda=.25/0 controls.',flush=True) controls=execute_controls(cases,gate) for key in cases: selections[key].update(controls[key]) # Only now assign GT face-pair/rim-line labels and evaluate selected controls. peg_lab,peg_members=peg_labels(normal['evaluation/peg/face'],normal['evaluation/peg/gt_visible'], normal['evaluation/peg/seam_endpoints'],contexts['peg']['reference'][0]) with np.load(old_config['input'],allow_pickle=False) as episode: box_lab,box_specs,box_transform=rim_labels(contexts['box']['reference'][1],frame.cam2world, episode['box_pose'][0],episode['box_hole_pose'][0],float(episode['box_hole_radii'])) result=dict(run_id=logger.run_id,source_run_id=SOURCE_RUN,config=config,baseline_gate=gate, source_contract=contracts,cases={},segment_definitions=dict( peg=dict(labels=sorted(set(peg_lab)),membership_by_reference=peg_members, physical_spacing='N/A: raster face transitions have no verified physical centreline order'), box=dict(labels=sorted(set(box_lab)),line_identity_roundoff_m=1e-8, domain='visible saved reference span; corner ambiguity explicit'))) arrays={} for name,context in ((n,contexts[n]) for n in OBJECTS): arrays.update({name+'/reference_uv':context['reference'][0],name+'/reference_xyz':context['reference'][1], name+'/observable':context['observable'],name+'/reference_segment':peg_lab if name=='peg' else box_lab}) for key,case in cases.items(): row=dict(candidate_count=len(case['candidate_flat']),candidate_sha256=case['candidate_sha256'], support_count=len(case['support_flat']),support_sha256=case['support_sha256'],conditions={}) for field in ('candidate_flat','candidate_xyz','support_flat','support_xyz'): arrays[key+'/'+field]=case[field] b=selections[key]['1.0'] for w in LAMBDAS: chosen=selections[key][str(w)]; name=case['name'] scored,data=score_case(case,chosen,contexts[name],frame,peg_lab if name=='peg' else box_lab, {} if name=='peg' else box_specs,None if name=='peg' else box_transform) scored['initial_flat_index']=int(chosen['P'][0]) scored['candidate_sha256']=case['candidate_sha256']; scored['support_sha256']=case['support_sha256'] np.testing.assert_array_equal(chosen['xyz'],geometry.xyz.reshape(-1,3)[chosen['F']]) require_equal(scored['initial_flat_index'],case['first'],'same lambda initial') common=len(np.intersect1d(chosen['P'],b['P'])) scored['paired_vs_lambda1']=dict(priority_shared_nodes=common,priority_replaced_nodes=32-common, final_shared_nodes=len(np.intersect1d(chosen['F'],b['F']))) row['conditions'][str(w)]=scored arrays.update({key+'/'+str(w)+'/'+k:v for k,v in data.items()}) for w in LAMBDAS: r=row['conditions'][str(w)]; base=row['conditions']['1.0'] r['paired_vs_lambda1'].update( priority_reference_delta=r['stages']['P']['unique_reference_count']-base['stages']['P']['unique_reference_count'], final_reference_delta=r['stages']['F']['unique_reference_count']-base['stages']['F']['unique_reference_count'], surface_mean_delta_mm=r['surface_distance_mm']['mean']-base['surface_distance_mm']['mean'], surface_p95_delta_mm=r['surface_distance_mm']['p95']-base['surface_distance_mm']['p95']) result['cases'][key]=row for method in METHODS: for w in LAMBDAS: require_equal(sum(len(selections[method+'/'+n][str(w)]['F']) for n in OBJECTS),256,'total budget') joined=np.concatenate([selections[method+'/'+n][str(w)]['F'] for n in OBJECTS]) require_equal(len(np.unique(joined)),256,'cross-object source uniqueness') result['answers_ko']=answers(result) result['pass_all']=True write_json(output/(STEM+'.json'),result) np.savez_compressed(output/(STEM+'.npz'),**arrays) # Readback validates storage, not merely the in-memory arrays. with np.load(output/(STEM+'.npz'),allow_pickle=False) as saved: for k,v in arrays.items(): np.testing.assert_array_equal(saved[k],v,err_msg=k) create_plots(output,frame,cases,selections,result,arrays,contexts) write_json(output/'git_end.json',dict(git_status=subprocess.check_output(['git','status','--short'],cwd=REPO).decode(), original_preservation=verify_preserved(baseline))) write_json(output/'source_hashes.json',dict(inputs_before=before,inputs_after=hashes(inputs), sources_before=source_hashes,sources_after=hashes(sources),original_preservation=verify_preserved(baseline))) require_equal(hashes(inputs),before,'all inputs after experiment') require_equal(hashes(sources),source_hashes,'all sources after experiment') verification=dict(status='PASS',baseline_gate=gate,required_tests=dict(summary=test_summary,modules=TEST_MODULES), controls_executed=True,real_fps_calls=dict(baseline=8,controls=16), candidate_initial_support_quota_fixed=True,original_selected_xyz_source_role_feature_alignment=True, feature_unavailable_explicit=True,npz_exact_readback=True,source_input_hashes_unchanged=True, preservation=verify_preserved(baseline),same_pair_joint_and_unique_reference_matching=True, gt_and_segment_selection_independence='synthetic tests; selection has no annotation arguments', ambiguous_physical_spacing='N/A',production_policy_adopted=False, skipped=['simulator','renderer','CUDA/GPU','other frames/seeds/lambdas','feature reconstruction', 'production policy','external upload','dependency installation','commit']) write_json(output/'verification.json',verification) # The report includes only local targets and is generated from the saved numbers. (output/'implementation.patch').touch() create_report(output,result,test_summary) create_html(output,result) verification['document_checks']=verify_links(output) write_json(output/'verification.json',verification) diff=subprocess.check_output(['git','diff','--binary'],cwd=REPO) for path in (Path(__file__),Path(__file__).with_name('test_priority_fps_metric_control.py'),REPORT): delta=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,stdout=subprocess.PIPE) if delta.returncode!=1: raise ValueError('cannot preserve implementation diff') diff+=delta.stdout (output/'implementation.patch').write_bytes(diff) for path in sorted(output.rglob('*')): if path.is_file() and not path.name.endswith('.tracking.json') and path.name not in ('metadata.json','manifest.json','config.yaml','metrics.json'): logger.link_output(path,kind='reports') logger.record(source_run_id=SOURCE_RUN,baseline_exact=True,simulator_executed=False,gpu_executed=False) logger.log({k:{w:dict(priority_refs=r['stages']['P']['unique_reference_count'],final_refs=r['stages']['F']['unique_reference_count'], surface_mean_mm=r['surface_distance_mm']['mean'],surface_p95_mm=r['surface_distance_mm']['p95']) for w,r in row['conditions'].items()} for k,row in result['cases'].items()},step=0,prefix='eval/task03e') print(output,flush=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') parser.add_argument('--baseline',type=Path,required=True) args=parser.parse_args() diagnose(args.source.resolve(),args.out,args.baseline)
if __name__=='__main__': main()123456789101112131415161718192021222324252627282930313233343536<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task03-E metric control</title><style>body{font:16px system-ui;margin:24px auto;max-width:1500px;padding:0 20px;color:#182538}img{width:100%;height:auto}a{color:#075ca8}pre{white-space:pre-wrap}li{margin:.6em 0}</style><h1>Task03-E — Depth-weighted Priority FPS</h1><p>Run 7f657cf88baf4f1f89e594252e243e1c; ep000 Frame 0; S2/S3; λ=1/.25/0. All four exact baseline gates PASS. Geometry-level ablation.</p><p>Priority=32/object; Final Peg=129, Box=127. Actual XYZ and 3D Surface metric retained. GT/segment annotations enter evaluation only.</p><nav><a href="priority_fps_metric_control.json">priority_fps_metric_control.json</a> | <a href="priority_fps_metric_control.npz">priority_fps_metric_control.npz</a> | <a href="verification.json">verification.json</a> | <a href="source_hashes.json">source_hashes.json</a> | <a href="tests.log">tests.log</a> | <a href="implementation.patch">implementation.patch</a> | <a href="report_snapshot.md">report_snapshot.md</a> | <a href="../../docs/visual-graph-integration/03e_priority_fps_metric_control.md">03e_priority_fps_metric_control.md</a> | <a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json">comparison.json</a> | <a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz">f0000_samples.npz</a></nav><ol><li>Z 가중치를 낮추면 실제 Priority 위치가 달라진다. λ=.25/0에서 baseline 대비 교체된 Priority node 수는 S2/peg 26/27점, S2/box 24/25점, S3/peg 24/25점, S3/box 17/23점이다. λ=1→.25→0에서 Priority depth median은 Peg S2 .1930→.1865→.1835m, S3 .2030→.1930→.1865m, Box S2 .5060→.5025→.5000m, S3 .5805→.5035→.4955m로 가까운 쪽으로 이동했다. Peg는 face_0_2의 실제 node가 늘고 face_2_5가 줄었다. Box는 일부 rim 선분의 node가 늘었지만 S3의 최대 depth 1.426m는 유지되고 p95도 1.4057→1.3683→1.3864m로 높게 남는다. XY-only도 X/Y 자체의 depth 의존성을 제거하지 않는다.</li><li>이 frame의 두 estimator 모두 Box rim coverage가 개선됐다. Priority unique reference coverage(λ=1→.25→0)는 S2 (13 → 16 → 17)/103, S3 (3 → 6 → 9)/103이다. Final은 S2 (16 → 19 → 20)/103, S3 (3 → 6 → 12)/103이다. Priority의 실제 matching node 수는 각각 4→7→7과 1→2→3, Final은 5→8→8과 1→2→4다. Reference 증가와 node 증가를 구분해야 하며 유지된 구간은 rim 전체의 일부다.</li><li>Peg 모든 구간이 더 촘촘하게 보존되지는 않았다. Final coverage는 S2 (139 → 137 → 142)/462, S3 (151 → 143 → 160)/462다. face_0_2는 S2 refs 24→36→40, nodes 4→7→7 및 S3 refs 29→43→44, nodes 4→7→7로 증가했다. 반면 face_2_5는 S2 refs 84→72→70, nodes 19→16→15 및 S3 refs 90→66→66, nodes 20→17→15로 감소했다. 전체 matching node 수는 모든 λ에서 S2 29, S3 30으로 같다. Peg의 Surface는 추가 reference를 하나도 보완하지 않았다. 예컨대 λ=0 S3는 30개 node가 160개 reference를 덮는다. Reference coverage 상승은 실제 node 수 증가를 뜻하지 않는다. 물리적 중심선 순서·간격은 저장 정보로 검증되지 않아 N/A다.</li><li>Surface representation의 손익은 물체·estimator에 따라 다르다. λ=.25에서 S2 Box는 rim 개선과 함께 Surface mean/p95가 11.992/20.179→11.903/19.857mm로 줄었지만 λ=0에서는 12.019/20.210mm로 소폭 증가했다. S3 Box는 11.253/18.751→11.461/19.088→11.580/19.077mm로 악화됐다. Peg는 두 control 모두 mean/p95가 baseline보다 증가했다. Box Priority negative ROI union은 S2 3→5→6/32, S3 9→11→14/32로 늘었다. Priority 변경에 따라 뒤따르는 원본 3D Surface FPS도 달라진다. Depth 분위수와 ROI는 설명용이며 filtering이나 일반 평면의 오선택 판정으로 사용하지 않았다.</li><li>Z 조정 후에도 전역 FPS의 국소 구조 누락이 남는다. S2 Box rim_axis1_+1은 모든 λ에서 0/25로 저장 visible span 46.33mm 전체가 reference 기준으로 누락된다. S3 Box rim_axis1_-1도 모든 λ에서 0/26이며 span은 48.74mm다. λ=0의 Peg도 S2 320/462, S3 302/462 observed references가 누락된다. S2 Box rim_axis1_-1의 실제 node 투영 간격은 일부 줄지만 다른 선분 전체 누락을 보완하지 못한다. 한 frame의 최적 λ나 production sampling 정책을 채택하지 않는다.</li></ol><pre>| 조건 | λ | P nodes / refs | F nodes / refs | Surface 추가 / overlap refs | Surface mean / p95 mm | P depth median / p95 m | Negative union P || --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: || S2/peg | 1 | 29 / 139 | 29 / 139 | 0 / 0 | 5.138 / 8.587 | 0.1930 / 0.3250 | 2/32 || S2/peg | 0.25 | 29 / 137 | 29 / 137 | 0 / 0 | 5.168 / 8.607 | 0.1865 / 0.3239 | 3/32 || S2/peg | 0 | 29 / 142 | 29 / 142 | 0 / 0 | 5.263 / 8.676 | 0.1835 / 0.3228 | 2/32 || S2/box | 1 | 4 / 13 | 5 / 16 | 3 / 0 | 11.992 / 20.179 | 0.5060 / 0.6653 | 3/32 || S2/box | 0.25 | 7 / 16 | 8 / 19 | 3 / 0 | 11.903 / 19.857 | 0.5025 / 0.6648 | 5/32 || S2/box | 0 | 7 / 17 | 8 / 20 | 3 / 0 | 12.019 / 20.210 | 0.5000 / 0.6625 | 6/32 || S3/peg | 1 | 30 / 151 | 30 / 151 | 0 / 0 | 5.170 / 8.550 | 0.2030 / 0.3329 | 2/32 || S3/peg | 0.25 | 30 / 143 | 30 / 143 | 0 / 0 | 5.268 / 8.694 | 0.1930 / 0.3325 | 2/32 || S3/peg | 0 | 30 / 160 | 30 / 160 | 0 / 0 | 5.284 / 8.609 | 0.1865 / 0.3325 | 2/32 || S3/box | 1 | 1 / 3 | 1 / 3 | 0 / 0 | 11.253 / 18.751 | 0.5805 / 1.4057 | 9/32 || S3/box | 0.25 | 2 / 6 | 2 / 6 | 0 / 0 | 11.461 / 19.088 | 0.5035 / 1.3683 | 11/32 || S3/box | 0 | 3 / 9 | 4 / 12 | 3 / 0 | 11.580 / 19.077 | 0.4955 / 1.3864 | 14/32 |</pre><h2>S2/S3 and lambda: all selected positions</h2><a href="selection_overview.png"><img src="selection_overview.png" alt="S2/S3 and lambda: all selected positions"></a><h2>Box rim: actual nodes vs covered references</h2><a href="box_structural_zoom.png"><img src="box_structural_zoom.png" alt="Box rim: actual nodes vs covered references"></a><h2>Peg seam: actual nodes vs covered references</h2><a href="peg_structural_zoom.png"><img src="peg_structural_zoom.png" alt="Peg seam: actual nodes vs covered references"></a><h2>Local reference coverage and nearest structural-node distances</h2><a href="local_reference_distances.png"><img src="local_reference_distances.png" alt="Local reference coverage and nearest structural-node distances"></a><h2>Verified Box line projections; Peg physical order/spacing N/A</h2><a href="box_line_node_spacing.png"><img src="box_line_node_spacing.png" alt="Verified Box line projections; Peg physical order/spacing N/A"></a><h2>Structural retention and general Surface trade-off</h2><a href="coverage_surface_tradeoff.png"><img src="coverage_surface_tradeoff.png" alt="Structural retention and general Surface trade-off"></a><h2>Actual X/Z distribution</h2><a href="spatial_xz.png"><img src="spatial_xz.png" alt="Actual X/Z distribution"></a><p>One node can cover multiple references. Reference-ID or image-u order is not arc length. Peg physical spacing and continuous unpreserved length: N/A. Box missing-reference run spans are discrete measured spans only. Unavailable original features are explicit; no dense PCA substitute. No production policy adopted.</p></html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "status": "PASS", "images": [ { "src": "selection_overview.png", "complete": true, "width": 1800, "height": 1920 }, { "src": "box_structural_zoom.png", "complete": true, "width": 2100, "height": 2240 }, { "src": "peg_structural_zoom.png", "complete": true, "width": 2100, "height": 2240 }, { "src": "local_reference_distances.png", "complete": true, "width": 2380, "height": 1820 }, { "src": "box_line_node_spacing.png", "complete": true, "width": 2100, "height": 1680 }, { "src": "coverage_surface_tradeoff.png", "complete": true, "width": 2100, "height": 1500 }, { "src": "spatial_xz.png", "complete": true, "width": 1950, "height": 1820 } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237"""Small local-first scalar logger; W&B is an optional transport.
JSON is used for config.yaml (JSON is a YAML 1.2 subset). No model, dataset,checkpoint format, random state, or training schedule is owned by this module."""import importlibimport jsonimport mathimport osfrom pathlib import Pathimport reimport subprocessfrom datetime import datetime, timezonefrom uuid import uuid4import warnings
REPO = Path(__file__).resolve().parents[1]DEFAULT_PROJECT = 'graph-recurrent-vla'DEFAULT_ENV_FILE = Path('/root/.secrets/wandb.env')GROUPS = {'Graph-Recurrent-VLA-controller': 'controller', 'Graph-Recurrent-VLA-vision': 'vision', 'Graph-Recurrent-VLA-graph': 'graph'}SECRET = re.compile(r'api.?key|token|password|secret|credential', re.I)
def load_env_file(path): """Load optional local credentials without replacing existing environment.""" env_path = Path(path).expanduser() if not env_path.is_file(): return False try: from dotenv import load_dotenv except ImportError: return False try: return load_dotenv(dotenv_path=env_path, override=False, verbose=False) except (OSError, UnicodeError): return False
def load_wandb_env(path=None): return load_env_file(path or os.getenv('WANDB_ENV_FILE') or DEFAULT_ENV_FILE)
def project_name(config=None): config = config or {} return os.getenv('WANDB_PROJECT') or config.get('wandb_project') or DEFAULT_PROJECT
def has_wandb_api_key(): """Return whether an API key exists in the merged process environment.""" return bool(os.environ.get('WANDB_API_KEY', '').strip())
def clean(value): """Persist explicit config only; redact credential fields recursively.""" if isinstance(value, dict): return {str(k): '[REDACTED]' if SECRET.search(str(k)) else clean(v) for k, v in value.items()} if isinstance(value, (list, tuple)): return [clean(v) for v in value] if isinstance(value, Path): return str(value.resolve()) if value is None or isinstance(value, (str, bool, int)): return value if isinstance(value, float): return value if math.isfinite(value) else None raise TypeError(f'Expected JSON configuration or scalar, got {type(value).__name__}')
def write(path, data): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + '.' + uuid4().hex + '.tmp') temporary.write_text(json.dumps(clean(data), indent=2, allow_nan=False) + '\n') temporary.replace(path)
def git_info(): def git(*args): try: return subprocess.check_output(['git', *args], cwd=REPO, stderr=subprocess.DEVNULL, timeout=3).decode().strip() except (OSError, subprocess.SubprocessError): return None return dict(git_commit=git('rev-parse', 'HEAD'), git_dirty=bool(git('status', '--porcelain')))
def scalars(values, prefix=''): """Flatten dictionaries only; lists/tensors/videos are deliberately excluded.""" result = {} for key, value in values.items(): name = f'{prefix}/{key}' if prefix else str(key) if SECRET.search(str(key)): continue if isinstance(value, dict): result.update(scalars(value, name)) elif isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value): result[name] = value return result
class ExperimentLogger: def __init__(self, *, team, config=None, seed=None, model=None, group=None, job_type='train', root=None): if team not in ('visual', 'graph', 'recurrent', 'integration'): raise ValueError('unknown team') load_wandb_env() self.run_id = uuid4().hex self.directory = Path(root or os.getenv('EXPERIMENTS_DIR', REPO / 'experiments')) / self.run_id self.directory.mkdir(parents=True, exist_ok=False) self.config = clean(config or {}) workspace = os.getenv('VESSL_WORKSPACE_NAME', '') self.group = (group or os.getenv('WANDB_RUN_GROUP') or self.config.get('wandb_group') or self.config.get('group') or GROUPS.get(workspace) or {'visual': 'vision', 'recurrent': 'controller'}.get(team, team)) self.metadata = dict(run_id=self.run_id, team=team, group=self.group, model=model, seed=seed, job_type=job_type, project=project_name(self.config), entity=os.getenv('WANDB_ENTITY') or self.config.get('wandb_entity'), started_at=datetime.now(timezone.utc).isoformat(), status='running', outputs=[], **git_info()) self.run = None self.closed = False self._metrics = (self.directory / 'metrics.json').open('w') # An incrementally valid JSON array; flush each event for error preservation. self._metrics.write('[]\n'); self._metrics.flush() self._first = True write(self.directory / 'config.yaml', self.config) self._save() requested = os.getenv('WANDB_MODE', 'online').lower() mode = requested if requested in ('offline', 'disabled') else ( 'online' if has_wandb_api_key() and self.metadata['entity'] else 'offline') self.metadata['wandb_mode'] = mode if mode != 'disabled': try: wandb = importlib.import_module('wandb') self.run = wandb.init(project=self.metadata['project'], entity=self.metadata['entity'], id=self.run_id, group=self.group, job_type=job_type, config=dict(parameters=self.config, experiment=self.metadata.copy()), dir=str(self.directory), mode=mode, resume='never', settings=wandb.Settings(init_timeout=10, save_code=False, disable_git=True, console='off')) self.metadata['wandb_directory'] = self.run.dir self.metadata['wandb_url'] = self.run.url if mode == 'online' else None except Exception as exc: self._failure('init', exc) self._save()
def _save(self): write(self.directory / 'metadata.json', self.metadata) from .experiment_artifacts import save_manifest save_manifest(self.directory, self.metadata)
def _failure(self, operation, exc): # Exception text can contain authentication details; record type only. self.metadata.setdefault('tracking_errors', []).append(dict(operation=operation, type=type(exc).__name__)) warnings.warn(f'Experiment tracking {operation} failed ({type(exc).__name__}); local metrics retained.', RuntimeWarning)
def log(self, metrics, *, step=None, prefix=''): if self.closed: raise RuntimeError('experiment already finished') values = scalars(metrics, prefix) event = dict(run_id=self.run_id, step=step, metrics=values) self._metrics.seek(self._metrics.tell() - 2) self._metrics.write(('' if self._first else ',\n') + json.dumps(event, allow_nan=False) + ']\n') self._metrics.flush() self._first = False if self.run is not None: try: # Let W&B assign transport steps; epoch/evaluation coordinates are data. self.run.log(dict(values, **({'epoch': step} if step is not None else {}))) except Exception as exc: self._failure('log', exc) self._save()
def log_epoch(self, row): values = scalars(row) values.update(scalars(row.get('train_metrics', {}), 'train')) values.update(scalars(row.get('validation_metrics', {}), 'val')) if 'train_mse' in row: values['train/loss'] = row['train_mse'] if 'val_mse' in row: values['val/loss'] = row['val_mse'] self.log(values, step=row.get('epoch'))
def record(self, **metadata): self.metadata.update(clean(metadata)) self._save() if self.run is not None: try: self.run.config.update({'experiment': clean(self.metadata)}, allow_val_change=True) except Exception as exc: self._failure('config', exc) self._save()
def link_output(self, path, *, checkpoint=False, kind=None): """A sidecar associates unchanged existing artifacts with this run.""" if kind not in (None, 'checkpoint', 'rollouts', 'episode_metadata', 'trajectory', 'metrics', 'reports'): raise ValueError('unknown artifact kind') path = Path(path).resolve() if kind is not None: self.metadata.setdefault('artifact_kinds', {})[str(path)] = kind if str(path) not in self.metadata['outputs']: self.metadata['outputs'].append(str(path)) self._save() sidecar = path.with_name(path.name + '.tracking.json') if checkpoint: if sidecar.exists(): try: previous = json.loads(sidecar.read_text()) self.record(source_run_id=previous.get('run_id')) except (OSError, ValueError, AttributeError) as exc: self._failure('artifact', exc) self._save() return write(sidecar, dict(run_id=self.run_id, experiment_directory=str(self.directory.resolve()), artifact=str(path)))
def finish(self, failed=False): if self.closed: return self.closed = True self.metadata.update(status='failed' if failed else 'finished', finished_at=datetime.now(timezone.utc).isoformat()) self._metrics.close() try: if self.run is not None: self.run.finish(exit_code=1 if failed else 0) except Exception as exc: self._failure('finish', exc) finally: self._save()
def __enter__(self): return self
def __exit__(self, exc_type, exc, traceback): if exc_type is not None: self.metadata['exception_type'] = exc_type.__name__ self.finish(failed=exc_type is not None) return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258"""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))12345678910111213141516171819202122232425262728293031323334353637383940414243<!doctype html><html lang="ko"><meta charset="utf-8"><title>Task03-E metric control</title><style>body{font:16px system-ui;margin:24px auto;max-width:1500px;padding:0 20px;color:#182538}img{width:100%;height:auto}a{color:#075ca8}pre{white-space:pre-wrap}li{margin:.6em 0}</style><h1>Task03-E — Depth-weighted Priority FPS</h1><p>Run 7f657cf88baf4f1f89e594252e243e1c; ep000 Frame 0; S2/S3; λ=1/.25/0. All four exact baseline gates PASS. Geometry-level ablation.</p><p>Priority=32/object; Final Peg=129, Box=127. Actual XYZ and 3D Surface metric retained. GT/segment annotations enter evaluation only.</p><nav><a href="priority_fps_metric_control.json">priority_fps_metric_control.json</a> | <a href="priority_fps_metric_control.npz">priority_fps_metric_control.npz</a> | <a href="verification.json">verification.json</a> | <a href="source_hashes.json">source_hashes.json</a> | <a href="tests.log">tests.log</a> | <a href="implementation.patch">implementation.patch</a> | <a href="report_snapshot.md">report_snapshot.md</a> | <a href="../../docs/visual-graph-integration/03e_priority_fps_metric_control.md">03e_priority_fps_metric_control.md</a> | <a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/comparison.json">comparison.json</a> | <a href="../../visual/results/sampling/2551448b0fae4c6bbce3caf48774275f/f0000_samples.npz">f0000_samples.npz</a></nav><ol><li>Z 가중치를 낮추면 실제 Priority 위치가 달라진다. λ=.25/0에서 baseline 대비 교체된 Priority node 수는 S2/peg 26/27점, S2/box 24/25점, S3/peg 24/25점, S3/box 17/23점이다. λ=1→.25→0에서 Priority depth median은 Peg S2 .1930→.1865→.1835m, S3 .2030→.1930→.1865m, Box S2 .5060→.5025→.5000m, S3 .5805→.5035→.4955m로 가까운 쪽으로 이동했다. Peg는 face_0_2의 실제 node가 늘고 face_2_5가 줄었다. Box는 일부 rim 선분의 node가 늘었지만 S3의 최대 depth 1.426m는 유지되고 p95도 1.4057→1.3683→1.3864m로 높게 남는다. XY-only도 X/Y 자체의 depth 의존성을 제거하지 않는다.</li><li>이 frame의 두 estimator 모두 Box rim coverage가 개선됐다. Priority unique reference coverage(λ=1→.25→0)는 S2 (13 → 16 → 17)/103, S3 (3 → 6 → 9)/103이다. Final은 S2 (16 → 19 → 20)/103, S3 (3 → 6 → 12)/103이다. Priority의 실제 matching node 수는 각각 4→7→7과 1→2→3, Final은 5→8→8과 1→2→4다. Reference 증가와 node 증가를 구분해야 하며 유지된 구간은 rim 전체의 일부다.</li><li>Peg 모든 구간이 더 촘촘하게 보존되지는 않았다. Final coverage는 S2 (139 → 137 → 142)/462, S3 (151 → 143 → 160)/462다. face_0_2는 S2 refs 24→36→40, nodes 4→7→7 및 S3 refs 29→43→44, nodes 4→7→7로 증가했다. 반면 face_2_5는 S2 refs 84→72→70, nodes 19→16→15 및 S3 refs 90→66→66, nodes 20→17→15로 감소했다. 전체 matching node 수는 모든 λ에서 S2 29, S3 30으로 같다. Peg의 Surface는 추가 reference를 하나도 보완하지 않았다. 예컨대 λ=0 S3는 30개 node가 160개 reference를 덮는다. Reference coverage 상승은 실제 node 수 증가를 뜻하지 않는다. 물리적 중심선 순서·간격은 저장 정보로 검증되지 않아 N/A다.</li><li>Surface representation의 손익은 물체·estimator에 따라 다르다. λ=.25에서 S2 Box는 rim 개선과 함께 Surface mean/p95가 11.992/20.179→11.903/19.857mm로 줄었지만 λ=0에서는 12.019/20.210mm로 소폭 증가했다. S3 Box는 11.253/18.751→11.461/19.088→11.580/19.077mm로 악화됐다. Peg는 두 control 모두 mean/p95가 baseline보다 증가했다. Box Priority negative ROI union은 S2 3→5→6/32, S3 9→11→14/32로 늘었다. Priority 변경에 따라 뒤따르는 원본 3D Surface FPS도 달라진다. Depth 분위수와 ROI는 설명용이며 filtering이나 일반 평면의 오선택 판정으로 사용하지 않았다.</li><li>Z 조정 후에도 전역 FPS의 국소 구조 누락이 남는다. S2 Box rim_axis1_+1은 모든 λ에서 0/25로 저장 visible span 46.33mm 전체가 reference 기준으로 누락된다. S3 Box rim_axis1_-1도 모든 λ에서 0/26이며 span은 48.74mm다. λ=0의 Peg도 S2 320/462, S3 302/462 observed references가 누락된다. S2 Box rim_axis1_-1의 실제 node 투영 간격은 일부 줄지만 다른 선분 전체 누락을 보완하지 못한다. 한 frame의 최적 λ나 production sampling 정책을 채택하지 않는다.</li></ol><pre>| 조건 | λ | P nodes / refs | F nodes / refs | Surface 추가 / overlap refs | Surface mean / p95 mm | P depth median / p95 m | Negative union P || --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: || S2/peg | 1 | 29 / 139 | 29 / 139 | 0 / 0 | 5.138 / 8.587 | 0.1930 / 0.3250 | 2/32 || S2/peg | 0.25 | 29 / 137 | 29 / 137 | 0 / 0 | 5.168 / 8.607 | 0.1865 / 0.3239 | 3/32 || S2/peg | 0 | 29 / 142 | 29 / 142 | 0 / 0 | 5.263 / 8.676 | 0.1835 / 0.3228 | 2/32 || S2/box | 1 | 4 / 13 | 5 / 16 | 3 / 0 | 11.992 / 20.179 | 0.5060 / 0.6653 | 3/32 || S2/box | 0.25 | 7 / 16 | 8 / 19 | 3 / 0 | 11.903 / 19.857 | 0.5025 / 0.6648 | 5/32 || S2/box | 0 | 7 / 17 | 8 / 20 | 3 / 0 | 12.019 / 20.210 | 0.5000 / 0.6625 | 6/32 || S3/peg | 1 | 30 / 151 | 30 / 151 | 0 / 0 | 5.170 / 8.550 | 0.2030 / 0.3329 | 2/32 || S3/peg | 0.25 | 30 / 143 | 30 / 143 | 0 / 0 | 5.268 / 8.694 | 0.1930 / 0.3325 | 2/32 || S3/peg | 0 | 30 / 160 | 30 / 160 | 0 / 0 | 5.284 / 8.609 | 0.1865 / 0.3325 | 2/32 || S3/box | 1 | 1 / 3 | 1 / 3 | 0 / 0 | 11.253 / 18.751 | 0.5805 / 1.4057 | 9/32 || S3/box | 0.25 | 2 / 6 | 2 / 6 | 0 / 0 | 11.461 / 19.088 | 0.5035 / 1.3683 | 11/32 || S3/box | 0 | 3 / 9 | 4 / 12 | 3 / 0 | 11.580 / 19.077 | 0.4955 / 1.3864 | 14/32 |</pre><h2>S2/S3 and lambda: all selected positions</h2><a href="selection_overview.png"><img src="selection_overview.png" alt="S2/S3 and lambda: all selected positions"></a><h2>Box rim: actual nodes vs covered references</h2><a href="box_structural_zoom.png"><img src="box_structural_zoom.png" alt="Box rim: actual nodes vs covered references"></a><h2>Peg seam: actual nodes vs covered references</h2><a href="peg_structural_zoom.png"><img src="peg_structural_zoom.png" alt="Peg seam: actual nodes vs covered references"></a><h2>Local reference coverage and nearest structural-node distances</h2><a href="local_reference_distances.png"><img src="local_reference_distances.png" alt="Local reference coverage and nearest structural-node distances"></a><h2>Verified Box line projections; Peg physical order/spacing N/A</h2><a href="box_line_node_spacing.png"><img src="box_line_node_spacing.png" alt="Verified Box line projections; Peg physical order/spacing N/A"></a><h2>Structural retention and general Surface trade-off</h2><a href="coverage_surface_tradeoff.png"><img src="coverage_surface_tradeoff.png" alt="Structural retention and general Surface trade-off"></a><h2>Actual X/Z distribution</h2><a href="spatial_xz.png"><img src="spatial_xz.png" alt="Actual X/Z distribution"></a><p>One node can cover multiple references. Reference-ID or image-u order is not arc length. Peg physical spacing and continuous unpreserved length: N/A. Box missing-reference run spans are discrete measured spans only. Unavailable original features are explicit; no dense PCA substitute. No production policy adopted.</p><script>window.addEventListener('load', () => { const images=Array.from(document.images).map(im=>({src:im.getAttribute('src'),complete:im.complete,width:im.naturalWidth,height:im.naturalHeight})); const out=document.createElement('pre'); out.id='browser-image-verification'; out.textContent=JSON.stringify({status:images.length===7 && images.every(im=>im.complete && im.width>0 && im.height>0)?'PASS':'FAIL',images}); document.body.appendChild(out);});</script></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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""Temporary Grounding DINO visualization runner.
Run from the repository root::
.venv/bin/python visual/runtime/test/run_grounding.py --device cpu
The default input is ``visual/data/step2/ep000.npz`` when it exists; otherwisethe checked-in Step 2 contact sheet supplies six representative RGB frames.Use ``--input`` for another episode NPZ, a contact sheet, or a PNG/JPEG.Episode NPZ files must contain``base_camera/rgb`` with shape (T,H,W,3), uint8 RGB. Annotated PNGs, detections,and an MP4 when multiple frames are available are written under ``--out``.Episode videos use every recorded camera frame and derive playback fps from therecorded timestamps when available."""
from __future__ import annotations
import argparseimport jsonimport sysimport timefrom contextlib import nullcontextfrom pathlib import Path
import cv2import imageio.v2 as imageioimport numpy as np
SCRIPT_DIR = Path(__file__).resolve().parentRUNTIME_DIR = SCRIPT_DIR.parentVISUAL_ROOT = SCRIPT_DIR.parents[1]DEFAULT_EPISODE = VISUAL_ROOT / "data/step2/ep000.npz"DEFAULT_SHEET = VISUAL_ROOT / "results/step2/ep000_base_camera_frames.jpg"sys.path.insert(0, str(RUNTIME_DIR))
from grounding import GDino # noqa: E402
PROMPTS = { "peg": "red and white block", "box": "cardboard box",}COLORS = { "peg": (255, 70, 70), "box": (60, 130, 255),}
def annotate( rgb: np.ndarray, detections: dict[str, tuple[list, list]], frame_idx: int, top_k: int = 1, scale: int = 3,) -> np.ndarray: """Draw detections on an enlarged canvas so boxes and labels are readable.""" height, width = rgb.shape[:2] enlarged = cv2.resize(rgb, (width * scale, height * scale), interpolation=cv2.INTER_CUBIC) header_height = 40 image = cv2.copyMakeBorder(enlarged, header_height, 0, 0, 0, cv2.BORDER_CONSTANT, value=(24, 24, 24)) for name, (boxes, scores) in detections.items(): color = COLORS[name] for rank, (box, score) in enumerate(zip(boxes[:top_k], scores[:top_k])): x1, y1, x2, y2 = (int(round(value * scale)) for value in box) y1 += header_height y2 += header_height thickness = max(2, scale) if rank == 0 else 1 cv2.rectangle(image, (x1, y1), (x2, y2), color, thickness) label = f"{name} {score:.2f}" if rank == 0 else f"{name} #{rank + 1} {score:.2f}" text_y = max(header_height + 20, y1 - 6) cv2.putText(image, label, (x1 + 3, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 3, cv2.LINE_AA) cv2.putText(image, label, (x1 + 3, text_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 1, cv2.LINE_AA)
title = f"sample {frame_idx} | Grounding DINO" cv2.putText(image, title, (10, 27), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 1, cv2.LINE_AA) return image
def load_rgb(path: Path, camera: str, parser: argparse.ArgumentParser) -> tuple[np.ndarray, str, np.ndarray | None]: """Load an episode, a Step 2 contact sheet, or one RGB image.""" if path.suffix.lower() == ".npz": with np.load(path) as archive: rgb_key = f"{camera}/rgb" if rgb_key not in archive: parser.error(f"{path} has no '{rgb_key}' array") timestamps = archive["timestamp"] if "timestamp" in archive else None return archive[rgb_key], "episode", timestamps
bgr = cv2.imread(str(path), cv2.IMREAD_COLOR) if bgr is None: parser.error(f"could not read image: {path}") rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB) if path.name.endswith(f"_{camera}_frames.jpg"): height, width = rgb.shape[:2] if width % 3 or height % (width // 3): parser.error(f"unexpected Step 2 contact sheet dimensions: {rgb.shape}") tile = width // 3 frames = np.stack([rgb[y:y + tile, :tile] for y in range(0, height, tile)]) return frames, "contact_sheet", None return rgb[None], "image", None
def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--input", type=Path, default=DEFAULT_EPISODE if DEFAULT_EPISODE.is_file() else DEFAULT_SHEET, help="Episode NPZ, Step 2 contact sheet, or RGB image (uses ep000 NPZ when present)", ) parser.add_argument("--out", type=Path, default=VISUAL_ROOT / "results/runtime_grounding") parser.add_argument("--camera", default="base_camera") parser.add_argument("--stride", type=int, default=1, help="Run inference on every Nth frame (default: every frame)") parser.add_argument("--max-frames", type=int, default=None, help="Optional cap on sampled frames") parser.add_argument("--fps", type=float, default=None, help="Output video fps (default: timestamps for episodes, 2 for sheets)") parser.add_argument("--display-scale", type=int, default=None, help="Visualization scale (default: 1 at 512px or larger, otherwise 3)") parser.add_argument("--top-k", type=int, default=1, help="Draw this many boxes per prompt") parser.add_argument("--device", default="cuda") parser.add_argument("--threshold", type=float, default=0.1) parser.add_argument("--peg-prompt", default=PROMPTS["peg"]) parser.add_argument("--box-prompt", default=PROMPTS["box"]) args = parser.parse_args()
if args.stride < 1: parser.error("--stride must be at least 1") if args.fps is not None and args.fps <= 0: parser.error("--fps must be positive") if args.display_scale is not None and args.display_scale < 1: parser.error("--display-scale must be at least 1") if not args.input.is_file(): parser.error(f"input file does not exist: {args.input}") args.out.mkdir(parents=True, exist_ok=True) frames_dir = args.out / "frames" frames_dir.mkdir(parents=True, exist_ok=True)
rgb, input_kind, timestamps = load_rgb(args.input, args.camera, parser)
if rgb.ndim != 4 or rgb.shape[-1] != 3: parser.error(f"expected {args.camera}/rgb with shape (T,H,W,3), got {rgb.shape}")
stride = args.stride frame_indices = list(range(0, len(rgb), stride)) if args.max_frames is not None: frame_indices = frame_indices[:max(0, args.max_frames)] if not frame_indices: parser.error("input episode contains no frames to process") if timestamps is not None and len(timestamps) != len(rgb): parser.error(f"timestamp length {len(timestamps)} differs from RGB frame count {len(rgb)}") if args.fps is not None: fps = args.fps elif timestamps is not None and len(frame_indices) > 1: gaps = np.diff(np.asarray(timestamps)[frame_indices]) positive_gaps = gaps[gaps > 0] fps = round(float(1 / np.median(positive_gaps)), 3) if len(positive_gaps) else 10.0 else: fps = 2.0 if input_kind == "contact_sheet" else 10.0 display_scale = args.display_scale or (1 if min(rgb.shape[1:3]) >= 512 else 3)
prompts = {"peg": args.peg_prompt, "box": args.box_prompt} detector = GDino(device=args.device, threshold=args.threshold) records = [] video_path = args.out / "grounding.mp4" if len(frame_indices) > 1 else None started = time.perf_counter()
video_context = imageio.get_writer(video_path, fps=fps, macro_block_size=1) if video_path else nullcontext() with video_context as writer: for frame_idx in frame_indices: image = np.asarray(rgb[frame_idx], dtype=np.uint8) detections = {} record = {"frame": int(frame_idx), "detections": {}} for name, prompt in prompts.items(): boxes, scores = detector(image, prompt) detections[name] = (boxes, scores) record["detections"][name] = { "prompt": prompt, "boxes": boxes, "scores": scores, "timing_ms": dict(detector.last_ms), }
rendered = annotate(image, detections, frame_idx, top_k=max(1, args.top_k), scale=display_scale) frame_name = f"frame_{frame_idx:05d}.png" cv2.imwrite(str(frames_dir / frame_name), cv2.cvtColor(rendered, cv2.COLOR_RGB2BGR)) if writer is not None: writer.append_data(rendered) records.append(record) print(f"frame {frame_idx}: " + ", ".join( f"{name}={len(detections[name][0])}" for name in prompts ), flush=True)
result = { "input": str(args.input.resolve()), "camera": args.camera, "input_kind": input_kind, "device": args.device, "threshold": args.threshold, "stride": stride, "fps": fps, "display_scale": display_scale, "frames_processed": len(frame_indices), "elapsed_seconds": round(time.perf_counter() - started, 3), "video": str(video_path) if video_path else None, "frames_dir": str(frames_dir), "results": records, } (args.out / "detections.json").write_text(json.dumps(result, indent=2), encoding="utf-8") if video_path: print(f"saved video: {video_path}") print(f"saved images: {frames_dir}")
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738"""RGB-only initialization behavior, including rejection and late acquisition."""
import sysimport unittestfrom pathlib import Path
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from initialization import assign, detect_initial # noqa: E402
class InitializationTest(unittest.TestCase): def test_joint_assignment_does_not_give_same_box_to_both_objects(self): peg = [([10, 10, 30, 30], 0.8)] box = [([11, 11, 31, 31], 0.9), ([50, 50, 70, 70], 0.5)] self.assertEqual(assign(peg, box), (peg[0], box[1]))
def test_late_initialization_requires_two_consistent_scans(self): frames = np.zeros((11, 100, 100, 3), dtype=np.uint8) frames[:, 0, 0, 0] = np.arange(11)
def detector(rgb, prompt): t = int(rgb[0, 0, 0]) if prompt == "peg": return ([[10, 10, 25, 25]], [0.8]) if t == 0 else ([], []) if t in (5, 10): return ([[60, 10, 75, 25]], [0.7]) return [], []
initial = detect_initial(frames, detector, {"peg": "peg", "box": "box"}) self.assertEqual(initial["peg"]["frame"], 0) self.assertEqual(initial["box"]["frame"], 10) self.assertEqual(initial["box"]["box"], [60, 10, 75, 25])
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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""Task03-E contracts; FPS inputs are synthetic, real replay belongs to runner."""import copyimport inspectfrom pathlib import Pathfrom types import SimpleNamespaceimport unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.geometry import OrganizedGeometryfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_priority_fps_metric_control as controlfrom visual.runtime.test.sampling_evaluation import CoverageMatcher, staged_reference_coverage
def synthetic_case(): flat=np.arange(120,dtype=np.int64) points=np.column_stack((np.sin(flat*.21),np.cos(flat*.15),flat*.02)).astype(np.float32) candidates=flat[::2] return dict(candidate_flat=candidates,candidate_xyz=points[::2].copy(),support_flat=flat, support_xyz=points,first=8,seed=0,budget=70,saved_flat=flat[:70], saved_features={'normals':points[:70].copy(),'flag':flat[:70]%3==0})
class MetricSelectionTests(unittest.TestCase): def test_metric_squared_distance_formula_and_original_unchanged(self): points=np.array([[0,0,1],[3,4,9],[1,5,2]],np.float32); before=points.copy() for weight in control.LAMBDAS: metric=control.metric_coordinates(points,weight) self.assertFalse(np.shares_memory(metric,points)) diff=points.astype(float)[:,None]-points.astype(float)[None,:] expected=diff[...,0]**2+diff[...,1]**2+weight*diff[...,2]**2 np.testing.assert_array_equal(((metric[:,None]-metric[None,:])**2).sum(-1),expected) np.testing.assert_array_equal(points,before) with self.assertRaises(ValueError): control.metric_coordinates(points,.5)
def test_zero_weight_z_change_does_not_change_priority_with_xy_ties(self): case=synthetic_case(); points=case['candidate_xyz'].copy(); points[2,:2]=points[3,:2] altered=points.copy(); altered[:,2]=np.arange(len(points))**3 a=fps_indices(control.metric_coordinates(points,0.),32,initial=[4]) b=fps_indices(control.metric_coordinates(altered,0.),32,initial=[4]) np.testing.assert_array_equal(a,b) # Exact XY ties retain existing source-row argmax behaviour. tie=np.zeros((40,3)); tie[:,2]=np.arange(40) np.testing.assert_array_equal(fps_indices(control.metric_coordinates(tie,0.),4,initial=[8]),[8,0,1,2])
def test_lambda_one_matches_existing_priority_and_seeded_surface(self): case=synthetic_case(); original=copy.deepcopy(case) p=fps_indices(case['candidate_xyz'],32,initial=[4]) initial=np.searchsorted(case['support_flat'],case['candidate_flat'][p]) final=fps_indices(case['support_xyz'],70,initial=initial) selected=control.select(case,1.) np.testing.assert_array_equal(selected['P'],case['candidate_flat'][p]) np.testing.assert_array_equal(selected['F'],case['support_flat'][final]) for field in ('candidate_flat','candidate_xyz','support_flat','support_xyz'): np.testing.assert_array_equal(case[field],original[field])
def test_all_weights_fixed_initial_quota_original_xyz_surface_metric(self): case=synthetic_case(); original=copy.deepcopy(case) for w in control.LAMBDAS: with patch.object(control,'fps_indices',wraps=fps_indices) as calls: chosen=control.select(case,w) self.assertEqual(calls.call_count,2) np.testing.assert_array_equal(calls.call_args_list[0].args[0],control.metric_coordinates(case['candidate_xyz'],w)) np.testing.assert_array_equal(calls.call_args_list[1].args[0],case['support_xyz']) self.assertEqual(chosen['P'][0],case['first']); self.assertEqual(len(chosen['P']),32) self.assertEqual(len(chosen['S']),38); self.assertEqual(len(chosen['F']),70) self.assertEqual(len(np.unique(chosen['F'])),70) self.assertFalse(np.intersect1d(chosen['P'],chosen['S']).size) np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][chosen['F']]) for field in ('candidate_flat','candidate_xyz','support_flat','support_xyz'): np.testing.assert_array_equal(case[field],original[field])
def test_every_gate_required_before_either_control(self): cases={k:synthetic_case() for k in ('S2/peg','S2/box','S3/peg','S3/box')} for key in cases: gate={k:dict(status='PASS') for k in cases}; gate[key]['status']='FAIL' with patch.object(control,'select',side_effect=AssertionError('must not select')): with self.assertRaises(ValueError): control.execute_controls(cases,gate) with patch.object(control,'select',side_effect=AssertionError('must not select')): with self.assertRaises(ValueError): control.execute_controls(cases,{})
def test_gt_annotations_and_segment_labels_cannot_affect_selection(self): case=synthetic_case(); before=control.select(case,.25) # Change annotations/segment labels while holding selection inputs fixed. annotations=[dict(gt=np.ones((4,3)),segments=['a']*4),dict(gt=np.full((4,3),999),segments=['ambiguous']*4)] for annotation in annotations: case_with_extra=dict(case,**annotation) after=control.select(case_with_extra,.25) np.testing.assert_array_equal(before['F'],after['F']) np.testing.assert_array_equal(before['xyz'],after['xyz']) self.assertEqual(tuple(inspect.signature(control.select).parameters),('case','weight')) with self.assertRaises(TypeError): control.select(case,.25,gt={})
def test_feature_gather_exact_only_available_rows_no_placeholder(self): case=synthetic_case(); before=copy.deepcopy(case) available,positions,features=control.feature_rows(case,np.array([8,100,4,119,20])) np.testing.assert_array_equal(available,[True,False,True,False,True]) np.testing.assert_array_equal(positions,[0,2,4]) for name,value in features.items(): np.testing.assert_array_equal(value,case['saved_features'][name][[8,4,20]]) np.testing.assert_array_equal(case['saved_features'][name],before['saved_features'][name])
class LocalEvaluationTests(unittest.TestCase): def test_joint_matching_same_pair_dedup_and_staged_union(self): xyz=np.zeros((1,10,3),np.float32); xyz[0,3]=[.1,0,0] geometry=OrganizedGeometry(xyz,np.ones((1,10),bool),{0:np.ones((1,10),bool)},np.zeros((1,10),bool)) matcher=CoverageMatcher(geometry,0,(np.array([[0.,0.],[7.,0.],[7.5,0.]]),np.array([[.1,0,0],[0,0,0],[0,0,0]]))) ids,hit=matcher.reference_hits(np.array([0,3])) self.assertFalse(len(ids)); self.assertFalse(len(hit)) # One node covers two refs, and multiple nodes cover those same two refs. p=np.array([7]); s=np.array([6,8]); f=np.r_[p,s] row=staged_reference_coverage(matcher,f,p,s,f) self.assertEqual(row['stages']['P']['matched_node_count'],1) self.assertEqual(row['stages']['P']['unique_reference_count'],2) self.assertEqual(row['stages']['S']['matched_node_count'],2) self.assertEqual(row['differences']['S_minus_P']['count'],0) self.assertEqual(row['differences']['P_intersect_S']['count'],2) self.assertEqual(row['reference_ids']['F'],[1,2])
def test_peg_face_pair_endpoint_ambiguity_and_nonphysical_order_na(self): face=np.array([[0,0,2],[0,5,2]],np.int8); visible=np.ones_like(face,bool) seam=np.array([[False,True,True],[True,True,True]]) uv=np.column_stack(np.nonzero(seam))[:,::-1] labels,members=control.peg_labels(face,visible,seam,uv) self.assertIn('ambiguous',labels) self.assertTrue(any(len(m)>1 for m in members)) r=control.segment_spacing([.03,.01,.02],[False,True,True],[.015],order_verified=False) self.assertEqual(r['status'],'N/A') self.assertNotIn('actual_inter_node_gap_mm',r)
def test_rim_line_identity_from_existing_transform_and_corner_ambiguity(self): # Known line points with shuffled reference order. Corner stays ambiguous. xyz=np.array([[.1,-.01,0],[.1,.005,-.01],[.1,-.01,-.01],[.1,-.01,.005]]) pose=np.array([0,0,0,1,0,0,0],float) labels,specs,_=control.rim_labels(xyz,np.eye(4),pose,pose,.01) self.assertEqual(labels.tolist(),['rim_axis1_-1','rim_axis2_-1','ambiguous','rim_axis1_-1']) self.assertTrue(specs['rim_axis1_-1']['order_verified'])
def test_spacing_uses_actual_node_projections_not_covered_reference_centres(self): row=control.segment_spacing(np.array([.03,.01,.02,.04]),np.array([False,True,False,True]), np.array([.012,.038]),order_verified=True) np.testing.assert_allclose(row['actual_inter_node_gap_mm'],[26]) self.assertAlmostEqual(row['start_tail_to_first_node_mm'],2) self.assertAlmostEqual(row['end_tail_from_last_node_mm'],2) self.assertEqual(row['missing_reference_runs'][0]['reference_count'],2) self.assertAlmostEqual(row['missing_reference_run_total_span_mm'],10) self.assertIsNone(row['continuous_unpreserved_length_mm']) self.assertEqual(control.segment_spacing([.01],[True],[],order_verified=True)['status'],'N/A')
def test_actual_gap_includes_matching_node_outside_visible_reference_span(self): # A joint-matching node may lie just beyond the first reference centre. # Keep that actual node when measuring adjacent selected-node intervals. row=control.segment_spacing([.01,.02,.03],[True,False,True], [.009,.025],order_verified=True) np.testing.assert_allclose(row['actual_inter_node_gap_mm'],[16.]) self.assertEqual(row['selected_nodes_within_reference_span'],1) self.assertAlmostEqual(row['start_tail_to_first_node_mm'],15.)
if __name__=='__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148"""Same-estimator equivalence including disconnected and degenerate patches."""from dataclasses import replaceimport unittestimport numpy as np
from visual.runtime.geometry import build_organized_geometry, compute_geometric_features, GeometryParametersfrom visual.runtime.test.normal_diagnostics import angular_error, quantize, synthetic_case, synthetic_framefrom visual.runtime.test.normal_estimators import local_planefrom visual.runtime.test.pca_optimized import build_geometry, local_plane_optimized, process_optimized, smallest_eigenvector
K = np.array([[256., 0, 32.], [0, 256., 32.], [0, 0, 1]])
class PCAOptimizationTests(unittest.TestCase): def assert_equivalent(self, frame): g = build_organized_geometry(frame) p = GeometryParameters() reference = {i: compute_geometric_features(g, i, *local_plane(g, i, 5), p) for i in g.object_masks} for solver in ('eigh', 'analytic'): actual = process_optimized(frame, solver=solver) np.testing.assert_array_equal(g.xyz, actual.geometry.xyz) for oid, expected in reference.items(): f = actual.objects[oid] for name in expected.__dataclass_fields__: if name == 'normals': if f.normal_valid.any(): self.assertLess(float(angular_error(f.normals[f.normal_valid], expected.normals[f.normal_valid]).max()), .001) elif name == 'normal_variation_rad': np.testing.assert_allclose(f.normal_variation_rad, expected.normal_variation_rad, atol=2e-5, rtol=0) else: np.testing.assert_array_equal(getattr(f, name), getattr(expected, name), err_msg=name)
def test_all_synthetic_geometries_float_and_quantized(self): for kind in ('front', 'tilted', 'crease', 'step'): frame, _, _ = synthetic_case(kind, K, shape=(64, 64), phase_m=.00025) for q in (False, True): with self.subTest(kind=kind, quantized=q): self.assert_equivalent(replace(frame, depth=quantize(frame.depth)) if q else frame)
def test_image_borders_invalid_overlap_two_objects_and_background_jumps(self): rng = np.random.default_rng(21) depth = np.full((31, 35), .25, np.float32) depth[:, 18:] = .45 depth[8, 8], depth[11, 10], depth[3, 3] = np.nan, 0, np.inf peg = rng.random(depth.shape) > .18 box = np.zeros_like(peg); box[10:22, 14:26] = True frame = replace(synthetic_frame(depth, K, peg), masks={0: peg, 1: box}) self.assert_equivalent(frame)
def test_disconnected_depth_surface_and_patch_limited_connectivity(self): depth = np.full((25, 25), .25, np.float32) mask = np.zeros_like(depth, bool); mask[3:22, 3:22] = True mask[5:20, 12] = False # Far away connection cannot bypass the local gap. depth[:, 13:] = .26 self.assert_equivalent(synthetic_frame(depth, K, mask))
def test_sparse_empty_collinear_tiny_and_invalid_only(self): for h, w in ((1, 1), (2, 2), (7, 9), (15, 17)): for kind in ('empty', 'line', 'all', 'invalid'): mask = np.zeros((h, w), bool) if kind=='line': mask[h//2] = True if kind in ('all', 'invalid'): mask[:] = True depth = np.full((h, w), 0 if kind=='invalid' else .25, np.float32) with self.subTest(h=h, w=w, kind=kind): self.assert_equivalent(synthetic_frame(depth, K, mask))
def test_camera_backprojection_preserves_arithmetic_and_inputs(self): rng = np.random.default_rng(0) depth = rng.uniform(.1, 2, (23, 29)).astype(np.float32); depth[0, :5] = [0, -1, np.nan, np.inf, -np.inf] intrinsic = np.array([[173.7, 0, 14.1], [0, 231.3, 11.8], [0, 0, 1]]) frame = synthetic_frame(depth, intrinsic, rng.random(depth.shape)>.1) before = frame.depth.copy(); a, b = build_organized_geometry(frame), build_geometry(frame) np.testing.assert_array_equal(a.xyz, b.xyz); np.testing.assert_array_equal(before, frame.depth) np.testing.assert_array_equal(a.valid_depth, b.valid_depth)
def test_analytic_eigensolver_rotations_and_degeneracy(self): rng = np.random.default_rng(5) basis, _ = np.linalg.qr(rng.normal(size=(200, 3, 3))) values = np.tile([1e-8, 2e-6, 8e-6], (200, 1)) values[:4] = [[0, 0, 0], [0, 0, 1], [1, 1, 1], [1, 1+1e-12, 2]] covariance = np.einsum('nij,nj,nkj->nik', basis, values, basis) actual, vectors, fallback = smallest_eigenvector(covariance) expected, truth = np.linalg.eigh(covariance) np.testing.assert_allclose(actual, expected, atol=1e-14, rtol=1e-7) self.assertGreaterEqual(fallback, 4) good = np.arange(len(values)) >= 4 dot = np.abs(np.sum(vectors[good]*truth[good, :, 0], axis=1)) self.assertLess(float(np.max(1-dot)), 1e-12)
def test_large_coordinate_translation_does_not_destroy_local_covariance(self): frame, _, _ = synthetic_case('tilted', K, shape=(64, 64), z0=10, phase_m=.00025) self.assert_equivalent(frame)
def test_parameters_reject_invalid_solver_and_unknown_mask(self): frame = synthetic_frame(np.ones((9, 9), np.float32), K, np.ones((9, 9), bool)) with self.assertRaises(ValueError): local_plane_optimized(build_geometry(frame), 0, solver='bad') with self.assertRaises(ValueError): build_geometry(replace(frame, masks={3:frame.masks[0]}))
def test_two_object_threads_preserve_every_output(self): frame,_,_=synthetic_case('crease',K,shape=(64,64),phase_m=.00025) box=np.roll(frame.masks[0],17,axis=1) frame=replace(frame,depth=quantize(frame.depth),masks={0:frame.masks[0],1:box}) serial=process_optimized(frame,solver='analytic') parallel=process_optimized(frame,solver='analytic',parallel=True) for oid in serial.objects: for key in serial.objects[oid].__dataclass_fields__: np.testing.assert_array_equal(getattr(serial.objects[oid],key),getattr(parallel.objects[oid],key))
def check_torch_device(self, device, backend='eigh'): import torch from visual.runtime.test.pca_torch import TorchPCA5 for kind in ('front', 'tilted', 'crease', 'step'): frame, _, _ = synthetic_case(kind, K, shape=(32, 32), phase_m=.00025) depth = quantize(frame.depth); depth[15, 15] = 0 frame = replace(frame, depth=depth) g = build_organized_geometry(frame) processor = TorchPCA5(K, frame.depth.shape, device=device, backend=backend) td=torch.as_tensor(depth,device=device).T.contiguous().T tm={i:torch.as_tensor(m,device=device).T.contiguous().T for i,m in frame.masks.items()} actual = processor(td,tm) np.testing.assert_array_equal(actual['xyz'].cpu().numpy(), g.xyz) for oid in g.object_masks: expected = compute_geometric_features(g, oid, *local_plane(g, oid, 5), GeometryParameters()) for key in expected.__dataclass_fields__: a, b = actual['objects'][oid][key].cpu().numpy(), getattr(expected, key) if key in ('normals', 'normal_variation_rad'): np.testing.assert_allclose(a, b, atol=2e-5, rtol=0, err_msg=key) else: np.testing.assert_array_equal(a, b, err_msg=key)
def test_torch_float64_contract_on_cpu(self): self.check_torch_device('cpu')
def test_torch_cuda_contract_when_available(self): import torch if not torch.cuda.is_available(): self.skipTest('CUDA unavailable on current host') self.check_torch_device('cuda')
def test_triton_cuda_contract_when_available(self): import torch if not torch.cuda.is_available(): self.skipTest('CUDA unavailable on current host') self.check_torch_device('cuda',backend='triton')
def test_fused_features_cuda_contract_when_available(self): import torch if not torch.cuda.is_available(): self.skipTest('CUDA unavailable on current host') self.check_torch_device('cuda',backend='triton_fused')
if __name__ == '__main__': unittest.main()visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/config/1088901223b936b83da80f8770bd43b1e6b1de9b345776ee42a59a1894d3f044/config.yamlAdded+97
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/metrics/2d3d14deeb565bc7d762f21e103cfdf31bbab43c3235673b4b61d770135f29ab/metrics.jsonAdded+56
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522/tracking.pyAdded+93
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f/experiment_artifacts.pyAdded+470
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a/benchmark_pca_cuda.pyAdded+92
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/08503679a20063b8b8b9d46bd17ad88b4908daaea345ca850a26659a8c411917/html_preview.pngAdded

Large File Pointer Details
- SHA256: 08503679a20063b8b8b9d46bd17ad88b4908daaea345ca850a26659a8c411917
- Pointer size: 131 Bytes
- Size of remote file: 836 kB
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/1233cefa7e4998f15a912330c606c2ac042d7f18125544feebe734b3bcd7b09d/tests.logAdded+63
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/12e91248337a3e8c23b01c88862e396073e58ac713dfe67c63933bfa1b338f2e/tests_final.logAdded+17
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/156ab94c6115890fb82fcbe8f77af4bd52909683775e9285bc289b3f3202eed3/peg_structural_zoom.pngAdded

Large File Pointer Details
- SHA256: 156ab94c6115890fb82fcbe8f77af4bd52909683775e9285bc289b3f3202eed3
- Pointer size: 132 Bytes
- Size of remote file: 2.07 MB
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/15f32b8c1eff70d55395c515b82c50ee9724aadb16b126b1a925d59cb5e75ef5/browser_render.logAdded+10
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/17d69c52d2d467b5d86030c37b0480b7a55696ca9fb5da217567ea416580ab23/implementation.patchAdded
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252/initialization.pyAdded+77
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866/test_geometry_evaluation.pyAdded+82
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3/run_tracking.pyAdded+254
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diffAdded+259
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb/benchmark_pca_streaming.pyAdded+146
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d/edge_evidence.pyAdded+81
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/34e0643471303d8f788f977f0bad7ae4829239c93e6c0af97ddbfe0ccc916b51/test_priority_fps_metric_control.pyAdded+154
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9/geometry.pyAdded+255
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a/run_rgbd.pyAdded+445
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692/normal_estimators.pyAdded+2
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b/grounding.pyAdded+90
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890/pca_optimized.pyAdded+2
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/406a4b17e370b21c3edef72a1fb3c920ec92d9d8f9c9ef7ef9e410959a84bce2/spatial_xz.pngAdded

Large File Pointer Details
- SHA256: 406a4b17e370b21c3edef72a1fb3c920ec92d9d8f9c9ef7ef9e410959a84bce2
- Pointer size: 131 Bytes
- Size of remote file: 478 kB
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/406d1d9ffbf439a5e39ed59c61b6c16203c325311c989f0c6bc39d8689a5a38c/verification.jsonAdded+212
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b/run_pca_optimization.pyAdded+206
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed/sampling.pyAdded+266
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942/test_rgbd_evaluation.pyAdded+160
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/59431ef2427510990adc4e994238de3552a0ff723905c6795b5cd9bae8a778a9/priority_fps_metric_control.npzAdded+3
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a/test_priority_fps_trace.pyAdded+64
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4/test_normal_diagnostics.pyAdded+111
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa/run_normal_diagnostics.pyAdded+475
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692/pca_triton.pyAdded+173
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645/test_priority_fps_seed_control.pyAdded+244
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482/pca_torch.pyAdded+150
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/6c5e2373431ec7c7e390a7f77baa963ab2d649c2361b28c0f1553a542e20ac34/run_priority_fps_metric_control.pyAdded+833
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/6e6b1cb6a837013c19f75919e0bbb9490607e5eb244a85e1e1d3b68a060807b8/priority_fps_metric_control.htmlAdded+36
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/72c564d7cbb3d927d7cc1eec058c4c8c3dac68163212839364e52ba70b77037e/browser_verification.jsonAdded+47
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45/experiment_logger.pyAdded+237
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517/pca.pyAdded+258
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/81df499127fcdcddff89fefdccaa0a86f3b126c4c826b527d0ba1d41784659dc/browser_image_check.htmlAdded+43
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3/run_rim_bottleneck.pyAdded+342
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60/test_sampling.pyAdded+206
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d/run_grounding.pyAdded+223
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/88fed1fc274039a5f6506d928639a1ba4038702c784e3e6d714b13f86b7b309f/coverage_surface_tradeoff.pngAdded

Large File Pointer Details
- SHA256: 88fed1fc274039a5f6506d928639a1ba4038702c784e3e6d714b13f86b7b309f
- Pointer size: 131 Bytes
- Size of remote file: 167 kB
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0/test_initialization.pyAdded+38
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd/test_sampling_evaluation.pyAdded+247
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/91f3709ef38aae7fd17c70a862ad58e397fc438b89933cb1bc8371becce007e9/box_line_node_spacing.pngAdded

Large File Pointer Details
- SHA256: 91f3709ef38aae7fd17c70a862ad58e397fc438b89933cb1bc8371becce007e9
- Pointer size: 131 Bytes
- Size of remote file: 129 kB
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565/test_priority_fps_metric_control.pyAdded+163
visual/7f657cf88baf4f1f89e594252e243e1c/artifacts/reports/a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1/test_pca_optimized.pyAdded+148