Publish experiment 92f29716e76f4b998fe924f08e80357d (rollouts)
Browse filesFiles changed (29)
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/config/d75156eeebf36319b7ac3dead743f759f0b4240e2bf2fa37a6b010e62099b824/config.yamlAdded+124
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/1cf28febe8f33b4f62654dd50886c3196dfdb34920a46ef25c1836089debe1c8/voxel_structural_sampling.jsonAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/ae4815498798f8b910b5c66375231bb8ba39b021acf95805ddb82d426d603dce/metrics.jsonAdded+102
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06606a548e8ee7cd492b4fc07d578135516b2c89a6396ed4833175fa500d0b15/voxel_structural_sampling.htmlAdded+52
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06bb251620fc682e8f916d24eb06f38e4b82cd3cb9f0caa3f59f3bcb5b421caf/selection_before_gt.jsonAdded+313
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e/report-29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e.zipAdded+3
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diffAdded+259
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/38e82d8bed4891a13ab38a98e9d1192a0a147a80eaa00c6627e778c36ec43b8a/03i_voxel_structural_sampling.mdAdded+168
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4220b00d3b0e384039f365d9aab2c26711f17f873fed8fb76b8fc9a5832995fe/implementation.patchAdded+1074
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4ad29586893b1e4621423ef0e284da0ed5c30d46a34d6601fd2f014ebe595da0/git_start.jsonAdded+4
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/5c65ce227b78f697e97e1c8251ac8ed79c5754df3513bcf67e167dc8d8f4fe64/synthetic.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/615e7b4d53d04455bc80bcbc86275ca7c5262f84a41100e2bd3ac68e93d4b3f2/primary_distances.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/6a8d4489a3e71e5405c1d4a7a2f63f1d052d2480b0376d730c925a48b77cb7d7/resolution_budget.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/7282fefc9a1e253d6888bff797ed059d348946ac5c31b87e492ecdab778fcea9/report_refinement.patchAdded+95
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/79d9f4d7ff3eaa50772a08d7baaac1a5506853c823febd73846297fe8351d477/peg_gt.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620/test_voxel_structural_sampling.pyAdded+214
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88de6d8684943b17e29f1fbf7abe3ad2e44531fe153f69c73e5245b0b1dd419d/voxel_structural_sampling.npzAdded+3
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9868720e0b2cb973a7d70ee51777da533a27d2aa3b62cd1b6815f75a6650245c/box_gt.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/990c0de604aa9594cbe36b1987b7e55b44386b8814a34a3c83b7e9f954bee913/run_voxel_structural_sampling.pyAdded+907
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426/selection_before_gt.npzAdded+3
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/adadc5ff7b636910f0149a2f7346f182a95f2eadb8dd4eb61085952dbd3bd488/depth_roi_surface.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b341724f3bff4db8f719eab6451b83d72c7155e6a172a5fe403f534884cdb42d/verification.jsonAdded+95
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b5c251c7ad9d7cbc9d7c49cae3ffa0faa3505e5de918e705b2d2fb80bb36ae99/preregistered_config.jsonAdded+124
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ca95318cabf4f2551a3a31ee4d2b4aa278f0668bd375658d252ddbd916b4644d/primary_selection.pngAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ccf39663ec5c351432aa136e6eb32414a52288eb917787238e1a81981683acab/source_hashes.jsonAdded
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/cf6b9dcb33fc2d08f3a82b4d69326d456ab8035228542f6aea3ad688333aa94a/git_end.jsonAdded+9
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ded04031d9104676536b76c89e15214251faa884c44b3fcb95f21c978f76ae63/tests.logAdded+93
- visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967/protected_baseline.jsonAdded
- visual/92f29716e76f4b998fe924f08e80357d/manifests/72cb909c95433269381af39bb41161808a3797cef92988886b35d18fd038a7fd/manifest.jsonAdded+210
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124{ "baseline_FPS_executed": false, "baseline_run_id": "7f657cf88baf4f1f89e594252e243e1c", "device": "cpu", "fixture_run_id": "1f7ad262dd2e4b2fb0ac805a4eda5278", "gpu_executed": false, "numpy": "2.4.6", "platform": "macOS-27.0.1-arm64-arm-64bit", "production_policy_adopted": false, "protected_baseline_sha256": "ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967", "python": "3.11.13", "rules": { "anchor": "original whole-C seeded anchor cell representative", "camera": "base_camera", "cap": "existing Euclidean 3D fps_indices", "dyadic": "count-only; floor_divide nominal keys by 2; first count<=32; never used for selection", "episode": "ep000", "final_targets": { "box": 127, "peg": 129 }, "frame": 0, "grid": "CV camera metres; origin 0; float64 floor(xyz/a); int64; half-open", "gt": "only after all real/synthetic selections saved, read back and hashed; same-pair <=2px AND <=3mm", "interpretation": "first feasibility of voxel precompression + 3D FPS cap; anchor also changes", "method": "S3 optimized PCA5", "multiplier": 1.0, "order": "C/R source ascending; mapped anchor first in P; rest FPS or source ascending", "orientation": "strict >20 degrees, stored C only", "priority_cap_per_object": 32, "representative": "float64 centroid nearest original C; exact squared-distance tie smallest source", "scale": "median Z of original X; epsilon=z*sqrt((2/fx)^2+(2/fy)^2); a=epsilon/sqrt(3)", "score": "none; no optimized dense C score available", "seed": 0, "structural_ratio": 0.25, "surface": "existing whole-X 3D FPS initial=P; unused Priority becomes Surface; no padding", "synthetic_names": [ "line_uniform", "line_dense", "separated_clean", "separated_noise", "camera_near", "camera_far", "camera_occluded" ], "synthetic_scale": "stored C median Z; stored focal=1600px", "synthetic_uncertainty_calibration": "N/A: no actual PCA5 estimator/localization evidence", "total_cap": 256, "uv_bins": [ 4, 4 ], "xyz_bins": [ 2, 2, 2 ] }, "simulator_executed": false, "source_run_id": "2551448b0fae4c6bbce3caf48774275f", "source_sha256": { "docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md": "5a1a63de2865ff3292bd03d00d3ff74842219f452c2b747e70b4b9b0a766e579", "utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "visual/runtime/test/run_candidate_count_matched.py": "df2b3ea2a6b80262e016a13bc02256965a4524cb18647dadac85018450393738", "visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "visual/runtime/test/run_geometry_aware_sampling.py": "6fcfd638a929e793ba920297942f2b85eb6b00b066058dd0133d32a358648276", "visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "visual/runtime/test/run_local_structural_sampling.py": "4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "visual/runtime/test/run_priority_fps_metric_control.py": "c01afcd516f3cf2b1f1d34d5878be2376e849e50dc7c1b809854d8f5231d1ca9", "visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "visual/runtime/test/run_voxel_structural_sampling.py": "e4c7105e5150911a947b857efc81f8f9fa23c7bf5f5f794998425142b2e1ba95", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "visual/runtime/test/test_candidate_count_matched.py": "17f5a36e36d53cceefb9860e1e4953c5d6c668701000386417ed15cd46fa913d", "visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f", "visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "visual/runtime/test/test_local_structural_sampling.py": "d6758da4be04c7622a40ed9226503e6d2884de89f08992fc731200c8d21d7994", "visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "visual/runtime/test/test_priority_fps_metric_control.py": "92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565", "visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "visual/runtime/test/test_voxel_structural_sampling.py": "88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620", "visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522" }, "task": "03-I"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102[ { "metrics": { "eval/box/compression/C_to_P_m/count": 599, "eval/box/compression/C_to_P_m/max": 32.71140308900391, "eval/box/compression/C_to_P_m/mean": 12.814144598289596, "eval/box/compression/C_to_P_m/missing_count": 0, "eval/box/compression/C_to_P_m/p50": 12.587070666068819, "eval/box/compression/C_to_P_m/p95": 26.863878584728504, "eval/box/compression/C_to_P_m/worst/distance_mm": 32.71140308900391, "eval/box/compression/C_to_P_m/worst/source": 108283, "eval/box/compression/C_to_R_m/count": 599, "eval/box/compression/C_to_R_m/max": 2.8783562869176387, "eval/box/compression/C_to_R_m/mean": 0.7018747511363954, "eval/box/compression/C_to_R_m/missing_count": 0, "eval/box/compression/C_to_R_m/p50": 0.0, "eval/box/compression/C_to_R_m/p95": 2.049209003518097, "eval/box/compression/C_to_R_m/worst/distance_mm": 2.8783562869176387, "eval/box/compression/C_to_R_m/worst/source": 120067, "eval/box/compression/a_used_m": 0.0031639241993862634, "eval/box/compression/above_epsilon_count": 473, "eval/box/compression/above_epsilon_fraction": 0.7896494156928213, "eval/box/compression/budget_extra_m/count": 599, "eval/box/compression/budget_extra_m/max": 32.71140308900391, "eval/box/compression/budget_extra_m/mean": 12.1122698471532, "eval/box/compression/budget_extra_m/missing_count": 0, "eval/box/compression/budget_extra_m/p50": 12.146024575883438, "eval/box/compression/budget_extra_m/p95": 26.41490960795531, "eval/box/compression/budget_extra_m/worst/distance_mm": 32.71140308900391, "eval/box/compression/budget_extra_m/worst/source": 108283, "eval/box/compression/candidate_count": 599, "eval/box/compression/discarded_occupied": 324, "eval/box/compression/nominal_occupied": 356, "eval/box/compression/occupied_over_32": 11.125, "eval/box/compression/priority_count": 32, "eval/box/compression/same_cell_m/count": 599, "eval/box/compression/same_cell_m/max": 2.8811001472630364, "eval/box/compression/same_cell_m/mean": 0.722129376689149, "eval/box/compression/same_cell_m/missing_count": 0, "eval/box/compression/same_cell_m/p50": 0.0, "eval/box/compression/same_cell_m/p95": 2.12752405755311, "eval/box/compression/same_cell_m/worst/distance_mm": 2.8811001472630364, "eval/box/compression/same_cell_m/worst/source": 120063, "eval/box/compression/selected_occupied": 32, "eval/box/compression/used_over_nominal": 1.0, "eval/box/surface/count": 11665, "eval/box/surface/max": 22.892585827751066, "eval/box/surface/mean": 11.270701889519758, "eval/box/surface/p50": 11.520784258301264, "eval/box/surface/p95": 18.69012975965717, "eval/peg/compression/C_to_P_m/count": 703, "eval/peg/compression/C_to_P_m/max": 6.637877405135524, "eval/peg/compression/C_to_P_m/mean": 2.8315011554915697, "eval/peg/compression/C_to_P_m/missing_count": 0, "eval/peg/compression/C_to_P_m/p50": 2.6333368258780387, "eval/peg/compression/C_to_P_m/p95": 5.683059008267792, "eval/peg/compression/C_to_P_m/worst/distance_mm": 6.637877405135524, "eval/peg/compression/C_to_P_m/worst/source": 191736, "eval/peg/compression/C_to_R_m/count": 703, "eval/peg/compression/C_to_R_m/max": 1.5352157222089429, "eval/peg/compression/C_to_R_m/mean": 0.295094613865753, "eval/peg/compression/C_to_R_m/missing_count": 0, "eval/peg/compression/C_to_R_m/p50": 0.0, "eval/peg/compression/C_to_R_m/p95": 0.9528303630411619, "eval/peg/compression/C_to_R_m/worst/distance_mm": 1.5352157222089429, "eval/peg/compression/C_to_R_m/worst/source": 167702, "eval/peg/compression/a_used_m": 0.0013140491864514026, "eval/peg/compression/above_epsilon_count": 416, "eval/peg/compression/above_epsilon_fraction": 0.5917496443812233, "eval/peg/compression/budget_extra_m/count": 703, "eval/peg/compression/budget_extra_m/max": 6.637877405135524, "eval/peg/compression/budget_extra_m/mean": 2.536406541625817, "eval/peg/compression/budget_extra_m/missing_count": 0, "eval/peg/compression/budget_extra_m/p50": 2.3578000922331404, "eval/peg/compression/budget_extra_m/p95": 5.534030541744475, "eval/peg/compression/budget_extra_m/worst/distance_mm": 6.637877405135524, "eval/peg/compression/budget_extra_m/worst/source": 191736, "eval/peg/compression/candidate_count": 703, "eval/peg/compression/discarded_occupied": 400, "eval/peg/compression/nominal_occupied": 432, "eval/peg/compression/occupied_over_32": 13.5, "eval/peg/compression/priority_count": 32, "eval/peg/compression/same_cell_m/count": 703, "eval/peg/compression/same_cell_m/max": 1.6562190831798083, "eval/peg/compression/same_cell_m/mean": 0.3085708068980958, "eval/peg/compression/same_cell_m/missing_count": 0, "eval/peg/compression/same_cell_m/p50": 0.0, "eval/peg/compression/same_cell_m/p95": 1.023371244743913, "eval/peg/compression/same_cell_m/worst/distance_mm": 1.6562190831798083, "eval/peg/compression/same_cell_m/worst/source": 207536, "eval/peg/compression/selected_occupied": 32, "eval/peg/compression/used_over_nominal": 1.0, "eval/peg/surface/count": 11780, "eval/peg/surface/max": 11.134074254647135, "eval/peg/surface/mean": 5.182570301426918, "eval/peg/surface/p50": 5.334853124793147, "eval/peg/surface/p95": 8.52546570882631 }, "run_id": "92f29716e76f4b998fe924f08e80357d", "step": 0 }]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152<!doctype html><html lang="ko"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Task03-I — Voxel precompression + FPS cap</title><style>body{font:16px/1.65 system-ui,sans-serif;background:#f4f6f9;color:#17212e;margin:auto;max-width:1450px;padding:30px}h1,h2{line-height:1.25}h2{margin-top:2.5em;border-bottom:2px solid #cbd5e1;padding-bottom:12px}p{max-width:1150px}table{border-collapse:collapse;width:100%;font-size:14px;background:white}td,th{border:1px solid #cbd5e1;padding:9px;text-align:left}th{background:#e2e8f0}tr:nth-child(even){background:#f8fafc}.scroll{overflow:auto}img{width:100%;height:auto;background:white;border:1px solid #cbd5e1}figure{margin:25px 0}figcaption{color:#475569}a{color:#155eab}nav{padding:18px;background:#e0f2fe}code,pre{overflow:auto}</style><h1>Task03-I — Shape-First Voxel Precompression + 3D FPS Cap</h1><nav>Run 92f29716e76f4b998fe924f08e80357d<br><a href="../../docs/visual-graph-integration/03i_voxel_structural_sampling.md">결과 Markdown</a> · <a href="../../docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md">승인 계획</a><br><a href="voxel_structural_sampling.json">voxel_structural_sampling.json</a> · <a href="voxel_structural_sampling.npz">voxel_structural_sampling.npz</a> · <a href="selection_before_gt.npz">selection_before_gt.npz</a> · <a href="selection_before_gt.json">selection_before_gt.json</a> · <a href="verification.json">verification.json</a> · <a href="tests.log">tests.log</a> · <a href="source_hashes.json">source_hashes.json</a> · <a href="preregistered_config.json">preregistered_config.json</a> · <a href="implementation.patch">implementation.patch</a> · <a href="git_start.diff">git_start.diff</a></nav><h2>두 연구 질문에 대한 판단</h2><p>peg: C=703 → nominal R=432 → P=32. Nominal occupied/cap=13.500배이며 400개 cell이 cap에서 제거됐다. C→P p95는 voxel 5.6831mm, 저장 Global λ=1 5.6654mm, λ=0 6.6621mm다. GT unique refs C/R/P/F=462/462/142/142다.</p><p>box: C=599 → nominal R=356 → P=32. Nominal occupied/cap=11.125배이며 324개 cell이 cap에서 제거됐다. C→P p95는 voxel 26.8639mm, 저장 Global λ=1 27.4828mm, λ=0 29.7788mm다. GT unique refs C/R/P/F=91/82/6/6다.</p><p>이번 결과는 Voxel precompression + 3D FPS cap의 첫 feasibility 평가다. 순수 Voxel Sampling이나 일반적으로 유효한 Shape-First Sampling의 검증이 아니다. Nominal R 전체는 cap 없는 해상도 진단 집합이므로 32점 기준선과 동등 budget 성능으로 비교하지 않는다. 32점 cap 뒤의 거리·local coverage와 Surface/GT trade-off를 함께 해석한다.</p><p>A — 전반적 우월성을 지지하지 않는다. Peg는 λ=0보다 C→P tail이 개선됐지만 λ=1보다 p95/max가 소폭 악화했고, Final seam은 151/160(λ=1/0)에서 142로 줄었다. Box는 p95가 두 기준선보다 작지만 mean은 두 기준선보다 크고, Final rim은 3(λ=1)보다 많은 6이지만 12(λ=0)보다 적다. Surface p95는 개선됐으나 λ=1 대비 Surface mean은 두 물체 모두 소폭 악화했다. Box 한 지표의 개선만으로 형상 보존에 유리하다고 채택하지 않는다.</p><p>B — nominal 해상도와 32점은 양립하지 않았다. Peg/Box의 R은 432/356개로 cap의 13.5/11.125배다. C→R의 GT 손실은 0/9 reference였고 R→P에서 320/76개가 추가로 소실됐다. 따라서 이 고정 경로에서는 cap 단계의 손실이 압축 단계보다 훨씬 컸다. 다만 cap 수 자체의 효과와 그 32개를 고른 FPS 정책의 효과를 분리한 budget sweep은 하지 않았다.</p><p>N_occupied>32인 물체는 원래 해상도의 모든 voxel을 최종 보존하지 못했다. R 단계의 작은 오차와 R→P 추가 손실은 이 관측에서 예산 충돌의 크기를 보여주지만, 32점이 유일한 인과적 병목이거나 더 큰 budget이 일반적인 최적값임을 증명하지 않는다. 후보 오염, FPS 거리 경쟁과 anchor 이동이 남아 있다. 결과에 따른 재선택·파라미터 변경은 하지 않았다.</p><h2>고정 조건·scale·실제 PCA5 지원 범위</h2><p>ep000 Frame 0 / base_camera / S3 optimized PCA5 / orientation-only >20° / seed0. Final Peg129/Box127, 총256; Priority 상한 각32/총64, structural_ratio=.25는 현재 조건이다. 전체 원본 X의 camera Z median, 저장 fx=fy=256px, multiplier=1로 epsilon=z_ref*sqrt((2/fx)^2+(2/fy)^2), a=epsilon/sqrt(3)를 정했다.</p><p>PCA5 normal은 중심 ±2px 5×5 내부의 same-object 4-connected support를 사용한다. Depth jump >.01+.02*min(z1,z2)에서 연결을 끊고, 최소6점·rank2·unique smallest eigenvector를 요구한다. 불완전 patch를 허용하며 부족한 normal은 invalid다. Pair는 인접 normal을 비교해 >20°일 때 양 끝을 후보로 표시한다. 두 normal support 합집합은 6×5 또는 5×6, 한 endpoint의 모든 비교 footprint는 7×7 bbox의 네 모서리를 제외한다. 단순 5×5 window와 전체 반응 띠를 혼동하지 않는다.</p><p>Spatial support, 실제 edge localization error, voxel approximation error는 서로 다르다. Nominal epsilon은 동일 depth 평면의 half-window 근사에서 정한 compression scale이며 edge 오차의 추정값·상한이 아니다. 경사·깊이 불연속에서는 근사가 깨진다. Same-cell 후보→대표점 bound sqrt(3)*a는 R 단계에서만 보장된다. Cell을 버린 P와 2px AND 3mm matcher 통과에는 보장되지 않는다. 새 normal/score/GT calibration은 없다.</p><div class="scroll"><table><thead><tr><th>object</th><th>X median m</th><th>epsilon mm</th><th>a nominal=used mm</th><th>R occupied</th><th>R/32</th><th>P cells</th><th>removed</th><th>P>epsilon count/fraction</th><th>dyadic a mm / ratio / cells</th></tr></thead><tbody><tr><td>peg</td><td>0.2060</td><td>2.2760</td><td>1.3140</td><td>432</td><td>13.5000</td><td>32</td><td>400</td><td>416/703 (59.17%)</td><td>21.0248 / 16x / 22</td></tr><tr><td>box</td><td>0.4960</td><td>5.4801</td><td>3.1639</td><td>356</td><td>11.1250</td><td>32</td><td>324</td><td>473/599 (78.96%)</td><td>101.2456 / 32x / 24</td></tr></tbody></table></div><p>실제 used/nominal ratio는 1이다. Dyadic은 nominal integer key를 음수에도 floor_divide(2)하여 만든 nested count-only 진단이다. 최초 occupied≤32에서 멈췄고 그 크기를 선택에 사용하지 않았다. 임의 크기 grid의 단조성이나 정확히32 cell 존재를 가정하지 않았다. 이 dyadic family의 첫 크기를 전역 최소·물리적 최적 해상도로 읽지 않는다.</p><figure><a href="resolution_budget.png"><img src="resolution_budget.png" alt="Nominal 해상도와 현재 Priority 상한; coarse 진단은 선택에 미사용"></a><figcaption>Nominal 해상도와 현재 Priority 상한; coarse 진단은 선택에 미사용</figcaption></figure><h2>선택 규칙·anchor 이동·원본 provenance</h2><p>Camera origin=(0,0,0), 원본 CV XYZ(m)의 float64 floor(XYZ/a) int64 key, half-open cell을 사용했다. BBox 최소점으로 이동하지 않았다. Cell centroid에 가장 가까운 원본 C 하나, exact squared-distance tie는 최소 source다. R은 source ascending, original anchor cell의 대표점을 initial로 기존 Euclidean 3D FPS cap32를 수행했다. R≤32면 전부 사용하고 남는 예산은 전체 X의 기존 3D Surface FPS로 넘긴다. Padding·복제·좌표 평균 node는 없다.</p><div class="scroll"><table><thead><tr><th>object</th><th>original anchor</th><th>mapped R source</th><th>3D shift mm</th><th>delta(u,v) px</th><th>pixel shift px</th></tr></thead><tbody><tr><td>peg</td><td>214225</td><td>214225</td><td>0.0000</td><td>[0, 0]</td><td>0.0000</td></tr><tr><td>box</td><td>96553</td><td>96552</td><td>1.1953</td><td>[-1, 0]</td><td>1.0000</td></tr></tbody></table></div><p>Anchor source가 바뀌면 grouping/precompression과 FPS 시작점 효과가 함께 달라진다. 추가 anchor-only arm은 실행하지 않았으므로 두 효과를 인과적으로 분해하지 않는다. C 전체 optimized score가 저장돼 있지 않아 score-free만 사용했다. Task02 reference PCA5 angle을 optimized score로 대체하지 않았다.</p><figure><a href="primary_selection.png"><img src="primary_selection.png" alt="PCA5 원본 C / nominal 대표점 R / 실제 Priority P와 Surface S=Final F"></a><figcaption>PCA5 원본 C / nominal 대표점 R / 실제 Priority P와 Surface S=Final F</figcaption></figure><h2>Primary: 압축 오차와 budget 추가 손실</h2><div class="scroll"><table><thead><tr><th>object</th><th>distance (mm)</th><th>mean</th><th>p50</th><th>p95</th><th>max</th><th>worst source</th></tr></thead><tbody><tr><td>peg</td><td>same_cell_m</td><td>0.3086</td><td>0.0000</td><td>1.0234</td><td>1.6562</td><td>207536</td></tr><tr><td>peg</td><td>C_to_R_m</td><td>0.2951</td><td>0.0000</td><td>0.9528</td><td>1.5352</td><td>167702</td></tr><tr><td>peg</td><td>C_to_P_m</td><td>2.8315</td><td>2.6333</td><td>5.6831</td><td>6.6379</td><td>191736</td></tr><tr><td>peg</td><td>budget_extra_m</td><td>2.5364</td><td>2.3578</td><td>5.5340</td><td>6.6379</td><td>191736</td></tr><tr><td>box</td><td>same_cell_m</td><td>0.7221</td><td>0.0000</td><td>2.1275</td><td>2.8811</td><td>120063</td></tr><tr><td>box</td><td>C_to_R_m</td><td>0.7019</td><td>0.0000</td><td>2.0492</td><td>2.8784</td><td>120067</td></tr><tr><td>box</td><td>C_to_P_m</td><td>12.8141</td><td>12.5871</td><td>26.8639</td><td>32.7114</td><td>108283</td></tr><tr><td>box</td><td>budget_extra_m</td><td>12.1123</td><td>12.1460</td><td>26.4149</td><td>32.7114</td><td>108283</td></tr></tbody></table></div><p>same_cell은 자기 cell의 대표점 거리, C→R은 모든 대표점 중 최근접 거리다. Budget extra=C→P−C→R≥0이며 same_cell을 빼지 않았다. 네 raw 배열, ECDF와 worst source/XYZ/pixel을 NPZ/JSON에 저장했다. Same-cell bound 확인과 성능 개선은 별개다.</p><div class="scroll"><table><thead><tr><th>object</th><th>method</th><th>P</th><th>C→P mean/p50/p95/max mm</th><th>X→F mean/p95/max mm</th><th>Final unique GT refs</th></tr></thead><tbody><tr><td>peg</td><td>global1</td><td>32</td><td>2.8481 / 2.6659 / 5.6654 / 6.6187</td><td>5.1700 / 8.5499 / 11.0471</td><td>151</td></tr><tr><td>peg</td><td>global0</td><td>32</td><td>2.9452 / 2.4687 / 6.6621 / 8.1979</td><td>5.2837 / 8.6095 / 10.8408</td><td>160</td></tr><tr><td>peg</td><td>voxel</td><td>32</td><td>2.8315 / 2.6333 / 5.6831 / 6.6379</td><td>5.1826 / 8.5255 / 11.1341</td><td>142</td></tr><tr><td>box</td><td>global1</td><td>32</td><td>12.7793 / 12.5895 / 27.4828 / 32.7114</td><td>11.2533 / 18.7511 / 22.8926</td><td>3</td></tr><tr><td>box</td><td>global0</td><td>32</td><td>10.8746 / 8.8430 / 29.7788 / 46.0516</td><td>11.5801 / 19.0768 / 23.1584</td><td>12</td></tr><tr><td>box</td><td>voxel</td><td>32</td><td>12.8141 / 12.5871 / 26.8639 / 32.7114</td><td>11.2707 / 18.6901 / 22.8926</td><td>6</td></tr></tbody></table></div><div class="scroll"><table><thead><tr><th>object</th><th>method</th><th>UV selected/occupied; P=0 IDs</th><th>XYZ selected/occupied; P=0 IDs</th><th>UV equal-region mean p95 mm</th></tr></thead><tbody><tr><td>peg</td><td>global1</td><td>8/8; []</td><td>3/4; [6]</td><td>5.2254</td></tr><tr><td>peg</td><td>global0</td><td>8/8; []</td><td>3/4; [6]</td><td>5.6162</td></tr><tr><td>peg</td><td>voxel</td><td>8/8; []</td><td>3/4; [6]</td><td>4.9291</td></tr><tr><td>box</td><td>global1</td><td>9/9; []</td><td>1/1; []</td><td>24.6447</td></tr><tr><td>box</td><td>global0</td><td>9/9; []</td><td>1/1; []</td><td>22.5887</td></tr><tr><td>box</td><td>voxel</td><td>9/9; []</td><td>1/1; []</td><td>24.4979</td></tr></tbody></table></div><p>독립 UV4×4/XYZ 최대2×2×2 구역은 같은 X bbox로 고정했다. 구역별 후보 밀도·선택률·거리 tail과 R 단계 구역 통계는 JSON/NPZ에 있다. Box의 30.726m outlier는 그대로 남아 coarse XYZ 구역과 bbox 정규화를 왜곡하므로 raw mm와 UV를 함께 본다. 단순 구역 점유가 같아도 국소 geometry가 같다는 뜻은 아니다.</p><figure><a href="primary_distances.png"><img src="primary_distances.png" alt="Same-cell / C→R / C→P / budget extra ECDF와 저장 FPS 비교"></a><figcaption>Same-cell / C→R / C→P / budget extra ECDF와 저장 FPS 비교</figcaption></figure><h2>Secondary: 선택 후 GT, C/R/P/S/F reference 손실</h2><p>Same-pair ≤2px AND ≤3mm를 유지했다. Peg observed462/visible464, Box observed103/visible103이다. 한 node는 여러 reference를 덮고 한 reference는 여러 node에 매칭될 수 있다. Pair count·matching node·unique reference는 서로 다르다.</p><div class="scroll"><table><thead><tr><th>object</th><th>voxel stage</th><th>nodes</th><th>matching nodes</th><th>unique refs</th><th>available/unavailable feature rows</th></tr></thead><tbody><tr><td>peg</td><td>C</td><td>703</td><td>692</td><td>462</td><td>32/671</td></tr><tr><td>peg</td><td>P</td><td>32</td><td>30</td><td>142</td><td>20/12</td></tr><tr><td>peg</td><td>S</td><td>97</td><td>0</td><td>0</td><td>49/48</td></tr><tr><td>peg</td><td>F</td><td>129</td><td>30</td><td>142</td><td>69/60</td></tr><tr><td>peg</td><td>R</td><td>432</td><td>426</td><td>462</td><td>21/411</td></tr><tr><td>box</td><td>C</td><td>599</td><td>127</td><td>91</td><td>35/564</td></tr><tr><td>box</td><td>P</td><td>32</td><td>2</td><td>6</td><td>28/4</td></tr><tr><td>box</td><td>S</td><td>95</td><td>0</td><td>0</td><td>80/15</td></tr><tr><td>box</td><td>F</td><td>127</td><td>2</td><td>6</td><td>108/19</td></tr><tr><td>box</td><td>R</td><td>356</td><td>70</td><td>82</td><td>31/325</td></tr></tbody></table></div><div class="scroll"><table><thead><tr><th>object</th><th>C→R lost refs</th><th>R→P additional lost refs</th><th>Surface added refs</th><th>P/S overlapping refs</th></tr></thead><tbody><tr><td>peg</td><td>0</td><td>320</td><td>0</td><td>0</td></tr><tr><td>box</td><td>9</td><td>76</td><td>0</td><td>0</td></tr></tbody></table></div><div class="scroll"><table><thead><tr><th>Box segment</th><th>reference count</th><th>C</th><th>R</th><th>P</th><th>S</th><th>F</th><th>Global λ1 P/F</th><th>Global λ0 P/F</th></tr></thead><tbody><tr><td>rim_axis1_+1</td><td>25</td><td>24</td><td>21</td><td>3</td><td>0</td><td>3</td><td>3 / 3</td><td>6 / 6</td></tr><tr><td>rim_axis1_-1</td><td>26</td><td>26</td><td>23</td><td>3</td><td>0</td><td>3</td><td>0 / 0</td><td>0 / 0</td></tr><tr><td>rim_axis2_+1</td><td>26</td><td>15</td><td>12</td><td>0</td><td>0</td><td>0</td><td>0 / 0</td><td>0 / 3</td></tr><tr><td>rim_axis2_-1</td><td>26</td><td>26</td><td>26</td><td>0</td><td>0</td><td>0</td><td>0 / 0</td><td>3 / 3</td></tr></tbody></table></div><p>각 단계 reference ID 집합·joint pairs·matching source·구간별 matching node/reference·Box line spacing을 저장했다. Surface 추가분은 refs(F)−refs(P)이며 S 전체 hit 수와 다르다. C→R과 R→P 손실은 P⊆R⊆C에서 구분했다. Peg 물리적 line 순서/간격은 N/A다. GT 후보→reference 거리에는 depth noise, reference 이산화, 가시성·matcher 정의가 섞여 순수 detector localization error가 아니다. 이를 epsilon calibration에 사용하지 않았다.</p><figure><a href="peg_gt.png"><img src="peg_gt.png" alt="Peg seam: C/R/P/S/F coverage와 압축/예산 손실"></a><figcaption>Peg seam: C/R/P/S/F coverage와 압축/예산 손실</figcaption></figure><figure><a href="box_gt.png"><img src="box_gt.png" alt="Box rim: C/R/P/S/F coverage와 압축/예산 손실"></a><figcaption>Box rim: C/R/P/S/F coverage와 압축/예산 손실</figcaption></figure><h2>Depth·ROI·일반 Surface trade-off</h2><div class="scroll"><table><thead><tr><th>object</th><th>stage</th><th>depth median/p95/max m</th><th>negative union count / nodes</th></tr></thead><tbody><tr><td>peg</td><td>X</td><td>0.2060 / 0.3271 / 0.3650</td><td>7800 / 11780</td></tr><tr><td>peg</td><td>C</td><td>0.1810 / 0.3160 / 0.3500</td><td>11 / 703</td></tr><tr><td>peg</td><td>R</td><td>0.1990 / 0.3280 / 0.3500</td><td>6 / 432</td></tr><tr><td>peg</td><td>P</td><td>0.1970 / 0.3329 / 0.3500</td><td>2 / 32</td></tr><tr><td>peg</td><td>S</td><td>0.2660 / 0.3506 / 0.3650</td><td>90 / 97</td></tr><tr><td>peg</td><td>F</td><td>0.2520 / 0.3492 / 0.3650</td><td>92 / 129</td></tr><tr><td>box</td><td>X</td><td>0.4960 / 0.5350 / 30.7260</td><td>10506 / 11665</td></tr><tr><td>box</td><td>C</td><td>0.4880 / 0.6665 / 1.4260</td><td>281 / 599</td></tr><tr><td>box</td><td>R</td><td>0.4905 / 0.6880 / 1.4260</td><td>150 / 356</td></tr><tr><td>box</td><td>P</td><td>0.5805 / 1.4057 / 1.4260</td><td>9 / 32</td></tr><tr><td>box</td><td>S</td><td>0.5220 / 8.4310 / 30.7260</td><td>70 / 95</td></tr><tr><td>box</td><td>F</td><td>0.5250 / 8.4310 / 30.7260</td><td>79 / 127</td></tr></tbody></table></div><p>원거리 positive depth를 제거하지 않았다. ROI는 중첩되므로 union을 별도 집계했다. ROI/far는 실제 noise 정답이 아니며 일반 Surface 점유를 자동 오선택으로 분류하지 않는다. X median/p95 기반 depth bands와 candidate별 P 선택률도 저장했다. Median은 단일 extreme max 영향은 줄이지만 mask 오염과 물체 내 depth 차이를 해결하지 않는다. Peg/Box는 같은 공식으로 서로 다른 metric a를 사용하며 동일 절대 해상도 비교가 아니다.</p><figure><a href="depth_roi_surface.png"><img src="depth_roi_surface.png" alt="원본 depth tail, 기존 negative union, 전체 X→F Surface 비교"></a><figcaption>원본 depth tail, 기존 negative union, 전체 X→F Surface 비교</figcaption></figure><h2>기존 7개 synthetic의 저장 입력 재사용</h2><div class="scroll"><table><thead><tr><th>fixture</th><th>C/R/P</th><th>a mm</th><th>dyadic ratio</th><th>Global/UV/Voxel C→P p95 mm</th><th>Global/UV/Voxel ref→P p95 mm</th><th>noise P G/UV/V</th></tr></thead><tbody><tr><td>line_uniform</td><td>128/128/32</td><td>0.8165</td><td>16</td><td>3.7500 / 5.6250 / 3.7500</td><td>3.7500 / 5.6250 / 3.7500</td><td>0 / 0 / 0</td></tr><tr><td>line_dense</td><td>216/169/32</td><td>0.8165</td><td>16</td><td>3.7500 / 7.5000 / 3.7500</td><td>3.7500 / 7.5000 / 3.7500</td><td>0 / 0 / 0</td></tr><tr><td>separated_clean</td><td>188/164/32</td><td>0.8165</td><td>16</td><td>3.7500 / 5.6250 / 3.7500</td><td>3.9844 / 6.0937 / 3.9844</td><td>0 / 0 / 0</td></tr><tr><td>separated_noise</td><td>196/172/32</td><td>0.8165</td><td>16</td><td>3.7500 / 5.6250 / 3.7500</td><td>4.2188 / 6.0938 / 4.2188</td><td>1 / 1 / 1</td></tr><tr><td>camera_near</td><td>188/164/32</td><td>0.8165</td><td>16</td><td>3.7500 / 5.6250 / 3.7500</td><td>3.9844 / 6.0937 / 3.9844</td><td>0 / 0 / 0</td></tr><tr><td>camera_far</td><td>154/120/32</td><td>1.6330</td><td>8</td><td>3.7500 / 6.2812 / 3.7500</td><td>3.8320 / 6.0938 / 4.1836</td><td>0 / 0 / 0</td></tr><tr><td>camera_occluded</td><td>60/36/32</td><td>0.8165</td><td>2</td><td>0.4688 / 0.4688 / 0.4688</td><td>0.5859 / 0.5859 / 0.5859</td><td>0 / 0 / 0</td></tr></tbody></table></div><p>Task03-F 저장 C/source/XYZ와 Global/UV 선택을 읽었으며 새 fixture·기준선 FPS를 만들지 않았다. Dense X가 없는 stress test에서 관측 C median과 기존 focal1600px로 같은 scale 공식을 적용했다. Annotation은 모든 선택 저장 후에만 noise/reference/구조별 평가에 사용했다. 실제 PCA5 5×5 localization uncertainty calibration과 Synthetic Surface는 N/A다. 계약/geometry stress test 통과가 uncertainty calibration 타당성을 뜻하지 않는다.</p><figure><a href="synthetic.png"><img src="synthetic.png" alt="기존 일곱 fixture의 저장 Global/UV와 단일 voxel precompression control"></a><figcaption>기존 일곱 fixture의 저장 Global/UV와 단일 voxel precompression control</figcaption></figure><h2>검증·재현·한계·완료 범위</h2><p>실행 UUID 92f29716e76f4b998fe924f08e80357d. 필수 계약 테스트: Ran 86 tests in 0.677s; OK. 성능 개선을 PASS 조건으로 두지 않았다. selection_before_gt.npz를 real/synthetic 선택 전체의 저장·readback·hash 이후에만 GT evaluator/annotation에 연결했다. 평가 후 선택 hash 불변, 원본 C/X·baseline exact alignment, 원본 feature available-only exact gather를 확인했다.</p><p>���존 ExperimentLogger(team=visual, job_type=evaluate), WANDB_MODE=disabled 및 로컬 artifact inventory를 재사용했다. 기존 UUID/project/group 규칙을 바꾸지 않았다. Git 시작 상태는 dirty이며 source snapshot·input/artifact hashes·시작 diff·implementation diff를 함께 보존했다. Production sampling/normal/tracking/shared simulator와 기존 dirty/untracked 파일은 변경하지 않았다. 같은 S3 조건에서 저장된 feature가 없는 source는 unavailable로 남겼으며 feature를 추정하지 않았다.</p><p>보호 대상 기존 파일 3,092개의 SHA-256와 HEAD 불변을 확인했다. Markdown↔HTML 및 JSON/NPZ/PNG 상대 링크, PNG 7개 decode는 PASS다. 실제 브라우저 로딩은 computer-use 권한이 없어 진행하지 못했고, 사용자의 후속 지시에 따라 생략했다. 이 미실행 항목을 검증 PASS로 계산하지 않는다. 수치 실행 source_snapshot과 선택·JSON/NPZ는 유지하고 최종 해석 문구/검증 상태를 보완한 보고 source는 report_source_snapshot과 report_generation_sources로 구분한다.</p><p>CPU NumPy/SciPy offline 실행이다. 단계별 wall time은 JSON에 기록했으며 Graph/GNN 20Hz 성능을 주장하지 않는다. Simulator/renderer/CUDA/MPS/GPU/PCL, 새 episode/fixture/score/normal, threshold/scale sweep, 두 번째 selection arm, GT calibration/quota, depth filtering, ratio/Adaptive Budget, Graph/GNN/BC, dependency 설치·외부 업로드·Git commit은 미실행이다. Task03-H의 동일 count 기대 coverage는 후보 해석 근거, Task03-F/G는 기존 실패 비교군으로만 유지했다. 보고서 제출 후 추가 알고리즘 실행 없이 중단한다.</p></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313{ "sha256": "9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426", "gt_connected": false, "actual": { "peg": { "scale": { "status": "defined", "z_ref_m": 0.20600000023841858, "fx_px": 256.0, "fy_px": 256.0, "epsilon_m": 0.002275999954578378, "a_m": 0.0013140491864514026, "multiplier": 1.0, "pair_footprint_m": 0.00290134204533286 }, "dyadic": { "status": "defined", "levels": [ { "level": 0, "occupied": 432, "a_m": 0.0013140491864514026, "ratio": 1, "bound_m": 0.002275999954578378 }, { "level": 1, "occupied": 206, "a_m": 0.002628098372902805, "ratio": 2, "bound_m": 0.004551999909156756 }, { "level": 2, "occupied": 99, "a_m": 0.00525619674580561, "ratio": 4, "bound_m": 0.009103999818313512 }, { "level": 3, "occupied": 49, "a_m": 0.01051239349161122, "ratio": 8, "bound_m": 0.018207999636627024 }, { "level": 4, "occupied": 22, "a_m": 0.02102478698322244, "ratio": 16, "bound_m": 0.03641599927325405 } ], "a_budget_m": 0.02102478698322244, "ratio": 16, "occupied": 22, "used_for_selection": false }, "anchor": { "original_source": 214225, "mapped_source": 214225, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 }, "counts": { "R": 432, "P": 32, "S": 97, "F": 129 } }, "box": { "scale": { "status": "defined", "z_ref_m": 0.4959999918937683, "fx_px": 256.0, "fy_px": 256.0, "epsilon_m": 0.005480077464633691, "a_m": 0.0031639241993862634, "multiplier": 1.0, "pair_footprint_m": 0.006985755482041815 }, "dyadic": { "status": "defined", "levels": [ { "level": 0, "occupied": 356, "a_m": 0.0031639241993862634, "ratio": 1, "bound_m": 0.005480077464633691 }, { "level": 1, "occupied": 226, "a_m": 0.006327848398772527, "ratio": 2, "bound_m": 0.010960154929267382 }, { "level": 2, "occupied": 125, "a_m": 0.012655696797545054, "ratio": 4, "bound_m": 0.021920309858534763 }, { "level": 3, "occupied": 74, "a_m": 0.025311393595090107, "ratio": 8, "bound_m": 0.043840619717069526 }, { "level": 4, "occupied": 42, "a_m": 0.050622787190180214, "ratio": 16, "bound_m": 0.08768123943413905 }, { "level": 5, "occupied": 24, "a_m": 0.10124557438036043, "ratio": 32, "bound_m": 0.1753624788682781 } ], "a_budget_m": 0.10124557438036043, "ratio": 32, "occupied": 24, "used_for_selection": false }, "anchor": { "original_source": 96553, "mapped_source": 96552, "distance_m": 0.0011953115463256836, "delta_pixel_uv": [ -1, 0 ], "pixel_distance_px": 1.0 }, "counts": { "R": 356, "P": 32, "S": 95, "F": 127 } } }, "synthetic": { "line_uniform": { "scale": { "status": "defined", "z_ref_m": 0.8, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0014142135623730952, "a_m": 0.0008164965809277262, "multiplier": 1.0, "pair_footprint_m": 0.0018027756377319946 }, "anchor": { "original_source": 524903, "mapped_source": 524903, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } }, "line_dense": { "scale": { "status": "defined", "z_ref_m": 0.8, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0014142135623730952, "a_m": 0.0008164965809277262, "multiplier": 1.0, "pair_footprint_m": 0.0018027756377319946 }, "anchor": { "original_source": 524809, "mapped_source": 524809, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } }, "separated_clean": { "scale": { "status": "defined", "z_ref_m": 0.8, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0014142135623730952, "a_m": 0.0008164965809277262, "multiplier": 1.0, "pair_footprint_m": 0.0018027756377319946 }, "anchor": { "original_source": 647599, "mapped_source": 647599, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } }, "separated_noise": { "scale": { "status": "defined", "z_ref_m": 0.8, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0014142135623730952, "a_m": 0.0008164965809277262, "multiplier": 1.0, "pair_footprint_m": 0.0018027756377319946 }, "anchor": { "original_source": 647588, "mapped_source": 647588, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } }, "camera_near": { "scale": { "status": "defined", "z_ref_m": 0.8, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0014142135623730952, "a_m": 0.0008164965809277262, "multiplier": 1.0, "pair_footprint_m": 0.0018027756377319946 }, "anchor": { "original_source": 647599, "mapped_source": 647599, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } }, "camera_far": { "scale": { "status": "defined", "z_ref_m": 1.6, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0028284271247461905, "a_m": 0.0016329931618554523, "multiplier": 1.0, "pair_footprint_m": 0.003605551275463989 }, "anchor": { "original_source": 586216, "mapped_source": 586216, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } }, "camera_occluded": { "scale": { "status": "defined", "z_ref_m": 0.8, "fx_px": 1600.0, "fy_px": 1600.0, "epsilon_m": 0.0014142135623730952, "a_m": 0.0008164965809277262, "multiplier": 1.0, "pair_footprint_m": 0.0018027756377319946 }, "anchor": { "original_source": 401752, "mapped_source": 401752, "distance_m": 0.0, "delta_pixel_uv": [ 0, 0 ], "pixel_distance_px": 0.0 } } }}123version https://git-lfs.github.com/spec/v1oid sha256:29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0esize 5164482123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259diff --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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168# Task03-I — Shape-First Voxel Precompression + 3D FPS Cap
[voxel_structural_sampling.html](../../experiments/92f29716e76f4b998fe924f08e80357d/voxel_structural_sampling.html) · [voxel_structural_sampling.json](../../experiments/92f29716e76f4b998fe924f08e80357d/voxel_structural_sampling.json) · [voxel_structural_sampling.npz](../../experiments/92f29716e76f4b998fe924f08e80357d/voxel_structural_sampling.npz) · [selection_before_gt.npz](../../experiments/92f29716e76f4b998fe924f08e80357d/selection_before_gt.npz) · [selection_before_gt.json](../../experiments/92f29716e76f4b998fe924f08e80357d/selection_before_gt.json) · [verification.json](../../visual/results/diagnostic_previews/03i/verification.json) · [tests.log](../../experiments/92f29716e76f4b998fe924f08e80357d/tests.log) · [source_hashes.json](../../experiments/92f29716e76f4b998fe924f08e80357d/source_hashes.json) · [preregistered_config.json](../../visual/results/diagnostic_previews/03i/preregistered_config.json) · [implementation.patch](../../experiments/92f29716e76f4b998fe924f08e80357d/implementation.patch) · [git_start.diff](../../experiments/92f29716e76f4b998fe924f08e80357d/git_start.diff)
[승인 계획](03i_voxel_structural_sampling_plan.md) · [Task03-H](03h_candidate_count_matched.md) · [Task03-F](03f_local_structural_sampling.md) · [Task03-G](03g_geometry_aware_sampling.md)
## 두 연구 질문에 대한 판단
peg: C=703 → nominal R=432 → P=32. Nominal occupied/cap=13.500배이며 400개 cell이 cap에서 제거됐다. C→P p95는 voxel 5.6831mm, 저장 Global λ=1 5.6654mm, λ=0 6.6621mm다. GT unique refs C/R/P/F=462/462/142/142다.
box: C=599 → nominal R=356 → P=32. Nominal occupied/cap=11.125배이며 324개 cell이 cap에서 제거됐다. C→P p95는 voxel 26.8639mm, 저장 Global λ=1 27.4828mm, λ=0 29.7788mm다. GT unique refs C/R/P/F=91/82/6/6다.
이번 결과는 Voxel precompression + 3D FPS cap의 첫 feasibility 평가다. 순수 Voxel Sampling이나 일반적으로 유효한 Shape-First Sampling의 검증이 아니다. Nominal R 전체는 cap 없는 해상도 진단 집합이므로 32점 기준선과 동등 budget 성능으로 비교하지 않는다. 32점 cap 뒤의 거리·local coverage와 Surface/GT trade-off를 함께 해석한다.
A — 전반적 우월성을 지지하지 않는다. Peg는 λ=0보다 C→P tail이 개선됐지만 λ=1보다 p95/max가 소폭 악화했고, Final seam은 151/160(λ=1/0)에서 142로 줄었다. Box는 p95가 두 기준선보다 작지만 mean은 두 기준선보다 크고, Final rim은 3(λ=1)보다 많은 6이지만 12(λ=0)보다 적다. Surface p95는 개선됐으나 λ=1 대비 Surface mean은 두 물체 모두 소폭 악화했다. Box 한 지표의 개선만으로 형상 보존에 유리하다고 채택하지 않는다.
B — nominal 해상도와 32점은 양립하지 않았다. Peg/Box의 R은 432/356개로 cap의 13.5/11.125배다. C→R의 GT 손실은 0/9 reference였고 R→P에서 320/76개가 추가로 소실됐다. 따라서 이 고정 경로에서는 cap 단계의 손실이 압축 단계보다 훨씬 컸다. 다만 cap 수 자체의 효과와 그 32개를 고른 FPS 정책의 효과를 분리한 budget sweep은 하지 않았다.
N_occupied>32인 물체는 원래 해상도의 모든 voxel을 최종 보존하지 못했다. R 단계의 작은 오차와 R→P 추가 손실은 이 관측에서 예산 충돌의 크기를 보여주지만, 32점이 유일한 인과적 병목이거나 더 큰 budget이 일반적인 최적값임을 증명하지 않는다. 후보 오염, FPS 거리 경쟁과 anchor 이동이 남아 있다. 결과에 따른 재선택·파라미터 변경은 하지 않았다.
## 고정 조건·scale·실제 PCA5 지원 범위
ep000 Frame 0 / base_camera / S3 optimized PCA5 / orientation-only >20° / seed0. Final Peg129/Box127, 총256; Priority 상한 각32/총64, structural_ratio=.25는 현재 조건이다. 전체 원본 X의 camera Z median, 저장 fx=fy=256px, multiplier=1로 epsilon=z_ref*sqrt((2/fx)^2+(2/fy)^2), a=epsilon/sqrt(3)를 정했다.
PCA5 normal은 중심 ±2px 5×5 내부의 same-object 4-connected support를 사용한다. Depth jump >.01+.02*min(z1,z2)에서 연결을 끊고, 최소6점·rank2·unique smallest eigenvector를 요구한다. 불완전 patch를 허용하며 부족한 normal은 invalid다. Pair는 인접 normal을 비교해 >20°일 때 양 끝을 후보로 표시한다. 두 normal support 합집합은 6×5 또는 5×6, 한 endpoint의 모든 비교 footprint는 7×7 bbox의 네 모서리를 제외한다. 단순 5×5 window와 전체 반응 띠를 혼동하지 않는다.
Spatial support, 실제 edge localization error, voxel approximation error는 서로 다르다. Nominal epsilon은 동일 depth 평면의 half-window 근사에서 정한 compression scale이며 edge 오차의 추정값·상한이 아니다. 경사·깊이 불연속에서는 근사가 깨진다. Same-cell 후보→대표점 bound sqrt(3)*a는 R 단계에서만 보장된다. Cell을 버린 P와 2px AND 3mm matcher 통과에�� 보장되지 않는다. 새 normal/score/GT calibration은 없다.
| object | X median m | epsilon mm | a nominal=used mm | R occupied | R/32 | P cells | removed | P>epsilon count/fraction | dyadic a mm / ratio / cells || --- | --- | --- | --- | --- | --- | --- | --- | --- | --- || peg | 0.2060 | 2.2760 | 1.3140 | 432 | 13.5000 | 32 | 400 | 416/703 (59.17%) | 21.0248 / 16x / 22 || box | 0.4960 | 5.4801 | 3.1639 | 356 | 11.1250 | 32 | 324 | 473/599 (78.96%) | 101.2456 / 32x / 24 |
실제 used/nominal ratio는 1이다. Dyadic은 nominal integer key를 음수에도 floor_divide(2)하여 만든 nested count-only 진단이다. 최초 occupied≤32에서 멈췄고 그 크기를 선택에 사용하지 않았다. 임의 크기 grid의 단조성이나 정확히32 cell 존재를 가정하지 않았다. 이 dyadic family의 첫 크기를 전역 최소·물리적 최적 해상도로 읽지 않는다.

## 선택 규칙·anchor 이동·원본 provenance
Camera origin=(0,0,0), 원본 CV XYZ(m)의 float64 floor(XYZ/a) int64 key, half-open cell을 사용했다. BBox 최소점으로 이동하지 않았다. Cell centroid에 가장 가까운 원본 C 하나, exact squared-distance tie는 최소 source다. R은 source ascending, original anchor cell의 대표점을 initial로 기존 Euclidean 3D FPS cap32를 수행했다. R≤32면 전부 사용하고 남는 예산은 전체 X의 기존 3D Surface FPS로 넘긴다. Padding·복제·좌표 평균 node는 없다.
| object | original anchor | mapped R source | 3D shift mm | delta(u,v) px | pixel shift px || --- | --- | --- | --- | --- | --- || peg | 214225 | 214225 | 0.0000 | [0, 0] | 0.0000 || box | 96553 | 96552 | 1.1953 | [-1, 0] | 1.0000 |
Anchor source가 바뀌면 grouping/precompression과 FPS 시작점 효과가 함께 달라진다. 추가 anchor-only arm은 실행하지 않았으므로 두 효과를 인과적으로 분해하지 않는다. C 전체 optimized score가 저장돼 있지 않아 score-free만 사용했다. Task02 reference PCA5 angle을 optimized score로 대체하지 않았다.

## Primary: 압축 오차와 budget 추가 손실
| object | distance (mm) | mean | p50 | p95 | max | worst source || --- | --- | --- | --- | --- | --- | --- || peg | same_cell_m | 0.3086 | 0.0000 | 1.0234 | 1.6562 | 207536 || peg | C_to_R_m | 0.2951 | 0.0000 | 0.9528 | 1.5352 | 167702 || peg | C_to_P_m | 2.8315 | 2.6333 | 5.6831 | 6.6379 | 191736 || peg | budget_extra_m | 2.5364 | 2.3578 | 5.5340 | 6.6379 | 191736 || box | same_cell_m | 0.7221 | 0.0000 | 2.1275 | 2.8811 | 120063 || box | C_to_R_m | 0.7019 | 0.0000 | 2.0492 | 2.8784 | 120067 || box | C_to_P_m | 12.8141 | 12.5871 | 26.8639 | 32.7114 | 108283 || box | budget_extra_m | 12.1123 | 12.1460 | 26.4149 | 32.7114 | 108283 |
same_cell은 자기 cell의 대표점 거리, C→R은 모든 대표점 중 최근접 거리다. Budget extra=C→P−C→R≥0이며 same_cell을 빼지 않았다. 네 raw 배열, ECDF와 worst source/XYZ/pixel을 NPZ/JSON에 저장했다. Same-cell bound 확인과 성능 개선은 별개다.
| object | method | P | C→P mean/p50/p95/max mm | X→F mean/p95/max mm | Final unique GT refs || --- | --- | --- | --- | --- | --- || peg | global1 | 32 | 2.8481 / 2.6659 / 5.6654 / 6.6187 | 5.1700 / 8.5499 / 11.0471 | 151 || peg | global0 | 32 | 2.9452 / 2.4687 / 6.6621 / 8.1979 | 5.2837 / 8.6095 / 10.8408 | 160 || peg | voxel | 32 | 2.8315 / 2.6333 / 5.6831 / 6.6379 | 5.1826 / 8.5255 / 11.1341 | 142 || box | global1 | 32 | 12.7793 / 12.5895 / 27.4828 / 32.7114 | 11.2533 / 18.7511 / 22.8926 | 3 || box | global0 | 32 | 10.8746 / 8.8430 / 29.7788 / 46.0516 | 11.5801 / 19.0768 / 23.1584 | 12 || box | voxel | 32 | 12.8141 / 12.5871 / 26.8639 / 32.7114 | 11.2707 / 18.6901 / 22.8926 | 6 |
| object | method | UV selected/occupied; P=0 IDs | XYZ selected/occupied; P=0 IDs | UV equal-region mean p95 mm || --- | --- | --- | --- | --- || peg | global1 | 8/8; [] | 3/4; [6] | 5.2254 || peg | global0 | 8/8; [] | 3/4; [6] | 5.6162 || peg | voxel | 8/8; [] | 3/4; [6] | 4.9291 || box | global1 | 9/9; [] | 1/1; [] | 24.6447 || box | global0 | 9/9; [] | 1/1; [] | 22.5887 || box | voxel | 9/9; [] | 1/1; [] | 24.4979 |
독립 UV4×4/XYZ 최대2×2×2 구역은 같은 X bbox로 고정했다. 구역별 후보 밀도·선택률·거리 tail과 R 단계 구역 통계는 JSON/NPZ에 있다. Box의 30.726m outlier는 그대로 남아 coarse XYZ 구역과 bbox 정규화를 왜곡하므로 raw mm와 UV를 함께 본다. 단순 구역 점유가 같아도 국소 geometry가 같다는 뜻은 아니다.

## Secondary: 선택 후 GT, C/R/P/S/F reference 손실
Same-pair ≤2px AND ≤3mm를 유지했다. Peg observed462/visible464, Box observed103/visible103이다. 한 node는 여러 reference를 덮고 한 reference는 여러 node에 매칭될 수 있다. Pair count·matching node·unique reference는 서로 다르다.
| object | voxel stage | nodes | matching nodes | unique refs | available/unavailable feature rows || --- | --- | --- | --- | --- | --- || peg | C | 703 | 692 | 462 | 32/671 || peg | P | 32 | 30 | 142 | 20/12 || peg | S | 97 | 0 | 0 | 49/48 || peg | F | 129 | 30 | 142 | 69/60 || peg | R | 432 | 426 | 462 | 21/411 || box | C | 599 | 127 | 91 | 35/564 || box | P | 32 | 2 | 6 | 28/4 || box | S | 95 | 0 | 0 | 80/15 || box | F | 127 | 2 | 6 | 108/19 || box | R | 356 | 70 | 82 | 31/325 |
| object | C→R lost refs | R→P additional lost refs | Surface added refs | P/S overlapping refs || --- | --- | --- | --- | --- || peg | 0 | 320 | 0 | 0 || box | 9 | 76 | 0 | 0 |
| Box segment | reference count | C | R | P | S | F | Global λ1 P/F | Global λ0 P/F || --- | --- | --- | --- | --- | --- | --- | --- | --- || rim_axis1_+1 | 25 | 24 | 21 | 3 | 0 | 3 | 3 / 3 | 6 / 6 || rim_axis1_-1 | 26 | 26 | 23 | 3 | 0 | 3 | 0 / 0 | 0 / 0 || rim_axis2_+1 | 26 | 15 | 12 | 0 | 0 | 0 | 0 / 0 | 0 / 3 || rim_axis2_-1 | 26 | 26 | 26 | 0 | 0 | 0 | 0 / 0 | 3 / 3 |
각 단계 reference ID 집합·joint pairs·matching source·구간별 matching node/reference·Box line spacing을 저장했다. Surface 추가분은 refs(F)−refs(P)이며 S 전체 hit 수와 다르다. C→R과 R→P 손실은 P⊆R⊆C에서 구분했다. Peg 물리적 line 순서/간격은 N/A다. GT 후보→reference 거리에는 depth noise, reference 이산화, 가시성·matcher 정의가 섞여 순수 detector localization error가 아니다. 이를 epsilon calibration에 사용하지 않았다.


## Depth·ROI·일반 Surface trade-off
| object | stage | depth median/p95/max m | negative union count / nodes || --- | --- | --- | --- || peg | X | 0.2060 / 0.3271 / 0.3650 | 7800 / 11780 || peg | C | 0.1810 / 0.3160 / 0.3500 | 11 / 703 || peg | R | 0.1990 / 0.3280 / 0.3500 | 6 / 432 || peg | P | 0.1970 / 0.3329 / 0.3500 | 2 / 32 || peg | S | 0.2660 / 0.3506 / 0.3650 | 90 / 97 || peg | F | 0.2520 / 0.3492 / 0.3650 | 92 / 129 || box | X | 0.4960 / 0.5350 / 30.7260 | 10506 / 11665 || box | C | 0.4880 / 0.6665 / 1.4260 | 281 / 599 || box | R | 0.4905 / 0.6880 / 1.4260 | 150 / 356 || box | P | 0.5805 / 1.4057 / 1.4260 | 9 / 32 || box | S | 0.5220 / 8.4310 / 30.7260 | 70 / 95 || box | F | 0.5250 / 8.4310 / 30.7260 | 79 / 127 |
원거리 positive depth를 제거하지 않았다. ROI는 중첩되므로 union을 별도 집계했다. ROI/far는 실제 noise 정답이 아니며 일반 Surface 점유를 자동 오선택으로 분류하지 않는다. X median/p95 기반 depth bands와 candidate별 P 선택률도 저장했다. Median은 단일 extreme max 영향은 줄이지만 mask 오염과 물체 내 depth 차이를 해결하지 않는다. Peg/Box는 같은 공식으로 서로 다른 metric a를 사용하며 동일 절대 해상도 비교가 아니다.

## 기존 7개 synthetic의 저장 입력 재사용
| fixture | C/R/P | a mm | dyadic ratio | Global/UV/Voxel C→P p95 mm | Global/UV/Voxel ref→P p95 mm | noise P G/UV/V || --- | --- | --- | --- | --- | --- | --- || line_uniform | 128/128/32 | 0.8165 | 16 | 3.7500 / 5.6250 / 3.7500 | 3.7500 / 5.6250 / 3.7500 | 0 / 0 / 0 || line_dense | 216/169/32 | 0.8165 | 16 | 3.7500 / 7.5000 / 3.7500 | 3.7500 / 7.5000 / 3.7500 | 0 / 0 / 0 || separated_clean | 188/164/32 | 0.8165 | 16 | 3.7500 / 5.6250 / 3.7500 | 3.9844 / 6.0937 / 3.9844 | 0 / 0 / 0 || separated_noise | 196/172/32 | 0.8165 | 16 | 3.7500 / 5.6250 / 3.7500 | 4.2188 / 6.0938 / 4.2188 | 1 / 1 / 1 || camera_near | 188/164/32 | 0.8165 | 16 | 3.7500 / 5.6250 / 3.7500 | 3.9844 / 6.0937 / 3.9844 | 0 / 0 / 0 || camera_far | 154/120/32 | 1.6330 | 8 | 3.7500 / 6.2812 / 3.7500 | 3.8320 / 6.0938 / 4.1836 | 0 / 0 / 0 || camera_occluded | 60/36/32 | 0.8165 | 2 | 0.4688 / 0.4688 / 0.4688 | 0.5859 / 0.5859 / 0.5859 | 0 / 0 / 0 |
Task03-F 저장 C/source/XYZ와 Global/UV 선택을 읽었으며 새 fixture·기준선 FPS를 만들지 않았다. Dense X가 없는 stress test에서 관측 C median과 기존 focal1600px로 같은 scale 공식을 적용했다. Annotation은 모든 선택 저장 후에만 noise/reference/구조별 평가에 사용했다. 실제 PCA5 5×5 localization uncertainty calibration과 Synthetic Surface는 N/A다. 계약/geometry stress test 통과가 uncertainty calibration 타당성을 뜻하지 않는다.

## 검증·재현·한계·완료 범위
실행 UUID 92f29716e76f4b998fe924f08e80357d. 필수 계약 테스트: Ran 86 tests in 0.677s; OK. 성능 개선을 PASS 조건으로 두지 않았다. selection_before_gt.npz를 real/synthetic 선택 전체의 저장·readback·hash 이후에만 GT evaluator/annotation에 연결했다. 평가 후 선택 hash 불변, 원본 C/X·baseline exact alignment, 원본 feature available-only exact gather를 확인했다.
기존 ExperimentLogger(team=visual, job_type=evaluate), WANDB_MODE=disabled 및 로컬 artifact inventory를 재사용했다. 기존 UUID/project/group 규칙을 바꾸지 않았다. Git 시작 상태는 dirty이며 source snapshot·input/artifact hashes·시작 diff·implementation diff를 함께 보존했다. Production sampling/normal/tracking/shared simulator와 기존 dirty/untracked 파일은 변경하지 않았다. 같은 S3 조건에서 저장된 feature가 없는 source는 unavailable로 남겼으며 feature를 추정하지 않았다.
보호 대상 기존 파일 3,092개의 SHA-256와 HEAD 불변을 확인했다. Markdown↔HTML 및 JSON/NPZ/PNG 상대 링크, PNG 7개 decode는 PASS다. 실제 브라우저 로딩은 computer-use 권한이 없어 진행하지 못했고, 사용자의 후속 지시에 따라 생략했다. 이 미실행 항목을 검증 PASS로 계산하지 않는다. 수치 실행 source_snapshot과 선택·JSON/NPZ는 유지하고 최종 해석 문구/검증 상태를 보완한 보고 source는 report_source_snapshot과 report_generation_sources로 구분한다.
CPU NumPy/SciPy offline 실행이다. 단계별 wall time은 JSON에 기록했으며 Graph/GNN 20Hz 성능을 주장하지 않는다. Simulator/renderer/CUDA/MPS/GPU/PCL, 새 episode/fixture/score/normal, threshold/scale sweep, 두 번째 selection arm, GT calibration/quota, depth filtering, ratio/Adaptive Budget, Graph/GNN/BC, dependency 설치·외부 업로드·Git commit은 미실행이다. Task03-H의 동일 count 기대 coverage는 후보 해석 근거, Task03-F/G는 기존 실패 비교군으로만 유지했다. 보고서 제출 후 추가 알고리즘 실행 없이 중단한다.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074diff --git a/visual/runtime/test/run_voxel_structural_sampling.py b/visual/runtime/test/run_voxel_structural_sampling.pynew file mode 100644index 0000000..3772aaa--- /dev/null+++ b/visual/runtime/test/run_voxel_structural_sampling.py@@ -0,0 +1,848 @@+"""Task03-I: one approved nominal voxel precompression + 3D FPS cap control.++Offline saved ep000 Frame0 only. Production, detectors and saved FPS are read-only.+WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_voxel_structural_sampling --baseline PATH+"""+from __future__ import annotations++import argparse+import hashlib+import html+from html.parser import HTMLParser+import json+import os+from pathlib import Path+import platform+import re+import shutil+import subprocess+import sys+from time import perf_counter++import matplotlib+matplotlib.use('Agg')+import matplotlib.pyplot as plt+import numpy as np+from scipy.spatial import cKDTree++from utils.experiment_logger import ExperimentLogger+from visual.runtime.sampling import fps_indices+from visual.runtime.test import run_local_structural_sampling as local+from visual.runtime.test import run_priority_fps_metric_control as prior+from visual.runtime.test.run_rim_bottleneck import occupancy, require_equal+from visual.runtime.test.sampling_evaluation import staged_reference_coverage++REPO = prior.REPO+STEM = 'voxel_structural_sampling'+REPORT = REPO/'docs/visual-graph-integration/03i_voxel_structural_sampling.md'+PLAN = REPO/'docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md'+FIXTURE_RUN = REPO/'experiments/1f7ad262dd2e4b2fb0ac805a4eda5278'+FIGURES = ('primary_selection.png', 'resolution_budget.png', 'primary_distances.png',+ 'peg_gt.png', 'box_gt.png', 'depth_roi_surface.png', 'synthetic.png')+TESTS = ['visual.runtime.test.'+n for n in ('test_voxel_structural_sampling', 'test_sampling',+ 'test_sampling_geometry', 'test_sampling_evaluation', 'test_priority_fps_metric_control',+ 'test_local_structural_sampling')]+RULES = dict(frame=0, episode='ep000', camera='base_camera', method='S3 optimized PCA5',+ orientation='strict >20 degrees, stored C only', seed=0, priority_cap_per_object=32,+ final_targets=dict(peg=129, box=127), total_cap=256, structural_ratio=.25,+ scale='median Z of original X; epsilon=z*sqrt((2/fx)^2+(2/fy)^2); a=epsilon/sqrt(3)',+ multiplier=1., grid='CV camera metres; origin 0; float64 floor(xyz/a); int64; half-open',+ representative='float64 centroid nearest original C; exact squared-distance tie smallest source',+ order='C/R source ascending; mapped anchor first in P; rest FPS or source ascending',+ anchor='original whole-C seeded anchor cell representative', cap='existing Euclidean 3D fps_indices',+ surface='existing whole-X 3D FPS initial=P; unused Priority becomes Surface; no padding',+ dyadic='count-only; floor_divide nominal keys by 2; first count<=32; never used for selection',+ gt='only after all real/synthetic selections saved, read back and hashed; same-pair <=2px AND <=3mm',+ score='none; no optimized dense C score available', uv_bins=[4,4], xyz_bins=[2,2,2],+ synthetic_names=local.FIXTURES['names'], synthetic_scale='stored C median Z; stored focal=1600px',+ synthetic_uncertainty_calibration='N/A: no actual PCA5 estimator/localization evidence',+ interpretation='first feasibility of voxel precompression + 3D FPS cap; anchor also changes')+++def serial(value):+ if isinstance(value, dict): return {str(k):serial(v) for k,v in value.items()}+ if isinstance(value, (list,tuple)): return [serial(v) for v in value]+ if isinstance(value, np.ndarray): return serial(value.tolist())+ if isinstance(value, np.generic): return serial(value.item())+ if isinstance(value, Path): return str(value)+ if isinstance(value, float) and not np.isfinite(value): return None+ return value+++def write_json(path, value):+ Path(path).write_text(json.dumps(serial(value), ensure_ascii=False, indent=2, allow_nan=False)+'\n')+++def sources(flat, xyz):+ flat, xyz = np.asarray(flat), np.asarray(xyz)+ if flat.ndim != 1 or flat.dtype.kind not in 'iu' or np.any(flat < 0):+ raise ValueError('nonnegative integer sources required')+ if len(flat)>1 and not np.all(flat[1:]>flat[:-1]): raise ValueError('strict source order required')+ if xyz.shape != (len(flat),3) or not np.isfinite(xyz).all(): raise ValueError('finite source XYZ required')+ return flat, xyz+++def nominal_scale(xyz, intrinsic):+ xyz, k = np.asarray(xyz), np.asarray(intrinsic, float)+ if xyz.ndim!=2 or xyz.shape[1]!=3 or not np.isfinite(xyz).all() or (xyz[:,2]<=0).any():+ raise ValueError('original positive-depth X required')+ if k.shape!=(3,3) or not np.isfinite(k).all() or min(k[0,0],k[1,1])<=0:+ raise ValueError('valid intrinsic required')+ if not len(xyz): return dict(status='N/A', z_ref_m=None, epsilon_m=None, a_m=None)+ z = float(np.median(xyz[:,2].astype(float)))+ epsilon = z*np.hypot(2/k[0,0], 2/k[1,1])+ a = epsilon/np.sqrt(3)+ if not np.isfinite(a) or a<=0: raise ValueError('nonpositive nominal scale')+ return dict(status='defined', z_ref_m=z, fx_px=float(k[0,0]), fy_px=float(k[1,1]),+ epsilon_m=float(epsilon), a_m=float(a), multiplier=1.,+ pair_footprint_m=float(z*max(np.hypot(3/k[0,0],2/k[1,1]),np.hypot(2/k[0,0],3/k[1,1]))))+++def voxel_keys(xyz, a):+ xyz=np.asarray(xyz, float)+ if xyz.ndim!=2 or xyz.shape[1]!=3 or not np.isfinite(xyz).all() or not np.isfinite(a) or a<=0:+ raise ValueError('finite XYZ and positive size required')+ with np.errstate(over='ignore',invalid='ignore'):+ q=np.floor(xyz/a)+ # float64(int64.max) rounds to 2**63, so the upper comparison is strict.+ if not np.isfinite(q).all() or (q < -(2.**63)).any() or (q >= 2.**63).any():+ raise ValueError('voxel key int64 overflow')+ return q.astype(np.int64)+++def representatives(flat, xyz, a):+ flat,xyz=sources(flat,xyz)+ key=voxel_keys(xyz,a)+ cells,membership,capacity=np.unique(key,axis=0,return_inverse=True,return_counts=True)+ rep_rows=np.empty(len(cells),np.int64)+ for cell in range(len(cells)):+ rows=np.flatnonzero(membership==cell) # already source ascending+ points=xyz[rows].astype(float)+ centroid=points.mean(axis=0)+ distance=np.sum((points-centroid)**2,axis=1)+ rep_rows[cell]=rows[int(distance.argmin())]+ same_rows=rep_rows[membership]+ same_distance=np.linalg.norm(xyz.astype(float)-xyz[same_rows].astype(float),axis=1)+ if len(flat) and np.max(same_distance)>np.sqrt(3)*a+64*np.finfo(float).eps*max(1.,np.max(np.abs(xyz))):+ raise AssertionError('same-cell bound failed')+ return dict(keys=key,cells=cells,membership=membership,capacity=capacity,+ cell_rep_rows=rep_rows, representative_rows=np.sort(rep_rows),+ same_representative_source=flat[same_rows], same_cell_distance_m=same_distance)+++def dyadic_counts(keys, a, cap=32):+ keys=np.asarray(keys)+ if keys.ndim!=2 or keys.shape[1]!=3 or keys.dtype!=np.int64 or not np.isfinite(a) or a<=0:+ raise ValueError('int64 keys and positive size required')+ if not isinstance(cap,int) or cap<0: raise ValueError('invalid cap')+ if cap==0 and len(keys): return dict(status='impossible',levels=[],a_budget_m=None,ratio=None)+ if cap<8 and len(keys): raise ValueError('termination only guaranteed for cap>=8')+ levels=[]; key=keys.copy()+ for level in range(65):+ count=len(np.unique(key,axis=0))+ if levels and count>levels[-1]['occupied']: raise AssertionError('non-nested parent count')+ size=float(np.ldexp(a,level))+ if not np.isfinite(size): raise ValueError('dyadic size overflow')+ levels.append(dict(level=level,occupied=count,a_m=size,ratio=2**level,bound_m=np.sqrt(3)*size))+ if count<=cap: return dict(status='defined',levels=levels,a_budget_m=size,ratio=2**level,+ occupied=count,used_for_selection=False)+ key=np.floor_divide(key,2)+ raise AssertionError('dyadic iteration failed to terminate')+++def choose_priority(flat, xyz, a, seed, anchor=None, cap=32, shape=None):+ if not isinstance(cap,int) or cap<0: raise ValueError('nonnegative integer cap required')+ t0=perf_counter(); g=representatives(flat,xyz,a); t1=perf_counter()+ flat,xyz=sources(flat,xyz); rrows=g['representative_rows']; rflat=flat[rrows]+ mapped=None; mapped_row=None+ if len(flat):+ if anchor is None: anchor=int(flat[np.random.default_rng(seed).integers(len(flat))])+ ar=np.flatnonzero(flat==anchor)+ if len(ar)!=1: raise ValueError('anchor outside C')+ mapped=int(g['same_representative_source'][ar[0]])+ mapped_row=int(np.searchsorted(rflat,mapped))+ if len(rrows)>cap:+ chosen=fps_indices(xyz[rrows],cap,seed=seed,initial=[mapped_row] if cap else ())+ elif len(rrows) and cap:+ chosen=np.r_[mapped_row,np.flatnonzero(rflat!=mapped)].astype(np.int64)+ else: chosen=np.empty(0,np.int64)+ prows=rrows[chosen]; t2=perf_counter()+ anchor_info=dict(original_source=anchor if len(flat) else None,mapped_source=mapped,distance_m=None,+ delta_pixel_uv=None,pixel_distance_px=None)+ if len(flat):+ anchor_info['distance_m']=float(np.linalg.norm(xyz[int(ar[0])].astype(float)-xyz[rrows[mapped_row]].astype(float)))+ if shape is not None:+ uvs=np.column_stack(np.unravel_index([anchor,mapped],shape))[:,::-1]+ delta=uvs[1]-uvs[0]+ anchor_info.update(delta_pixel_uv=delta.tolist(),pixel_distance_px=float(np.linalg.norm(delta)))+ g.update(R=rflat.copy(),P=flat[prows].copy(),priority_rows=prows,anchor=anchor_info,+ timings_ms=dict(grid_representatives=(t1-t0)*1000,cap_fps=(t2-t1)*1000))+ return g+++def select(candidate_flat,candidate_xyz,support_flat,support_xyz,shape,intrinsic,seed,anchor,final_target,cap=32):+ if not isinstance(cap,int) or cap<0: raise ValueError('invalid Priority cap')+ c,cxyz=sources(candidate_flat,candidate_xyz); x,xxyz=sources(support_flat,support_xyz)+ local.uv_from_flat(c,shape);local.uv_from_flat(x,shape)+ rows=np.searchsorted(x,c)+ if (rows>=len(x)).any() or not np.array_equal(x[rows],c): raise ValueError('C outside X')+ np.testing.assert_array_equal(xxyz[rows],cxyz)+ if not isinstance(final_target,int) or final_target<0: raise ValueError('invalid final target')+ t0=perf_counter();scale=nominal_scale(xxyz,intrinsic);t1=perf_counter()+ if len(x):+ g=choose_priority(c,cxyz,scale['a_m'],seed,anchor,min(cap,final_target),shape)+ dyadic=dyadic_counts(g['keys'],scale['a_m'],cap)+ else:+ g=dict(R=c.copy(),P=c.copy(),keys=np.empty((0,3),np.int64),cells=np.empty((0,3),np.int64),+ membership=np.empty(0,np.int64),capacity=np.empty(0,np.int64),cell_rep_rows=np.empty(0,np.int64),+ representative_rows=np.empty(0,np.int64),same_representative_source=c.copy(),same_cell_distance_m=np.empty(0),+ anchor=dict(original_source=None,mapped_source=None,distance_m=None,delta_pixel_uv=None,pixel_distance_px=None),+ timings_ms=dict(grid_representatives=0.,cap_fps=0.))+ dyadic=dict(status='N/A',levels=[],a_budget_m=None,ratio=None)+ t2=perf_counter(); initial=np.searchsorted(x,g['P'])+ frows=fps_indices(xxyz,final_target,seed=seed,initial=initial);f=x[frows];t3=perf_counter()+ return dict(P=g['P'],R=g['R'],S=f[len(initial):],F=f,xyz=xxyz[frows].copy(),grouping=g,scale=scale,+ dyadic=dyadic,shortfall=max(0,final_target-len(f)),+ timings_ms=dict(scale=(t1-t0)*1000,selection_and_dyadic=(t2-t1)*1000,surface_fps=(t3-t2)*1000,**g['timings_ms']))+++def nearest_sources(query,flat,xyz):+ """Exact tie resolution by ascending source, independent of cKDTree ordering."""+ flat=np.asarray(flat); xyz=np.asarray(xyz,float);query=np.asarray(query,float)+ if not len(flat): return np.full(len(query),np.nan),np.full(len(query),-1,np.int64)+ order=np.argsort(flat,kind='stable');flat=flat[order];xyz=xyz[order]+ distances=np.empty(len(query));near=np.empty(len(query),np.int64)+ for i,q in enumerate(query):+ d=np.sum((xyz-q)**2,axis=1);j=int(d.argmin());distances[i]=np.sqrt(d[j]);near[i]=flat[j]+ return distances,near+++def distance_decomposition(c,cxyz,chosen,shape):+ g=chosen['grouping']; r=chosen['R'];p=chosen['P']+ rxyz=cxyz[np.searchsorted(c,r)]; pxyz=cxyz[np.searchsorted(c,p)]+ dr,nr=nearest_sources(cxyz,r,rxyz);dp,np_=nearest_sources(cxyz,p,pxyz)+ budget=dp-dr+ if np.isfinite(budget).any() and np.nanmin(budget)<-1e-12: raise AssertionError('P not subset of R distance')+ arrays=dict(same_cell_m=g['same_cell_distance_m'],C_to_R_m=dr,C_to_P_m=dp,budget_extra_m=budget,+ C_to_R_source=nr,C_to_P_source=np_,same_cell_source=g['same_representative_source'])+ result={}+ for key in ('same_cell_m','C_to_R_m','C_to_P_m','budget_extra_m'):+ d=arrays[key];finite=np.isfinite(d);worst=int(np.nanargmax(d)) if finite.any() else None+ result[key]=dict(**local.summary(d*1000),unit='mm',missing_count=int((~finite).sum()),+ worst=None if worst is None else dict(source=int(c[worst]),xyz_m=cxyz[worst].tolist(),+ pixel_uv=local.uv_from_flat(c[[worst]],shape)[0].tolist(),distance_mm=float(d[worst]*1000)))+ arrays[key+'_ecdf']=np.sort(d[finite])+ eps=chosen['scale']['epsilon_m']+ selected_cells=np.unique(g['membership'][np.searchsorted(c,p)]) if len(p) else np.empty(0,np.int64)+ discarded=np.setdiff1d(np.arange(len(r)),selected_cells)+ above=dp>eps if eps is not None else np.zeros(len(c),bool)+ result.update(candidate_count=len(c),nominal_occupied=len(r),selected_occupied=len(selected_cells),+ discarded_occupied=len(discarded),occupied_over_32=len(r)/32,priority_count=len(p),+ resolution_budget_conflict=len(r)>32,above_epsilon_count=int(above.sum()),+ above_epsilon_fraction=float(above.mean()) if len(c) else None,+ a_used_m=chosen['scale']['a_m'],used_over_nominal=1. if eps is not None else None,+ discarded_cells=[dict(cell=int(i),key=g['cells'][i].tolist(),candidate_count=int(g['capacity'][i]),+ C_to_P_mm=local.summary(dp[g['membership']==i]*1000)) for i in discarded])+ arrays.update(selected_cell_ids=selected_cells,discarded_cell_ids=discarded,above_epsilon=above)+ return result,arrays+++def add_arrays(target,prefix,values):+ for k,v in values.items(): target[prefix+'/'+k]=np.asarray(v)+++def selection_arrays(cases,selections,synthetic):+ arrays={}+ for name,case in cases.items():+ chosen=selections[name]+ add_arrays(arrays,name,{k:case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz')})+ add_arrays(arrays,name,{k:chosen[k] for k in ('R','P','S','F','xyz')})+ add_arrays(arrays,name+'/voxel',{k:chosen['grouping'][k] for k in ('keys','cells','membership','capacity',+ 'cell_rep_rows','representative_rows','same_representative_source','same_cell_distance_m')})+ for name,data in synthetic.items():+ add_arrays(arrays,'synthetic/'+name,dict(candidate_flat=data['flat'],candidate_xyz=data['xyz'],+ R=data['chosen']['R'],P=data['chosen']['P'],keys=data['chosen']['grouping']['keys']))+ return arrays+++def freeze_selection(output,cases,selections,synthetic):+ path=output/'selection_before_gt.npz'+ if path.exists(): raise FileExistsError('selection already frozen')+ arrays=selection_arrays(cases,selections,synthetic)+ np.savez_compressed(path,**arrays)+ with np.load(path,allow_pickle=False) as saved:+ require_equal(set(saved.files),set(arrays),'frozen keys')+ for key,value in arrays.items(): np.testing.assert_array_equal(saved[key],value,err_msg=key)+ return prior.sha(path),arrays+++def check_selection(case,chosen):+ c,x=case['candidate_flat'],case['support_flat'];p,r,s,f=(chosen[k] for k in ('P','R','S','F'))+ if not set(p)<=set(r)<=set(c)<=set(x): raise AssertionError('P subset R subset C subset X')+ for key in ('R','P','S','F'):+ if len(np.unique(chosen[key]))!=len(chosen[key]): raise AssertionError('duplicate '+key)+ if len(p)>32 or len(f)>case['budget'] or len(f)!=min(len(x),case['budget']): raise AssertionError('budget')+ np.testing.assert_array_equal(f,np.r_[p,s]);np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(x,f)])+++def load_baselines(cases,zero,samples):+ baselines={}+ with np.load(local.BASELINE/(prior.STEM+'.npz'),allow_pickle=False) as e:+ for name,case in cases.items():+ one={stage:case['saved_flat'][sl].copy() for stage,sl in+ (('P',slice(0,32)),('S',slice(32,None)),('F',slice(None)))}+ one['xyz']=case['support_xyz'][np.searchsorted(case['support_flat'],one['F'])].copy()+ for stage in ('P','S','F'):+ np.testing.assert_array_equal(one[stage],e[f'S3/{name}/1.0/{stage}/flat_index'])+ for method,chosen in dict(global1=one,global0=zero[name]).items():+ require_equal((len(chosen['P']),len(chosen['F']),int(chosen['P'][0])),+ (32,case['budget'],case['first']),'stored baseline count/anchor')+ np.testing.assert_array_equal(chosen['F'],np.r_[chosen['P'],chosen['S']])+ np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(case['support_flat'],chosen['F'])])+ key='S3_n256_r0.25_t20_s0';mask=samples[key+'/object_id']==case['oid']+ np.testing.assert_array_equal(samples[key+'/points'][mask],one['xyz'])+ np.testing.assert_array_equal(samples[key+'/priority_selected'][mask],np.arange(case['budget'])<32)+ for flag in ('orientation_candidate','structural_candidate'):+ np.testing.assert_array_equal(case['saved_features'][flag],np.isin(one['F'],case['candidate_flat']))+ baselines[name]=dict(global1=one,global0=zero[name])+ return baselines+++def load_synthetic_observations():+ """Read observations and saved baseline selections only; no annotation field."""+ manifest=json.loads((FIXTURE_RUN/'fixture_manifest.json').read_text())+ output={}+ with np.load(FIXTURE_RUN/(local.STEM+'.npz'),allow_pickle=False) as saved:+ for name in RULES['synthetic_names']:+ pre='synthetic/'+name+'/'+ flat,xyz=saved[pre+'candidate_flat'].copy(),saved[pre+'candidate_xyz'].copy()+ sources(flat,xyz)+ if len(flat)!=manifest[name]['counts']['observed_count']: raise AssertionError('fixture count')+ require_equal(prior.array_sha(flat),manifest[name]['flat_sha256'],'saved fixture source hash')+ require_equal(prior.array_sha(xyz),manifest[name]['xyz_sha256'],'saved fixture XYZ hash')+ shape=tuple(local.FIXTURES['shape']);local.uv_from_flat(flat,shape)+ seed=prior.fps_seed(0,0);anchor=int(flat[np.random.default_rng(seed).integers(len(flat))])+ k=np.array([[1600.,0,511.5],[0,1600.,511.5],[0,0,1]])+ scale=nominal_scale(xyz,k)+ g=choose_priority(flat,xyz,scale['a_m'],seed,anchor,32,shape)+ chosen=dict(R=g['R'],P=g['P'],grouping=g,scale=scale,dyadic=dyadic_counts(g['keys'],scale['a_m']))+ output[name]=dict(flat=flat,xyz=xyz,shape=shape,chosen=chosen,+ saved_global=saved[pre+'global/P'].copy(),saved_uv=saved[pre+'local/P'].copy())+ return output+++def stage_gt(flat,context,labels,specs,transform):+ """Thin variable-cardinality adapter over the existing joint matcher."""+ matcher=context['matcher'];rows=np.searchsorted(matcher.flat,flat)+ ids,matched=matcher.reference_hits(flat);adj=matcher.adjacencies['2px_3mm'][rows]+ covered=np.zeros(matcher.nref,bool);covered[ids]=True+ xyz=matcher.xyz[rows];uv=matcher.uv[rows]+ segments={}+ for label in sorted(set(labels)):+ mask=labels==label;hit=adj[:,mask].getnnz(axis=1)>0+ spacing=dict(status='N/A',reason='physical single-line order unverified')+ if label in specs and transform is not None:+ wt=transform['world_to_cv'];rot=transform['rot']+ world=(xyz[hit]-wt[:3,3])@np.linalg.inv(wt[:3,:3].T)+ loc=(world-transform['box_pose'][:3])@np.linalg.inv(rot.T)+ spacing=prior.segment_spacing(specs[label]['local'][mask],covered[mask],loc[:,specs[label]['axis']],order_verified=True)+ segments[str(label)]=dict(reference_count=int(mask.sum()),observed_reference_count=int((mask&context['observable']).sum()),+ unique_reference_count=int((covered&mask).sum()),covered_reference_ids=np.flatnonzero(covered&mask).tolist(),+ matching_node_count=int(hit.sum()),matching_sources=flat[hit].tolist(),spacing=spacing)+ distance,nearest=nearest_sources(xyz,np.arange(matcher.nref,dtype=np.int64),context['reference'][1])+ coo=adj.tocoo()+ return dict(node_count=len(flat),matching_node_count=len(matched),unique_reference_count=len(ids),+ covered_reference_ids=ids.tolist(),matching_sources=matched.tolist(),segments=segments,+ candidate_to_GT_reference_mm=local.summary(distance*1000)),dict(flat_index=flat,xyz=xyz,pixel_uv=uv,+ covered=covered,matching_source=matched,joint_node_row=coo.row,joint_reference_id=coo.col,+ to_GT_reference_m=distance,to_GT_reference_id=nearest)+++def evaluate_method(case,chosen,context,frame,labels,specs,transform,arrays,prefix):+ c=case['candidate_flat'];x=case['support_flat'];stages=dict(C=c,P=chosen['P'],S=chosen['S'],F=chosen['F'])+ if 'R' in chosen: stages['R']=chosen['R']+ details={}+ for stage,flat in stages.items():+ details[stage],raw=stage_gt(flat,context,labels,specs,transform)+ add_arrays(arrays,prefix+'/'+stage,raw)+ available,positions,features=prior.feature_rows(case,flat)+ add_arrays(arrays,prefix+'/'+stage,dict(feature_available=available,feature_available_positions=positions))+ add_arrays(arrays,prefix+'/'+stage+'/available_features',features)+ details[stage]['feature_available_count']=int(available.sum())+ details[stage]['feature_unavailable_count']=int((~available).sum())+ coverage=staged_reference_coverage(context['matcher'],c,chosen['P'],chosen['S'],chosen['F'])+ sets={k:set(v['covered_reference_ids']) for k,v in details.items()}+ differences={}+ for label,first,second in [('C_minus_R','C','R'),('R_minus_P','R','P'),('F_minus_P','F','P'),('P_intersect_S','P','S')]:+ if first in sets and second in sets:+ ids=sets[first]&sets[second] if label=='P_intersect_S' else sets[first]-sets[second]+ differences[label]=dict(count=len(ids),reference_ids=sorted(ids))+ occ=occupancy(frame,dict(X=x,**stages),context['negatives'])+ bounds=occ['depth_band_bounds_m'];zc=frame.depth.ravel()[c];zp=frame.depth.ravel()[chosen['P']]+ band=lambda z:(z<=bounds['median'],(z>bounds['median'])&(z<=bounds['p95']),z>bounds['p95'])+ occ['candidate_band_priority_selection_rates']=[dict(candidate_count=int(a.sum()),priority_count=int(b.sum()),+ rate=float(b.sum()/a.sum()) if a.any() else None) for a,b in zip(band(zc),band(zp))]+ spatial,raw=local.spatial_metrics(c,case['candidate_xyz'],chosen['P'],+ case['support_xyz'][np.searchsorted(x,chosen['P'])],x,case['support_xyz'],frame.depth.shape)+ add_arrays(arrays,prefix+'/spatial',raw)+ ds=local.nearest(case['support_xyz'],chosen['xyz'])*1000+ add_arrays(arrays,prefix,dict(X_to_F_mm=ds,F_selection_role=np.where(np.arange(len(chosen['F']))<len(chosen['P']),'Priority','Surface')))+ return dict(stages=details,coverage=coverage,reference_differences=differences,occupancy=occ,+ spatial=spatial,surface_mm=local.summary(ds))+++def evaluate_after_freeze(output,selection_sha,frame,geometry,samples,cases,selections,baselines,synthetic,input_config):+ require_equal(prior.sha(output/'selection_before_gt.npz'),selection_sha,'pre-GT selection hash')+ arrays={};actual={}+ with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal:+ contexts=prior.evaluation_inputs(frame,geometry,samples,edges,normal)+ peg_labels,_=prior.peg_labels(normal['evaluation/peg/face'],normal['evaluation/peg/gt_visible'],+ normal['evaluation/peg/seam_endpoints'],contexts['peg']['reference'][0])+ with np.load(input_config['input'],allow_pickle=False) as episode:+ box_labels,specs,transform=prior.rim_labels(contexts['box']['reference'][1],frame.cam2world,+ episode['box_pose'][0],episode['box_hole_pose'][0],float(episode['box_hole_radii']))+ for name,case in cases.items():+ context=contexts[name];labels=peg_labels if name=='peg' else box_labels+ add_arrays(arrays,'evaluation/'+name,dict(reference_uv=context['reference'][0],reference_xyz=context['reference'][1],+ observable=context['observable'],segment=labels))+ methods={}+ for method,chosen in dict(**baselines[name],voxel=selections[name]).items():+ methods[method]=evaluate_method(case,chosen,context,frame,labels,{} if name=='peg' else specs,+ None if name=='peg' else transform,arrays,name+'/'+method)+ original_metrics=json.loads((local.SOURCE/'f0000_metrics.json').read_text())['S3_n256_r0.25_t20_s0']['objects'][name]+ score=context['matcher'].score(baselines[name]['global1']['F'])[0]+ require_equal(score,original_metrics['structural'],'original structural exact')+ require_equal(prior.stats(arrays[name+'/global1/X_to_F_mm']),original_metrics['surface']['all']['distance_mm'],'original Surface exact')+ saved_e=json.loads((local.BASELINE/(prior.STEM+'.json')).read_text())['cases']['S3/'+name]['conditions']['0.0']+ for stage in ('C','P','S','F'):+ require_equal(methods['global0']['stages'][stage]['unique_reference_count'],saved_e['stages'][stage]['unique_reference_count'],'E saved refs')+ require_equal(methods['global0']['stages'][stage]['matching_node_count'],saved_e['stages'][stage]['structural_matching_nodes'],'E saved nodes')+ compression,raw=distance_decomposition(case['candidate_flat'],case['candidate_xyz'],selections[name],frame.depth.shape)+ add_arrays(arrays,name+'/compression',raw)+ r=selections[name]['R'];rxyz=case['candidate_xyz'][np.searchsorted(case['candidate_flat'],r)]+ rspatial,rraw=local.spatial_metrics(case['candidate_flat'],case['candidate_xyz'],r,rxyz,case['support_flat'],case['support_xyz'],frame.depth.shape)+ add_arrays(arrays,name+'/R_spatial',rraw)+ support_scales=case['candidate_xyz'][:,2].astype(float)*np.hypot(2/frame.intrinsic[0,0],2/frame.intrinsic[1,1])+ add_arrays(arrays,name,dict(candidate_r5_m=support_scales))+ actual[name]=dict(scale=selections[name]['scale'],dyadic=selections[name]['dyadic'],anchor=selections[name]['grouping']['anchor'],+ compression=compression,R_spatial=rspatial,candidate_r5_mm=local.summary(support_scales*1000),methods=methods,+ timings_ms=selections[name]['timings_ms'])+ synth_result={}+ with np.load(FIXTURE_RUN/(local.STEM+'.npz'),allow_pickle=False) as saved:+ for name,data in synthetic.items():+ pre='synthetic/'+name+'/'+ annotation={k:saved[pre+k].copy() for k in ('structure_id','reference_xyz','reference_structure_id','reference_visible','lengths_m','generated_id')}+ annotation['occluded']=name=='camera_occluded'+ compression,raw=distance_decomposition(data['flat'],data['xyz'],data['chosen'],data['shape'])+ add_arrays(arrays,pre.rstrip('/')+'/compression',raw)+ row={}+ for method,p in dict(global0=data['saved_global'],uv=data['saved_uv'],voxel=data['chosen']['P']).items():+ row[method],raw=local.evaluate_synthetic(data,annotation,p)+ add_arrays(arrays,pre+method,raw)+ synth_result[name]=dict(scale=data['chosen']['scale'],dyadic=data['chosen']['dyadic'],compression=compression,+ anchor=data['chosen']['grouping']['anchor'],methods=row,uncertainty_calibration='N/A',surface='N/A')+ data['annotation']=annotation+ require_equal(prior.sha(output/'selection_before_gt.npz'),selection_sha,'post-GT selection unchanged')+ return actual,synth_result,arrays,contexts+++def plot_results(output,frame,cases,selections,result,arrays,synthetic,contexts):+ def save(fig,name):+ fig.savefig(output/name,dpi=150,bbox_inches='tight');plt.close(fig)+ def points(ax,flat,color,label,marker='o',size=10):+ uv=local.uv_from_flat(flat,frame.depth.shape)+ ax.scatter(uv[:,0],uv[:,1],s=size,c=color,label=label,marker=marker,linewidths=.5)+ def view(ax,case):+ uv=local.uv_from_flat(case['support_flat'],frame.depth.shape);lo,hi=uv.min(0),uv.max(0)+ ax.imshow(frame.rgb);ax.set_xlim(lo[0]-8,hi[0]+8);ax.set_ylim(hi[1]+8,lo[1]-8)+ ax.set_xlabel('source u [px]');ax.set_ylabel('source v [px]')+ fig,axes=plt.subplots(2,3,figsize=(15,9))+ for row,(name,case) in enumerate(cases.items()):+ chosen=selections[name]+ for ax in axes[row]:view(ax,case)+ points(axes[row,0],case['candidate_flat'],'#38bdf8','C',size=8)+ points(axes[row,1],case['candidate_flat'],'#64748b','C',size=5)+ points(axes[row,1],chosen['R'],'#ff9f1c','R',size=12)+ points(axes[row,2],chosen['S'],'#a3e635','S',size=9)+ points(axes[row,2],chosen['P'],'#e879f9','P','*',35)+ for ax,title in zip(axes[row],(f'{name}: original C={len(case["candidate_flat"])}',+ f'nominal R={len(chosen["R"])} (not budget matched)',f'P={len(chosen["P"])} + S={len(chosen["S"])} = F={len(chosen["F"])}')):+ ax.set_title(title);ax.legend(fontsize=8)+ fig.suptitle('Observed source points: C / nominal representatives R / actual P + S = F',fontsize=15)+ save(fig,'primary_selection.png')++ fig,axes=plt.subplots(2,2,figsize=(12,8))+ for col,(name,row) in enumerate(result['actual'].items()):+ co=row['compression'];dy=row['dyadic'];s=row['scale']+ ax=axes[0,col];counts=[co['candidate_count'],co['nominal_occupied'],co['selected_occupied'],co['discarded_occupied']]+ ax.bar(['C','R occupied','P occupied','discarded'],counts,color=['#38bdf8','#ff9f1c','#d946ef','#64748b'])+ ax.axhline(32,color='red',ls='--',label='Priority cap=32');ax.legend()+ ax.set_title(f'{name}: epsilon={s["epsilon_m"]*1000:.3f} mm; a={s["a_m"]*1000:.3f} mm')+ for i,c in enumerate(counts):ax.text(i,c+3,str(c),ha='center')+ ax=axes[1,col];lev=dy['levels'];ax.plot([r['ratio'] for r in lev],[r['occupied'] for r in lev],'o-')+ ax.axhline(32,color='red',ls='--');ax.set_xscale('log',base=2)+ ax.set_xlabel('dyadic metric size / nominal (count only; not selected)');ax.set_ylabel('occupied cells')+ ax.set_title(f'First <=32: {dy["occupied"]} cells at {dy["ratio"]}x; actual selection stays 1x')+ fig.tight_layout();save(fig,'resolution_budget.png')++ fig,axes=plt.subplots(2,2,figsize=(13,9))+ for col,(name,row) in enumerate(result['actual'].items()):+ ax=axes[0,col]+ for field,label in [('same_cell_m','same-cell'),('C_to_R_m','C -> R'),('C_to_P_m','C -> P'),('budget_extra_m','budget extra')]:+ d=arrays[f'{name}/compression/{field}_ecdf']*1000+ ax.step(d,np.arange(1,len(d)+1)/max(1,len(d)),where='post',label=label)+ ax.axvline(row['scale']['epsilon_m']*1000,color='grey',ls='--',label='nominal epsilon (R cell only)')+ ax.set_xlabel('Euclidean distance [mm]');ax.set_ylabel('fraction');ax.set_title(name+' distance decomposition');ax.legend(fontsize=8)+ ax=axes[1,col]+ for method in ('global1','global0','voxel'):+ d=arrays[f'{name}/{method}/spatial/distance_mm'];d=np.sort(d)+ ax.step(d,np.arange(1,len(d)+1)/len(d),where='post',label=method)+ ax.set_xlabel('C -> actual Priority [mm]');ax.set_ylabel('fraction');ax.set_title(name+' fixed-cap comparison');ax.legend()+ fig.tight_layout();save(fig,'primary_distances.png')++ for name,case in cases.items():+ row=result['actual'][name]['methods']['voxel'];context=contexts[name];uv=context['reference'][0]+ fig,axes=plt.subplots(2,3,figsize=(15,9))+ for ax,stage in zip(axes.flat,('C','R','P','S','F')):+ view(ax,case);covered=np.asarray(arrays[f'{name}/voxel/{stage}/covered'])+ ax.scatter(uv[:,0],uv[:,1],c='#ef4444',s=10,label='uncovered reference')+ ax.scatter(uv[covered,0],uv[covered,1],c='#22c55e',s=12,label='covered reference')+ points(ax,arrays[f'{name}/voxel/{stage}/flat_index'],'#c084fc',stage,'x',15)+ st=row['stages'][stage]+ ax.set_title(f'{stage}: nodes={st["node_count"]}; matching={st["matching_node_count"]}; unique refs={st["unique_reference_count"]}')+ ax=axes.flat[-1];view(ax,case)+ ax.scatter(uv[:,0],uv[:,1],s=8,c='#64748b',label='all refs')+ for key,color,label in [('C_minus_R','#ef4444','lost C -> R'),('R_minus_P','#f59e0b','lost R -> P'),('F_minus_P','#22c55e','added Surface')]:+ ids=row['reference_differences'][key]['reference_ids']+ ax.scatter(uv[ids,0],uv[ids,1],c=color,s=24,label=f'{label}: {len(ids)}')+ ax.set_title('Loss at compression / cap; Surface additions');ax.legend(fontsize=8)+ fig.suptitle(name+' auxiliary GT only: same-pair <=2px AND <=3mm; references != matching nodes')+ fig.tight_layout();save(fig,name+'_gt.png')++ fig,axes=plt.subplots(2,3,figsize=(15,9))+ for row,(name,data) in enumerate(result['actual'].items()):+ ax=axes[row,0]+ for stage,color in [('C','#38bdf8'),('R','#ff9f1c'),('P','#d946ef'),('S','#84cc16'),('F','#8b5cf6')]:+ flat=arrays[f'{name}/voxel/{stage}/flat_index'];z=np.sort(frame.depth.ravel()[flat])+ ax.step(z,np.arange(1,len(z)+1)/len(z),where='post',label=stage,color=color)+ ax.set_xscale('log');ax.set_xlabel('original depth Z [m], log scale');ax.set_title(name+' retained depth tails');ax.legend()+ methods=list(data['methods']);x=np.arange(len(methods));ax=axes[row,1]+ for offset,stage in [(-.2,'P'),(0,'S'),(.2,'F')]:+ vals=[data['methods'][m]['occupancy']['negative_roi']['known_negative_union'][stage]['fraction_of_path']['value'] for m in methods]+ ax.bar(x+offset,vals,width=.2,label=stage)+ ax.set_xticks(x,methods);ax.set_ylabel('ROI fraction (not noise ground truth)');ax.set_title(name+' existing negative union');ax.legend()+ ax=axes[row,2]+ for offset,metric in [(-.2,'mean'),(0,'p95'),(.2,'max')]:+ ax.bar(x+offset,[data['methods'][m]['surface_mm'][metric] for m in methods],width=.2,label=metric)+ ax.set_xticks(x,methods);ax.set_ylabel('X -> F [mm]');ax.set_title(name+' Surface trade-off');ax.legend()+ fig.tight_layout();save(fig,'depth_roi_surface.png')++ fig,axes=plt.subplots(7,3,figsize=(15,23))+ for row,(name,data) in enumerate(synthetic.items()):+ for col,(method,p) in enumerate(dict(global0=data['saved_global'],uv=data['saved_uv'],voxel=data['chosen']['P']).items()):+ ax=axes[row,col];xyz=data['xyz'];pxyz=xyz[np.searchsorted(data['flat'],p)]+ ax.scatter(xyz[:,0]*1000,xyz[:,1]*1000,s=7,c='#94a3b8',label='stored C')+ if method=='voxel':+ r=xyz[np.searchsorted(data['flat'],data['chosen']['R'])]+ ax.scatter(r[:,0]*1000,r[:,1]*1000,s=13,c='#ff9f1c',label='nominal R')+ ax.scatter(pxyz[:,0]*1000,pxyz[:,1]*1000,s=28,c='#d946ef',marker='*',label='P')+ m=result['synthetic'][name]['methods'][method]+ ax.set_title(f'{name} / {method}: P={len(p)}, p95={m["mm"]["raw"]["p95"]:.3f}mm, noise={m["noise_selected"]}')+ ax.set_xlabel('camera X [mm]');ax.set_ylabel('camera Y [mm]');ax.legend(fontsize=7)+ fig.suptitle('Stored seven fixtures only; PCA5 localization calibration and Surface: N/A',y=1.001)+ fig.tight_layout();save(fig,'synthetic.png')+++def report_blocks(result):+ b=[]+ p=lambda text:b.append(('p',text))+ h=lambda text:b.append(('h',text))+ table=lambda headers,rows:b.append(('table',(headers,rows)))+ image=lambda name,caption:b.append(('image',(name,caption)))+ fmt=lambda x:'N/A' if x is None else f'{x:.4f}'+ h('두 연구 질문에 대한 판단')+ for name,row in result['actual'].items():+ co=row['compression'];v=row['methods']['voxel'];g1=row['methods']['global1'];g0=row['methods']['global0']+ p(f'{name}: C={co["candidate_count"]} → nominal R={co["nominal_occupied"]} → P={co["priority_count"]}. '+ f'Nominal occupied/cap={co["occupied_over_32"]:.3f}배이며 {co["discarded_occupied"]}개 cell이 cap에서 제거됐다. '+ f'C→P p95는 voxel {fmt(v["spatial"]["mm"]["raw"]["p95"])}mm, 저장 Global λ=1 {fmt(g1["spatial"]["mm"]["raw"]["p95"])}mm, '+ f'λ=0 {fmt(g0["spatial"]["mm"]["raw"]["p95"])}mm다. '+ f'GT unique refs C/R/P/F={v["stages"]["C"]["unique_reference_count"]}/{v["stages"]["R"]["unique_reference_count"]}/'+ f'{v["stages"]["P"]["unique_reference_count"]}/{v["stages"]["F"]["unique_reference_count"]}다.')+ p('이번 결과는 Voxel precompression + 3D FPS cap의 첫 feasibility 평가다. 순수 Voxel Sampling이나 일반적으로 유효한 Shape-First Sampling의 검증이 아니다. '+ 'Nominal R 전체는 cap 없는 해상도 진단 집합이므로 32점 기준선과 동등 budget 성능으로 비교하지 않는다. '+ '32점 cap 뒤의 거리·local coverage와 Surface/GT trade-off를 함께 해석한다.')+ p('N_occupied>32인 물체는 원래 해상도의 모든 voxel을 최종 보존하지 못했다. '+ 'R 단계의 작은 오차와 R→P 추가 손실은 이 관측에서 예산 충돌의 크기를 보여주지만, '+ '32점이 유일한 인과적 병목이거나 더 큰 budget이 일반적인 최적값임을 증명하지 않는다. '+ '후보 오염, FPS 거리 경쟁과 anchor 이동이 남아 있다. 결과에 따른 재선택·파라미터 변경은 하지 않았다.')+ h('고정 조건·scale·실제 PCA5 지원 범위')+ p('ep000 Frame 0 / base_camera / S3 optimized PCA5 / orientation-only >20° / seed0. '+ 'Final Peg129/Box127, 총256; Priority 상한 각32/총64, structural_ratio=.25는 현재 조건이다. '+ '전체 원본 X의 camera Z median, 저장 fx=fy=256px, multiplier=1로 epsilon=z_ref*sqrt((2/fx)^2+(2/fy)^2), a=epsilon/sqrt(3)를 정했다.')+ p('PCA5 normal은 중심 ±2px 5×5 내부의 same-object 4-connected support를 사용한다. '+ 'Depth jump >.01+.02*min(z1,z2)에서 연결을 끊고, 최소6점·rank2·unique smallest eigenvector를 요구한다. '+ '불완전 patch를 허용하며 부족한 normal은 invalid다. Pair는 인접 normal을 비교해 >20°일 때 양 끝을 후보로 표시한다. '+ '두 normal support 합집합은 6×5 또는 5×6, 한 endpoint의 모든 비교 footprint는 7×7 bbox의 네 모서리를 제외한다. '+ '단순 5×5 window와 전체 반응 띠를 혼동하지 않는다.')+ p('Spatial support, 실제 edge localization error, voxel approximation error는 서로 다르다. '+ 'Nominal epsilon은 동일 depth 평면의 half-window 근사에서 정한 compression scale이며 edge 오차의 추정값·상한이 아니다. '+ '경사·깊이 불연속에서는 ���사가 깨진다. Same-cell 후보→대표점 bound sqrt(3)*a는 R 단계에서만 보장된다. '+ 'Cell을 버린 P와 2px AND 3mm matcher 통과에는 보장되지 않는다. 새 normal/score/GT calibration은 없다.')+ table(['object','X median m','epsilon mm','a nominal=used mm','R occupied','R/32','P cells','removed','P>epsilon count/fraction','dyadic a mm / ratio / cells'],[+ [name,fmt(row['scale']['z_ref_m']),fmt(row['scale']['epsilon_m']*1000),fmt(row['scale']['a_m']*1000),+ row['compression']['nominal_occupied'],fmt(row['compression']['occupied_over_32']),row['compression']['selected_occupied'],row['compression']['discarded_occupied'],+ f'{row["compression"]["above_epsilon_count"]}/{row["compression"]["candidate_count"]} ({row["compression"]["above_epsilon_fraction"]:.2%})',+ f'{row["dyadic"]["a_budget_m"]*1000:.4f} / {row["dyadic"]["ratio"]}x / {row["dyadic"]["occupied"]}'] for name,row in result['actual'].items()])+ p('실제 used/nominal ratio는 1이다. Dyadic은 nominal integer key를 음수에도 floor_divide(2)하여 만든 nested count-only 진단이다. '+ '최초 occupied≤32에서 멈췄고 그 크기를 선택에 사용하지 않았다. 임의 크기 grid의 단조성이나 정확히32 cell 존재를 가정하지 않았다. '+ '이 dyadic family의 첫 크기를 전역 최소·물리적 최적 해상도로 읽지 않는다.')+ image('resolution_budget.png','Nominal 해상도와 현재 Priority 상한; coarse 진단은 선택에 미사용')+ h('선택 규칙·anchor 이동·원본 provenance')+ p('Camera origin=(0,0,0), 원본 CV XYZ(m)의 float64 floor(XYZ/a) int64 key, half-open cell을 사용했다. '+ 'BBox 최소점으로 이동하지 않았다. Cell centroid에 가장 가까운 원본 C 하나, exact squared-distance tie는 최소 source다. '+ 'R은 source ascending, original anchor cell의 대표점을 initial로 기존 Euclidean 3D FPS cap32를 수행했다. '+ 'R≤32면 전부 사용하고 남는 예산은 전체 X의 기존 3D Surface FPS로 넘긴다. Padding·복제·좌표 평균 node는 없다.')+ table(['object','original anchor','mapped R source','3D shift mm','delta(u,v) px','pixel shift px'],[+ [name,row['anchor']['original_source'],row['anchor']['mapped_source'],fmt(row['anchor']['distance_m']*1000),+ str(row['anchor']['delta_pixel_uv']),fmt(row['anchor']['pixel_distance_px'])] for name,row in result['actual'].items()])+ p('Anchor source가 바뀌면 grouping/precompression과 FPS 시작점 효과가 함께 달라진다. '+ '추가 anchor-only arm은 실행하지 않았으므로 두 효과를 인과적으로 분해하지 않는다. '+ 'C 전체 optimized score가 저장돼 있지 않아 score-free만 사용했다. Task02 reference PCA5 angle을 optimized score로 대체하지 않았다.')+ image('primary_selection.png','PCA5 원본 C / nominal 대표점 R / 실제 Priority P와 Surface S=Final F')+ h('Primary: 압축 오차와 budget 추가 손실')+ table(['object','distance (mm)','mean','p50','p95','max','worst source'],[+ [name,key,*[fmt(row['compression'][key][k]) for k in ('mean','p50','p95','max')],row['compression'][key]['worst']['source']]+ for name,row in result['actual'].items() for key in ('same_cell_m','C_to_R_m','C_to_P_m','budget_extra_m')])+ p('same_cell은 자기 cell의 대표점 거리, C→R은 모든 대표점 중 최근접 거리다. '+ 'Budget extra=C→P−C→R≥0이며 same_cell을 빼지 않았다. 네 raw 배열, ECDF와 worst source/XYZ/pixel을 NPZ/JSON에 저장했다. '+ 'Same-cell bound 확인과 성능 개선은 별개다.')+ table(['object','method','P','C→P mean/p50/p95/max mm','X→F mean/p95/max mm','Final unique GT refs'],[+ [name,method,m['stages']['P']['node_count'],' / '.join(fmt(m['spatial']['mm']['raw'][k]) for k in ('mean','p50','p95','max')),+ ' / '.join(fmt(m['surface_mm'][k]) for k in ('mean','p95','max')),m['stages']['F']['unique_reference_count']]+ for name,row in result['actual'].items() for method,m in row['methods'].items()])+ table(['object','method','UV selected/occupied; P=0 IDs','XYZ selected/occupied; P=0 IDs','UV equal-region mean p95 mm'],[+ [name,method,*[f'{g["candidate_occupied_regions"]-len(g["empty_priority_region_ids"])}/{g["candidate_occupied_regions"]}; {g["empty_priority_region_ids"]}'+ for g in (m['spatial']['grids']['uv'],m['spatial']['grids']['xyz'])],fmt(m['spatial']['grids']['uv']['equal_region_mean_p95_mm'])]+ for name,row in result['actual'].items() for method,m in row['methods'].items()])+ p('독립 UV4×4/XYZ 최대2×2×2 구역은 같은 X bbox로 고정했다. 구역별 후보 밀도·선택률·거리 tail과 R 단계 구역 통계는 JSON/NPZ에 있다. '+ 'Box의 30.726m outlier는 그대로 남아 coarse XYZ 구역과 bbox 정규화를 왜곡하므로 raw mm와 UV를 함께 본다. '+ '단순 구역 점유가 같아도 국소 geometry가 같다는 뜻은 아니다.')+ image('primary_distances.png','Same-cell / C→R / C→P / budget extra ECDF와 저장 FPS 비교')+ h('Secondary: 선택 후 GT, C/R/P/S/F reference 손실')+ p('Same-pair ≤2px AND ≤3mm를 유지했다. Peg observed462/visible464, Box observed103/visible103이다. '+ '한 node는 여러 reference를 덮고 한 reference는 여러 node에 매칭될 수 있다. Pair count·matching node·unique reference는 서로 다르다.')+ table(['object','voxel stage','nodes','matching nodes','unique refs','available/unavailable feature rows'],[+ [name,stage,m['node_count'],m['matching_node_count'],m['unique_reference_count'],f'{m["feature_available_count"]}/{m["feature_unavailable_count"]}']+ for name,row in result['actual'].items() for stage,m in row['methods']['voxel']['stages'].items()])+ table(['object','C→R lost refs','R→P additional lost refs','Surface added refs','P/S overlapping refs'],[+ [name,*[row['methods']['voxel']['reference_differences'][key]['count'] for key in ('C_minus_R','R_minus_P','F_minus_P','P_intersect_S')]]+ for name,row in result['actual'].items()])+ table(['Box segment','reference count','C','R','P','S','F','Global λ1 P/F','Global λ0 P/F'],[+ [label,seg['reference_count'],*[result['actual']['box']['methods']['voxel']['stages'][stage]['segments'][label]['unique_reference_count'] for stage in ('C','R','P','S','F')],+ *[' / '.join(str(result['actual']['box']['methods'][method]['stages'][stage]['segments'][label]['unique_reference_count']) for stage in ('P','F')) for method in ('global1','global0')]]+ for label,seg in result['actual']['box']['methods']['voxel']['stages']['C']['segments'].items()])+ p('각 단계 reference ID 집합·joint pairs·matching source·구간별 matching node/reference·Box line spacing을 저장했다. '+ 'Surface 추가분은 refs(F)−refs(P)이며 S 전체 hit 수와 다르다. C→R과 R→P 손실은 P⊆R⊆C에서 구분했다. '+ 'Peg 물리적 line 순서/간격은 N/A다. GT 후보→reference 거리에는 depth noise, reference 이산화, 가시성·matcher 정의가 섞여 '+ '순수 detector localization error가 아니다. 이를 epsilon calibration에 사용하지 않았다.')+ image('peg_gt.png','Peg seam: C/R/P/S/F coverage와 압축/예산 손실')+ image('box_gt.png','Box rim: C/R/P/S/F coverage와 압축/예산 손실')+ h('Depth·ROI·일반 Surface trade-off')+ table(['object','stage','depth median/p95/max m','negative union count / nodes'],[+ [name,stage,' / '.join(fmt(row['methods']['voxel']['occupancy']['depth_m'][stage][k]) for k in ('median','p95','max')),+ f'{row["methods"]["voxel"]["occupancy"]["negative_roi"]["known_negative_union"][stage]["count"]} / '+ f'{row["methods"]["voxel"]["occupancy"]["negative_roi"]["known_negative_union"][stage]["fraction_of_path"]["denominator"]}']+ for name,row in result['actual'].items() for stage in ('X','C','R','P','S','F')])+ p('원거리 positive depth를 제거하지 않았다. ROI는 중첩되므로 union을 별도 집계했다. '+ 'ROI/far는 실제 noise 정답이 아니며 일반 Surface 점유를 자동 오선택으로 분류하지 않는다. '+ 'X median/p95 기반 depth bands와 candidate별 P 선택률도 저장했다. '+ 'Median은 단일 extreme max 영향은 줄이지만 mask 오염과 물체 내 depth 차이를 해결하지 않는다. '+ 'Peg/Box는 같은 공식으로 서로 다른 metric a를 사용하며 동일 절대 해상도 비교가 아니다.')+ image('depth_roi_surface.png','원본 depth tail, 기존 negative union, 전체 X→F Surface 비교')+ h('기존 7개 synthetic의 저장 입력 재사용')+ table(['fixture','C/R/P','a mm','dyadic ratio','Global/UV/Voxel C→P p95 mm','Global/UV/Voxel ref→P p95 mm','noise P G/UV/V'],[+ [name,f'{row["compression"]["candidate_count"]}/{row["compression"]["nominal_occupied"]}/{row["compression"]["priority_count"]}',+ fmt(row['scale']['a_m']*1000),row['dyadic']['ratio'],+ ' / '.join(fmt(row['methods'][m]['mm']['raw']['p95']) for m in ('global0','uv','voxel')),+ ' / '.join(fmt(row['methods'][m]['reference_mm']['p95']) for m in ('global0','uv','voxel')),+ ' / '.join(str(row['methods'][m]['noise_selected']) for m in ('global0','uv','voxel'))]+ for name,row in result['synthetic'].items()])+ p('Task03-F 저장 C/source/XYZ와 Global/UV 선택을 읽었으며 새 fixture·기준선 FPS를 만들지 않았다. '+ 'Dense X가 없는 stress test에서 관측 C median과 기존 focal1600px로 같은 scale 공식을 적용했다. '+ 'Annotation은 모든 선택 저장 후에만 noise/reference/구조별 평가에 사용했다. '+ '실제 PCA5 5×5 localization uncertainty calibration과 Synthetic Surface는 N/A다. '+ '계약/geometry stress test 통과가 uncertainty calibration ��당성을 뜻하지 않는다.')+ image('synthetic.png','기존 일곱 fixture의 저장 Global/UV와 단일 voxel precompression control')+ h('검증·재현·한계·완료 범위')+ p(f'실행 UUID {result["run_id"]}. 필수 계약 테스트: {result["tests_summary"]}. '+ '성능 개선을 PASS 조건으로 두지 않았다. selection_before_gt.npz를 real/synthetic 선택 전체의 저장·readback·hash 이후에만 '+ 'GT evaluator/annotation에 연결했다. 평가 후 선택 hash 불변, 원본 C/X·baseline exact alignment, 원본 feature available-only exact gather를 확인했다.')+ p('기존 ExperimentLogger(team=visual, job_type=evaluate), WANDB_MODE=disabled 및 로컬 artifact inventory를 재사용했다. '+ '기존 UUID/project/group 규칙을 바꾸지 않았다. Git 시작 상태는 dirty이며 source snapshot·input/artifact hashes·시작 diff·implementation diff를 함께 보존했다. '+ 'Production sampling/normal/tracking/shared simulator와 기존 dirty/untracked 파일은 변경하지 않았다. '+ '같은 S3 조건에서 저장된 feature가 없는 source는 unavailable로 남겼으며 feature를 추정하지 않았다.')+ p('CPU NumPy/SciPy offline 실행이다. 단계별 wall time은 JSON에 기록했으며 Graph/GNN 20Hz 성능을 주장하지 않는다. '+ 'Simulator/renderer/CUDA/MPS/GPU/PCL, 새 episode/fixture/score/normal, threshold/scale sweep, 두 번째 selection arm, '+ 'GT calibration/quota, depth filtering, ratio/Adaptive Budget, Graph/GNN/BC, dependency 설치·외부 업로드·Git commit은 미실행이다. '+ 'Task03-H의 동일 count 기대 coverage는 후보 해석 근거, Task03-F/G는 기존 실패 비교군으로만 유지했다. '+ '보고서 제출 후 추가 알고리즘 실행 없이 중단한다.')+ return b+++def write_reports(output,result):+ blocks=report_blocks(result);relative='../../experiments/'+output.name+'/'+ artifacts=[STEM+'.html',STEM+'.json',STEM+'.npz','selection_before_gt.npz','selection_before_gt.json',+ 'verification.json','tests.log','source_hashes.json','preregistered_config.json','implementation.patch','git_start.diff']+ md=['# Task03-I — Shape-First Voxel Precompression + 3D FPS Cap','',+ ' · '.join(f'[{f}]({relative+f})' for f in artifacts),'',+ '[승인 계획](03i_voxel_structural_sampling_plan.md) · [Task03-H](03h_candidate_count_matched.md) · '+ '[Task03-F](03f_local_structural_sampling.md) · [Task03-G](03g_geometry_aware_sampling.md)','']+ page=['<!doctype html><html lang="ko"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">',+ '<title>Task03-I — Voxel precompression + FPS cap</title><style>body{font:16px/1.65 system-ui,sans-serif;background:#f4f6f9;color:#17212e;margin:auto;max-width:1450px;padding:30px}h1,h2{line-height:1.25}h2{margin-top:2.5em;border-bottom:2px solid #cbd5e1;padding-bottom:12px}p{max-width:1150px}table{border-collapse:collapse;width:100%;font-size:14px;background:white}td,th{border:1px solid #cbd5e1;padding:9px;text-align:left}th{background:#e2e8f0}tr:nth-child(even){background:#f8fafc}.scroll{overflow:auto}img{width:100%;height:auto;background:white;border:1px solid #cbd5e1}figure{margin:25px 0}figcaption{color:#475569}a{color:#155eab}nav{padding:18px;background:#e0f2fe}code,pre{overflow:auto}</style>',+ '<h1>Task03-I — Shape-First Voxel Precompression + 3D FPS Cap</h1>',+ f'<nav>Run {output.name}<br><a href="../../docs/visual-graph-integration/03i_voxel_structural_sampling.md">결과 Markdown</a> · '+ '<a href="../../docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md">승인 계획</a><br>'+ ' · '.join(f'<a href="{f}">{f}</a>' for f in artifacts if not f.endswith('.html'))+'</nav>']+ for kind,value in blocks:+ if kind=='h':md.extend(['## '+value,'']);page.append('<h2>'+html.escape(value)+'</h2>')+ elif kind=='p':md.extend([value,'']);page.append('<p>'+html.escape(value)+'</p>')+ elif kind=='image':+ filename,caption=value;md.extend([f'',''])+ page.append(f'<figure><a href="{filename}"><img src="{filename}" alt="{html.escape(caption)}"></a><figcaption>{html.escape(caption)}</figcaption></figure>')+ else:+ headers,rows=value+ esc=lambda x:str(x).replace('|','/').replace('\n',' ')+ md.extend(['| '+' | '.join(map(esc,headers))+' |','| '+' | '.join(['---']*len(headers))+' |'])+ md.extend('| '+' | '.join(map(esc,row))+' |' for row in rows);md.append('')+ page.append('<div class="scroll"><table><thead><tr>'+''.join('<th>'+html.escape(str(v))+'</th>' for v in headers)+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+html.escape(str(v))+'</td>' for v in row)+'</tr>' for row in rows)+'</tbody></table></div>')+ page.append('<pre id="browser-check">pending</pre><script>addEventListener("load",()=>{document.getElementById("browser-check").textContent=JSON.stringify(Array.from(document.images).map(i=>({src:i.getAttribute("src"),complete:i.complete,width:i.naturalWidth,height:i.naturalHeight})));});</script></html>')+ REPORT.write_text('\n'.join(md));(output/(STEM+'.html')).write_text('\n'.join(page))+++def verify_documents(output):+ class Links(HTMLParser):+ def __init__(self):super().__init__();self.targets=[]+ def handle_starttag(self,tag,attrs):self.targets.extend(v for k,v in attrs if k in ('href','src'))+ parser=Links();page=(output/(STEM+'.html')).read_text();parser.feed(page)+ if re.search(r'<script[^>]+src=|\bfetch\s*\(|https?://',page):raise AssertionError('external/dynamic HTML dependency')+ for target in parser.targets:+ if Path(target).is_absolute() or not (output/target).is_file():raise AssertionError('bad HTML link '+target)+ mdlinks=re.findall(r'\]\(([^)]+)\)',REPORT.read_text())+ for target in mdlinks:+ if Path(target).is_absolute() or not (REPORT.parent/target).is_file():raise AssertionError('bad Markdown link '+target)+ decoded={}+ for filename in FIGURES:+ a=plt.imread(output/filename)+ if min(a.shape[:2])<400 or not np.isfinite(a).all() or a.std()<.01:raise AssertionError('bad PNG '+filename)+ decoded[filename]=list(a.shape)+ return dict(status='PASS',html_relative_links=len(parser.targets),markdown_relative_links=len(mdlinks),png_decoded=decoded,+ static_no_cdn_no_fetch=True)+++def preserved(baseline):+ current={p:prior.sha(Path(p)) for p in baseline['hashes']}+ require_equal(current,baseline['hashes'],'protected original hashes')+ require_equal(subprocess.check_output(['git','rev-parse','HEAD'],cwd=REPO,text=True).strip(),baseline['head'],'HEAD unchanged')+ return dict(status='PASS',protected_file_count=len(current),all_sha256_unchanged=True,HEAD_unchanged=True)+++def run(baseline_path):+ if REPORT.exists():raise FileExistsError('existing result report; refusing overwrite')+ if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required')+ baseline=json.loads(baseline_path.read_text());preserved(baseline)+ source_paths=sorted(set([Path(__file__),Path(__file__).with_name('test_voxel_structural_sampling.py'),PLAN,+ *[p for p in (REPO/'visual/runtime').rglob('*.py')],REPO/'utils/experiment_logger.py',REPO/'utils/experiment_artifacts.py']))+ source_hash=prior.hashes(source_paths)+ config=dict(task='03-I',rules=RULES,source_sha256=source_hash,protected_baseline_sha256=prior.sha(baseline_path),+ source_run_id=prior.SOURCE_RUN,baseline_run_id=local.BASELINE_ID,fixture_run_id=FIXTURE_RUN.name,+ python=platform.python_version(),numpy=np.__version__,platform=platform.platform(),device='cpu',+ simulator_executed=False,gpu_executed=False,baseline_FPS_executed=False,production_policy_adopted=False)+ with ExperimentLogger(team='visual',config=config,seed=0,model='task03i_voxel_precompression_3d_fps_cap',job_type='evaluate') as logger:+ output=logger.directory+ def registered(path,kind='reports'):logger.link_output(path,kind=kind)+ try:+ write_json(output/'git_start.json',dict(head=baseline['head'],status=baseline['git_status']))+ (output/'git_start.diff').write_text(baseline['git_diff'])+ shutil.copyfile(baseline_path,output/'protected_baseline.json')+ write_json(output/'preregistered_config.json',config);config_sha=prior.sha(output/'preregistered_config.json')+ for path in source_paths:+ dest=output/'source_snapshot'/path.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,dest)+ for filename in ('git_start.json','git_start.diff','protected_baseline.json','preregistered_config.json'):registered(output/filename)+ with (output/'tests.log').open('w') as log:+ process=subprocess.run([sys.executable,'-m','unittest',*TESTS,'-v'],cwd=REPO,stdout=log,stderr=subprocess.STDOUT)+ registered(output/'tests.log')+ if process.returncode:raise RuntimeError('required contracts failed; no real selection performed')+ tests=(output/'tests.log').read_text();summary=next(s for s in tests.splitlines() if s.startswith('Ran '))+'; '+tests.splitlines()[-1]+ print(summary,flush=True)+ frame,geometry,samples,cases,zero,old,input_config,contracts=local.load_actual()+ baselines=load_baselines(cases,zero,samples)+ selections={}+ for name,case in cases.items():+ selections[name]=select(case['candidate_flat'],case['candidate_xyz'],case['support_flat'],case['support_xyz'],+ frame.depth.shape,frame.intrinsic,case['seed'],case['first'],case['budget'])+ check_selection(case,selections[name])+ require_equal(sum(len(s['F']) for s in selections.values()),256,'total Final budget')+ synthetic=load_synthetic_observations()+ selection_sha,selection_data=freeze_selection(output,cases,selections,synthetic)+ registered(output/'selection_before_gt.npz')+ write_json(output/'selection_before_gt.json',dict(sha256=selection_sha,gt_connected=False,+ actual={name:dict(scale=s['scale'],dyadic=s['dyadic'],anchor=s['grouping']['anchor'],+ counts={k:len(s[k]) for k in ('R','P','S','F')}) for name,s in selections.items()},+ synthetic={name:dict(scale=s['chosen']['scale'],anchor=s['chosen']['grouping']['anchor']) for name,s in synthetic.items()}))+ registered(output/'selection_before_gt.json')+ print('All selections frozen before GT:',output.name,flush=True)+ t0=perf_counter()+ actual,synth_result,arrays,contexts=evaluate_after_freeze(output,selection_sha,frame,geometry,samples,cases,selections,baselines,synthetic,input_config)+ result=dict(run_id=logger.run_id,config=config,tests_summary=summary,actual=actual,synthetic=synth_result,+ selection_before_gt_sha256=selection_sha,evaluation_ms=(perf_counter()-t0)*1000,source_contract=contracts,+ real_FPS_calls=dict(baseline=0,priority_cap=sum(len(s['R'])>32 for s in selections.values()),surface=2),+ synthetic_FPS_calls=dict(baseline=0,priority_cap=sum(len(d['chosen']['R'])>32 for d in synthetic.values())),+ policy_adopted=False)+ arrays.update(selection_data)+ np.savez_compressed(output/(STEM+'.npz'),**arrays);registered(output/(STEM+'.npz'))+ with np.load(output/(STEM+'.npz'),allow_pickle=False) as saved:+ for key,value in arrays.items():np.testing.assert_array_equal(saved[key],value,err_msg=key)+ write_json(output/(STEM+'.json'),result);registered(output/(STEM+'.json'),'metrics')+ plot_results(output,frame,cases,selections,result,arrays,synthetic,contexts)+ for filename in FIGURES:registered(output/filename)+ preservation=preserved(baseline)+ require_equal(prior.hashes(source_paths),source_hash,'executed source hashes')+ require_equal(prior.sha(output/'preregistered_config.json'),config_sha,'frozen config')+ require_equal(prior.sha(output/'selection_before_gt.npz'),selection_sha,'frozen selection after evaluation')+ write_json(output/'source_hashes.json',dict(sources_before=source_hash,sources_after=prior.hashes(source_paths),+ protected_before=baseline['hashes'],protected_after={p:prior.sha(Path(p)) for p in baseline['hashes']},preservation=preservation))+ registered(output/'source_hashes.json')+ patch_text=''+ for path in (Path(__file__),Path(__file__).with_name('test_voxel_structural_sampling.py')):+ patch_text+=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,capture_output=True,text=True).stdout+ (output/'implementation.patch').write_text(patch_text);registered(output/'implementation.patch')+ verification=dict(status='pending report verification',required_tests=dict(summary=summary,modules=TESTS,+ pass_count=sum(' ... ok' in line for line in tests.splitlines()),fail_count=0,skip_count=sum(' ... skipped' in line for line in tests.splitlines())),+ baseline_exact=True,C_X_source_XYZ_exact=True,P_subset_R_subset_C_subset_X=True,no_padding_duplicates=True,+ fixed_origin_floor=True,centroid_representatives_original_only=True,variable_P_contract=True,dyadic_nested_counts=True,+ pre_GT_saved_readback_hash=selection_sha,selection_hash_unchanged_after_GT=True,feature_exact_available_only=True,+ same_pair_2px_AND_3mm=True,source_preservation=preservation,config_sha256=config_sha,NPZ_exact_readback=True,+ simulator_executed=False,gpu_executed=False,performance_improvement_is_PASS_condition=False,+ source_snapshots='source_snapshot/',static_browser_loading='pending')+ write_json(output/'verification.json',verification)+ write_reports(output,result)+ verification['documents']=verify_documents(output)+ verification['status']='PASS; static browser loading pending'+ write_json(output/'verification.json',verification);registered(output/'verification.json')+ registered(output/(STEM+'.html'));registered(REPORT)+ write_json(output/'git_end.json',dict(status=subprocess.check_output(['git','status','--short'],cwd=REPO,text=True),preservation=preserved(baseline)))+ registered(output/'git_end.json')+ logger.log({name:dict(compression=row['compression'],surface=row['methods']['voxel']['surface_mm']) for name,row in actual.items()},step=0,prefix='eval')+ print(output,flush=True)+ except Exception as exc:+ write_json(output/'attempt_failure.json',dict(error_type=type(exc).__name__,message=str(exc),real_selection_saved=(output/'selection_before_gt.npz').exists()))+ registered(output/'attempt_failure.json');raise+ return output+++def main():+ parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--baseline',type=Path,required=True)+ args=parser.parse_args();run(args.baseline)+++if __name__=='__main__':main()diff --git a/visual/runtime/test/test_voxel_structural_sampling.py b/visual/runtime/test/test_voxel_structural_sampling.pynew file mode 100644index 0000000..b30a072--- /dev/null+++ b/visual/runtime/test/test_voxel_structural_sampling.py@@ -0,0 +1,214 @@+"""Task03-I contracts. Performance improvement is not a PASS condition."""+import copy+import inspect+from pathlib import Path+import tempfile+from types import SimpleNamespace+import unittest+from unittest.mock import patch++import numpy as np++from visual.runtime.test import run_voxel_structural_sampling as voxel+from visual.runtime.sampling import fps_indices+from visual.runtime.geometry import OrganizedGeometry+from visual.runtime.test.sampling_evaluation import CoverageMatcher+++def case(n=100):+ flat=np.arange(n,dtype=np.int64)+ xyz=np.column_stack((flat*.01,np.sin(flat)*.002,np.ones(n))).astype(np.float32)+ return dict(candidate_flat=flat[::2],candidate_xyz=xyz[::2].copy(),support_flat=flat,+ support_xyz=xyz,shape=(10,10),intrinsic=np.diag([100.,100.,1.]),seed=47,anchor=0,final_target=64)+++class GridTests(unittest.TestCase):+ def test_fixed_origin_negative_floor_and_boundaries(self):+ q=np.array([[-1.1,-1.,-.1],[0.,1.,1.1],[np.nextafter(1.,0),np.nextafter(1.,2),-0.]])+ np.testing.assert_array_equal(voxel.voxel_keys(q,1.),[[-2,-1,-1],[0,1,1],[0,1,0]])+ # Adding a distant observation never recentres existing cells.+ np.testing.assert_array_equal(voxel.voxel_keys(np.vstack([q,[1000,1000,1]]),1.)[:-1],voxel.voxel_keys(q,1.))++ def test_representative_centroid_is_not_output_and_tie_source(self):+ flat=np.array([2,4,7],np.int64);xyz=np.array([[.125,.125,.125],[.375,.125,.125],[1.5,.125,.125]])+ g=voxel.representatives(flat,xyz,1.)+ np.testing.assert_array_equal(flat[g['representative_rows']],[2,7])+ np.testing.assert_array_equal(g['same_representative_source'],[2,2,7])+ self.assertNotIn(.2,xyz[g['representative_rows'],0])+ np.testing.assert_array_equal(g['capacity'],[2,1])++ def test_coincident_xyz_sources_collapse_without_duplicate(self):+ g=voxel.representatives(np.array([1,3,5]),np.ones((3,3)),1.)+ np.testing.assert_array_equal(g['representative_rows'],[0])+ np.testing.assert_array_equal(g['same_cell_distance_m'],0.)++ def test_determinism_input_unchanged_and_bound(self):+ c=case();snapshot=copy.deepcopy(c)+ a=voxel.select(**c);b=voxel.select(**c)+ for key in ('R','P','F','xyz'): np.testing.assert_array_equal(a[key],b[key])+ for key,value in c.items():+ if isinstance(value,np.ndarray):np.testing.assert_array_equal(value,snapshot[key])+ self.assertLessEqual(a['grouping']['same_cell_distance_m'].max(),a['scale']['epsilon_m']+1e-12)++ def test_invalid_grid_and_source_inputs_fail_closed(self):+ for a in (0,-1,np.inf,np.nan):+ with self.assertRaises(ValueError):voxel.voxel_keys(np.ones((1,3)),a)+ for xyz in (np.array([[np.nan,1,1]]),np.array([[2.**63,0,0]]),np.array([[-2.**64,0,0]])):+ with self.assertRaises(ValueError):voxel.voxel_keys(xyz,1.)+ for flat in (np.array([1,1]),np.array([2,1]),np.array([-1,2]),np.array([1.,2.])):+ with self.assertRaises(ValueError):voxel.representatives(flat,np.ones((2,3)),1.)++ def test_scale_median_robust_to_extreme_max_and_uses_only_X(self):+ x=np.array([[0,0,1],[0,0,2],[0,0,30.726]])+ s=voxel.nominal_scale(x,np.diag([256.,128.,1.]))+ self.assertEqual(s['z_ref_m'],2.)+ self.assertAlmostEqual(s['epsilon_m'],2*np.hypot(2/256,2/128))+ self.assertAlmostEqual(s['a_m']*np.sqrt(3),s['epsilon_m'])+ self.assertEqual(voxel.nominal_scale(np.empty((0,3)),np.eye(3))['status'],'N/A')+ for x,k in ((np.array([[0,0,-1]]),np.eye(3)),(x,np.diag([0,1,1]))):+ with self.assertRaises(ValueError):voxel.nominal_scale(x,k)++ def test_dyadic_parent_nesting_first_count_and_nonexact32(self):+ keys=np.column_stack((np.arange(-40,40),np.zeros(80,int),np.zeros(80,int))).astype(np.int64)+ d=voxel.dyadic_counts(keys,.01)+ self.assertEqual([v['occupied'] for v in d['levels']],[80,40,20])+ self.assertEqual(d['ratio'],4);self.assertFalse(d['used_for_selection'])+ self.assertEqual(voxel.dyadic_counts(keys,.01,0)['status'],'impossible')+ self.assertEqual(voxel.dyadic_counts(np.empty((0,3),np.int64),.01)['occupied'],0)++ def test_dyadic_signed_int64_extremes_terminate(self):+ vals=np.array([np.iinfo(np.int64).min,np.iinfo(np.int64).max],np.int64)+ keys=np.array(np.meshgrid(vals,vals,vals)).reshape(3,-1).T+ d=voxel.dyadic_counts(keys,.001)+ self.assertLessEqual(d['occupied'],32)+ # General, non-nested voxel sizes do not imply monotone cell counts.+ xyz=np.array([[.9,0,0],[1.1,0,0],[1.9,0,0]])+ self.assertEqual(len(np.unique(voxel.voxel_keys(xyz,1.),axis=0)),2)+++class SelectionTests(unittest.TestCase):+ def test_more_equal_fewer_occupied_and_zero_cap(self):+ for n in (0,1,10,32,45):+ flat=np.arange(n,dtype=np.int64);xyz=np.column_stack((flat*2.,flat*0,flat*0+1))+ g=voxel.choose_priority(flat,xyz,1.,47,0 if n else None,32,(10,10))+ self.assertEqual(len(g['P']),min(n,32));self.assertEqual(len(g['R']),n)+ self.assertLessEqual(len(np.unique(g['P'])),32)+ if n<=32: np.testing.assert_array_equal(np.sort(g['P']),flat)+ z=voxel.choose_priority(flat,xyz,1.,47,0,0)+ self.assertEqual(len(z['P']),0)++ def test_anchor_maps_to_representative_records_distance_pixels(self):+ f=np.array([0,1,2],np.int64);x=np.array([[.1,0,1],[.2,0,1],[.4,0,1]])+ g=voxel.choose_priority(f,x,1.,0,0,32,(1,3))+ self.assertEqual(g['anchor']['original_source'],0);self.assertEqual(g['anchor']['mapped_source'],1)+ self.assertAlmostEqual(g['anchor']['distance_m'],.1)+ self.assertEqual(g['anchor']['delta_pixel_uv'],[1,0]);self.assertEqual(g['anchor']['pixel_distance_px'],1)+ np.testing.assert_array_equal(g['P'],[1])++ def test_cap_reuses_existing_3d_fps_and_exact_source(self):+ c=case();c['intrinsic']=np.diag([10000.,10000.,1.])+ with patch.object(voxel,'fps_indices',wraps=fps_indices) as spy:+ s=voxel.select(**c)+ self.assertEqual(spy.call_count,2)+ rxyz=c['candidate_xyz'][np.searchsorted(c['candidate_flat'],s['R'])]+ np.testing.assert_array_equal(spy.call_args_list[0].args[0],rxyz)+ self.assertEqual(spy.call_args_list[0].kwargs['initial'],[int(np.searchsorted(s['R'],s['grouping']['anchor']['mapped_source']))])+ np.testing.assert_array_equal(s['F'][:len(s['P'])],s['P'])+ np.testing.assert_array_equal(s['xyz'],c['support_xyz'][np.searchsorted(c['support_flat'],s['F'])])+ self.assertTrue(set(s['P'])<=set(s['R'])<=set(c['candidate_flat'])<=set(c['support_flat']))+ self.assertEqual(len(s['F']),len(np.unique(s['F'])))++ def test_underfill_surface_empty_candidate_small_support_and_empty(self):+ for n,nc in ((10,2),(10,0),(0,0)):+ c=case(n);c['candidate_flat']=c['support_flat'][:nc];c['candidate_xyz']=c['support_xyz'][:nc]+ c['anchor']=0 if nc else None+ s=voxel.select(**c)+ self.assertEqual(len(s['F']),n);self.assertLessEqual(len(s['P']),nc)+ self.assertEqual(len(s['S']),n-len(s['P']));self.assertEqual(s['shortfall'],64-n)++ def test_invalid_membership_coordinates_anchor_target(self):+ c=case();c['candidate_xyz'][0,0]=42+ with self.assertRaises(AssertionError):voxel.select(**c)+ c=case();c['anchor']=99+ with self.assertRaises(ValueError):voxel.select(**c)+ c=case();c['final_target']=-1+ with self.assertRaises(ValueError):voxel.select(**c)++ def test_decomposition_nn_extra_and_ties(self):+ c=case();s=voxel.select(**c)+ metrics,a=voxel.distance_decomposition(c['candidate_flat'],c['candidate_xyz'],s,c['shape'])+ self.assertTrue((a['budget_extra_m']>=-1e-12).all())+ np.testing.assert_allclose(a['C_to_R_m']+a['budget_extra_m'],a['C_to_P_m'])+ self.assertTrue((a['C_to_R_m']<=a['same_cell_m']+1e-12).all())+ d,near=voxel.nearest_sources(np.array([[0.,0,1]]),np.array([9,1]),np.array([[1,0,1],[-1,0,1]]))+ self.assertEqual(near[0],1);self.assertEqual(d[0],1)+ self.assertEqual(metrics['nominal_occupied']-metrics['selected_occupied'],metrics['discarded_occupied'])++ def test_empty_P_distance_is_missing_not_zero(self):+ c=case();g=voxel.choose_priority(c['candidate_flat'],c['candidate_xyz'],.01,0,0,0,c['shape'])+ s=dict(grouping=g,R=g['R'],P=g['P'],scale=dict(epsilon_m=.01,a_m=.01))+ row,a=voxel.distance_decomposition(c['candidate_flat'],c['candidate_xyz'],s,c['shape'])+ self.assertIsNone(row['C_to_P_m']['mean']);self.assertEqual(row['C_to_P_m']['missing_count'],50)+ self.assertTrue(np.isnan(a['C_to_P_m']).all())+++class EvaluationContracts(unittest.TestCase):+ def test_selection_signature_has_no_annotations_and_freeze_before_GT(self):+ forbidden=('gt','roi','pose','score','label','reference','annotation')+ for f in (voxel.select,voxel.choose_priority,voxel.representatives,voxel.nominal_scale):+ self.assertFalse(any(bad in p.lower() for p in inspect.signature(f).parameters for bad in forbidden))+ c=case();s=voxel.select(**c)+ case_data=dict(c,budget=64)+ with tempfile.TemporaryDirectory() as temp,patch.object(voxel.prior,'evaluation_inputs',side_effect=AssertionError('GT forbidden')):+ sha,arrays=voxel.freeze_selection(Path(temp),{'peg':case_data},{'peg':s},{})+ self.assertEqual(voxel.prior.sha(Path(temp)/'selection_before_gt.npz'),sha)+ self.assertIn('peg/R',arrays)+ with self.assertRaises(FileExistsError):voxel.freeze_selection(Path(temp),{'peg':case_data},{'peg':s},{})++ def test_available_feature_exact_gather_variable_priority(self):+ c=dict(saved_flat=np.array([1,3,7]),saved_features={'score':np.array([.1,.3,.7]),'normal_valid':np.array([True,False,True])})+ mask,pos,fields=voxel.prior.feature_rows(c,np.array([3,4,1,9]))+ np.testing.assert_array_equal(mask,[True,False,True,False]);np.testing.assert_array_equal(pos,[0,2])+ np.testing.assert_array_equal(fields['score'],[.3,.1]);np.testing.assert_array_equal(fields['normal_valid'],[False,True])++ def test_GT_stage_unique_node_reference_same_pair_and_subset_losses(self):+ xyz=np.array([[[0,0,1],[.001,0,1],[.002,0,1]]],np.float32)+ geometry=OrganizedGeometry(xyz,np.ones((1,3),bool),{0:np.ones((1,3),bool)},np.zeros((1,3),bool))+ reference=(np.array([[0,0],[1,0],[2,0]]),xyz.reshape(-1,3).copy())+ matcher=CoverageMatcher(geometry,0,reference)+ context=dict(matcher=matcher,reference=reference,observable=np.ones(3,bool))+ row,arrays=voxel.stage_gt(np.array([0]),context,np.array(['a']*3),{},None)+ self.assertEqual(row['matching_node_count'],1);self.assertEqual(row['unique_reference_count'],3)+ self.assertEqual(len(arrays['joint_reference_id']),3)+ bad=CoverageMatcher(geometry,0,(np.array([[0,0],[99,0]]),np.array([[0,0,2],[0,0,1]])))+ context.update(matcher=bad,reference=(bad.ref_uv,bad.ref_xyz),observable=np.ones(2,bool))+ row,_=voxel.stage_gt(np.array([0]),context,np.array(['a','a']),{},None)+ self.assertEqual(row['unique_reference_count'],0)++ def test_variable_P_adapter_and_separate_reference_losses(self):+ flat=np.array([0,3,6],np.int64);xyz=np.zeros((1,7,3),np.float32)+ xyz[0,flat]=np.column_stack((np.arange(3)*.01,np.zeros(3),np.ones(3)))+ support=np.zeros((1,7),bool);support[0,flat]=True+ geometry=OrganizedGeometry(xyz,support,{0:support},np.zeros_like(support))+ reference=(np.column_stack((flat,np.zeros(3))),xyz[0,flat])+ matcher=CoverageMatcher(geometry,0,reference)+ context=dict(matcher=matcher,reference=reference,observable=np.ones(3,bool),negatives={'test':np.zeros_like(support)})+ c=dict(candidate_flat=flat,candidate_xyz=xyz[0,flat],support_flat=flat,support_xyz=xyz[0,flat],+ saved_flat=flat,saved_features={'test_feature':np.arange(3)},oid=0)+ chosen=dict(R=flat[:2],P=flat[:1],S=flat[2:],F=flat[[0,2]],xyz=xyz[0,flat[[0,2]]])+ arrays={};row=voxel.evaluate_method(c,chosen,context,SimpleNamespace(depth=np.ones((1,7))),np.array(['a']*3),{},None,arrays,'test')+ self.assertEqual([row['stages'][k]['unique_reference_count'] for k in ('C','R','P','S','F')],[3,2,1,1,2])+ self.assertEqual(row['reference_differences']['C_minus_R']['reference_ids'],[2])+ self.assertEqual(row['reference_differences']['R_minus_P']['reference_ids'],[1])+ self.assertEqual(row['reference_differences']['F_minus_P']['reference_ids'],[2])+ np.testing.assert_array_equal(arrays['test/F_selection_role'],['Priority','Surface'])++ def test_protected_hash_failure_is_not_ignored(self):+ with tempfile.TemporaryDirectory() as temp:+ p=Path(temp)/'original';p.write_bytes(b'original')+ baseline=dict(hashes={str(p):voxel.prior.sha(p)},head='unused')+ p.write_bytes(b'changed')+ with self.assertRaises(ValueError):voxel.preserved(baseline)+++if __name__=='__main__': unittest.main()1234{ "head": "2e10a51736826aa980f2fe79a801eb6c9da8e288", "status": " M docs/visual-graph-integration/03_sampling.md\n M visual/runtime/test/sampling_evaluation.py\n M visual/runtime/test/test_sampling_evaluation.py\n?? docs/visual-graph-integration/03ab_adaptive_node_budget.md\n?? docs/visual-graph-integration/03ab_adaptive_node_budget_plan.md\n?? docs/visual-graph-integration/03d_box_rim_bottleneck_phase1.md\n?? docs/visual-graph-integration/03d_priority_fps_seed_control_phase3.md\n?? docs/visual-graph-integration/03d_priority_fps_seed_control_phase3_plan.md\n?? docs/visual-graph-integration/03d_priority_fps_trace_phase2.md\n?? docs/visual-graph-integration/03d_priority_fps_trace_phase2_plan.md\n?? docs/visual-graph-integration/03e_priority_fps_metric_control.md\n?? docs/visual-graph-integration/03e_priority_fps_metric_control_plan.md\n?? docs/visual-graph-integration/03f_local_structural_sampling.md\n?? docs/visual-graph-integration/03f_local_structural_sampling_plan.md\n?? docs/visual-graph-integration/03g_geometry_aware_sampling.md\n?? docs/visual-graph-integration/03g_geometry_aware_sampling_plan.md\n?? docs/visual-graph-integration/03h_candidate_count_matched.md\n?? docs/visual-graph-integration/03h_candidate_count_matched_plan.md\n?? docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md\n?? visual/runtime/test/run_adaptive_node_budget.py\n?? visual/runtime/test/run_candidate_count_matched.py\n?? visual/runtime/test/run_geometry_aware_sampling.py\n?? visual/runtime/test/run_local_structural_sampling.py\n?? visual/runtime/test/run_priority_fps_metric_control.py\n?? visual/runtime/test/run_priority_fps_seed_control.py\n?? visual/runtime/test/run_priority_fps_trace.py\n?? visual/runtime/test/run_rim_bottleneck.py\n?? visual/runtime/test/test_adaptive_node_budget.py\n?? visual/runtime/test/test_candidate_count_matched.py\n?? visual/runtime/test/test_geometry_aware_sampling.py\n?? visual/runtime/test/test_local_structural_sampling.py\n?? visual/runtime/test/test_priority_fps_metric_control.py\n?? visual/runtime/test/test_priority_fps_seed_control.py\n?? visual/runtime/test/test_priority_fps_trace.py\n"}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495diff --git a/experiments/92f29716e76f4b998fe924f08e80357d/source_snapshot/visual/runtime/test/run_voxel_structural_sampling.py b/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/runtime/test/run_voxel_structural_sampling.pyindex 3772aaa..4d9bae7 100644--- a/experiments/92f29716e76f4b998fe924f08e80357d/source_snapshot/visual/runtime/test/run_voxel_structural_sampling.py+++ b/Users/jeong-yunseong/Documents/programming/graph-recurrent-VLA/visual/runtime/test/run_voxel_structural_sampling.py@@ -572,6 +572,14 @@ def report_blocks(result): p('이번 결과는 Voxel precompression + 3D FPS cap의 첫 feasibility 평가다. 순수 Voxel Sampling이나 일반적으로 유효한 Shape-First Sampling의 검증이 아니다. ' 'Nominal R 전체는 cap 없는 해상도 진단 집합이므로 32점 기준선과 동등 budget 성능으로 비교하지 않는다. ' '32점 cap 뒤의 거리·local coverage와 Surface/GT trade-off를 함께 해석한다.')+ p('A — 전반적 우월성을 지지하지 않는다. Peg는 λ=0보다 C→P tail이 개선됐지만 λ=1보다 p95/max가 소폭 악화했고, '+ 'Final seam은 151/160(λ=1/0)에서 142로 줄었다. Box는 p95가 두 기준선보다 작지만 mean은 두 기준선보다 크고, '+ 'Final rim은 3(λ=1)보다 많은 6이지만 12(λ=0)보다 적다. Surface p95는 개선됐으나 λ=1 대비 Surface mean은 두 물체 모두 소폭 악화했다. '+ 'Box 한 지표의 개선만으로 형상 보존에 유리하다고 채택하지 않는다.')+ p('B — nominal 해상도와 32점은 양립하지 않았다. Peg/Box의 R은 432/356개로 cap의 13.5/11.125배다. '+ 'C→R의 GT 손실은 0/9 reference였고 R→P에서 320/76개가 추가로 소실됐다. '+ '따라서 이 고정 경로에서는 cap 단계의 손실이 압축 단계보다 훨씬 컸다. '+ '다만 cap 수 자체의 효과와 그 32개를 고른 FPS 정책의 효과를 분리한 budget sweep은 하지 않았다.') p('N_occupied>32인 물체는 원래 해상도의 모든 voxel을 최종 보존하지 못했다. ' 'R 단계의 작은 오차와 R→P 추가 손실은 이 관측에서 예산 충돌의 크기를 보여주지만, ' '32점이 유일한 인과적 병목이거나 더 큰 budget이 일반적인 최적값임을 증명하지 않는다. '@@ -682,6 +690,10 @@ def report_blocks(result): '기존 UUID/project/group 규칙을 바꾸지 않았다. Git 시작 상태는 dirty이며 source snapshot·input/artifact hashes·시작 diff·implementation diff를 함께 보존했다. ' 'Production sampling/normal/tracking/shared simulator와 기존 dirty/untracked 파일은 변경하지 않았다. ' '같은 S3 조건에서 저장된 feature가 없는 source는 unavailable로 남겼으며 feature를 추정하지 않았다.')+ p('보호 대상 기존 파일 3,092개의 SHA-256와 HEAD 불변을 확인했다. Markdown↔HTML 및 JSON/NPZ/PNG 상대 링크, '+ 'PNG 7개 decode는 PASS다. 실제 브라우저 로딩은 computer-use 권한이 없어 진행하지 못했고, 사용자의 후속 지시에 따라 생략했다. '+ '이 미실행 항목을 검증 PASS로 계산하지 않는다. 수치 실행 source_snapshot과 선택·JSON/NPZ는 유지하고 '+ '최종 해석 문구/검증 상태를 보완한 보고 source는 report_source_snapshot과 report_generation_sources로 구분한다.') p('CPU NumPy/SciPy offline 실행이다. 단계별 wall time은 JSON에 기록했으며 Graph/GNN 20Hz 성능을 주장하지 않는다. ' 'Simulator/renderer/CUDA/MPS/GPU/PCL, 새 episode/fixture/score/normal, threshold/scale sweep, 두 번째 selection arm, ' 'GT calibration/quota, depth filtering, ratio/Adaptive Budget, Graph/GNN/BC, dependency 설치·외부 업로드·Git commit은 미실행이다. '@@ -715,7 +727,7 @@ def write_reports(output,result): md.extend(['| '+' | '.join(map(esc,headers))+' |','| '+' | '.join(['---']*len(headers))+' |']) md.extend('| '+' | '.join(map(esc,row))+' |' for row in rows);md.append('') page.append('<div class="scroll"><table><thead><tr>'+''.join('<th>'+html.escape(str(v))+'</th>' for v in headers)+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+html.escape(str(v))+'</td>' for v in row)+'</tr>' for row in rows)+'</tbody></table></div>')- page.append('<pre id="browser-check">pending</pre><script>addEventListener("load",()=>{document.getElementById("browser-check").textContent=JSON.stringify(Array.from(document.images).map(i=>({src:i.getAttribute("src"),complete:i.complete,width:i.naturalWidth,height:i.naturalHeight})));});</script></html>')+ page.append('</html>') REPORT.write_text('\n'.join(md));(output/(STEM+'.html')).write_text('\n'.join(page)) @@ -842,7 +854,54 @@ def run(baseline_path): def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--baseline',type=Path,required=True)- args=parser.parse_args();run(args.baseline)+ parser.add_argument('--finalize-saved',type=Path,help='Report/verification only; no FPS, evaluation, tests or new UUID')+ args=parser.parse_args()+ if args.finalize_saved:finalize_saved(args.finalize_saved,args.baseline)+ else:run(args.baseline)+++def finalize_saved(output,baseline_path):+ """Finalize the completed local run after browser validation was waived."""+ from utils.experiment_artifacts import register_existing_output+ result=json.loads((output/(STEM+'.json')).read_text())+ require_equal(output.name,result['run_id'],'saved identity')+ metadata=json.loads((output/'metadata.json').read_text())+ require_equal(metadata['status'],'finished','completed numerical run')+ immutable=[output/(STEM+'.json'),output/(STEM+'.npz'),output/'selection_before_gt.npz',output/'tests.log']+ before={str(p):prior.sha(p) for p in immutable}+ require_equal(before[str(output/'selection_before_gt.npz')],result['selection_before_gt_sha256'],'saved pre-GT hash')+ baseline=json.loads(baseline_path.read_text());preservation=preserved(baseline)+ current=[Path(__file__),Path(__file__).with_name('test_voxel_structural_sampling.py')]+ for path in current:+ destination=output/'report_source_snapshot'/path.relative_to(REPO)+ destination.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,destination)+ report_patch=''+ for path in current:+ report_patch+=subprocess.run(['git','diff','--no-index','--',str(output/'source_snapshot'/path.relative_to(REPO)),str(path)],+ cwd=REPO,capture_output=True,text=True).stdout+ (output/'report_refinement.patch').write_text(report_patch)+ write_reports(output,result)+ verification=json.loads((output/'verification.json').read_text())+ verification['documents']=verify_documents(output)+ verification['static_browser_loading']=dict(status='SKIP',reason='Computer-use permissions unavailable; user explicitly requested completion without browser execution',images_verified_by_decode=7)+ verification['status']='PASS for executed checks; browser loading SKIP by user instruction'+ ran=int(re.search(r'Ran (\d+) tests',result['tests_summary']).group(1))+ verification['required_tests']['pass_count']=ran-verification['required_tests']['skip_count']+ verification['source_preservation']=preservation+ verification['report_only_postprocessing']=dict(new_UUID=False,new_FPS=False,new_evaluation=False,numerical_artifacts_unchanged=True)+ write_json(output/'verification.json',verification)+ hashes=json.loads((output/'source_hashes.json').read_text())+ hashes['report_generation_sources']=prior.hashes(current)+ hashes['final_protected_preservation']=preservation+ hashes['numerical_artifacts_before_after']=dict(before=before,after={str(p):prior.sha(p) for p in immutable})+ require_equal(hashes['numerical_artifacts_before_after']['before'],hashes['numerical_artifacts_before_after']['after'],'report only preserves numerical artifacts')+ write_json(output/'source_hashes.json',hashes)+ for path in (REPORT,output/(STEM+'.html'),output/'verification.json',output/'source_hashes.json',output/'report_refinement.patch',+ *[(output/'report_source_snapshot'/p.relative_to(REPO)) for p in current]):+ register_existing_output(output,path,kind='reports')+ write_json(output/'git_end.json',dict(status=subprocess.check_output(['git','status','--short'],cwd=REPO,text=True),preservation=preserved(baseline)))+ register_existing_output(output,output/'git_end.json',kind='reports')+ print(json.dumps(dict(run_id=output.name,documents=verification['documents'],preservation=preservation,browser='SKIP',no_new_numerical_work=True))) if __name__=='__main__':main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Task03-I contracts. Performance improvement is not a PASS condition."""import copyimport inspectfrom pathlib import Pathimport tempfilefrom types import SimpleNamespaceimport unittestfrom unittest.mock import patch
import numpy as np
from visual.runtime.test import run_voxel_structural_sampling as voxelfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.geometry import OrganizedGeometryfrom visual.runtime.test.sampling_evaluation import CoverageMatcher
def case(n=100): flat=np.arange(n,dtype=np.int64) xyz=np.column_stack((flat*.01,np.sin(flat)*.002,np.ones(n))).astype(np.float32) return dict(candidate_flat=flat[::2],candidate_xyz=xyz[::2].copy(),support_flat=flat, support_xyz=xyz,shape=(10,10),intrinsic=np.diag([100.,100.,1.]),seed=47,anchor=0,final_target=64)
class GridTests(unittest.TestCase): def test_fixed_origin_negative_floor_and_boundaries(self): q=np.array([[-1.1,-1.,-.1],[0.,1.,1.1],[np.nextafter(1.,0),np.nextafter(1.,2),-0.]]) np.testing.assert_array_equal(voxel.voxel_keys(q,1.),[[-2,-1,-1],[0,1,1],[0,1,0]]) # Adding a distant observation never recentres existing cells. np.testing.assert_array_equal(voxel.voxel_keys(np.vstack([q,[1000,1000,1]]),1.)[:-1],voxel.voxel_keys(q,1.))
def test_representative_centroid_is_not_output_and_tie_source(self): flat=np.array([2,4,7],np.int64);xyz=np.array([[.125,.125,.125],[.375,.125,.125],[1.5,.125,.125]]) g=voxel.representatives(flat,xyz,1.) np.testing.assert_array_equal(flat[g['representative_rows']],[2,7]) np.testing.assert_array_equal(g['same_representative_source'],[2,2,7]) self.assertNotIn(.2,xyz[g['representative_rows'],0]) np.testing.assert_array_equal(g['capacity'],[2,1])
def test_coincident_xyz_sources_collapse_without_duplicate(self): g=voxel.representatives(np.array([1,3,5]),np.ones((3,3)),1.) np.testing.assert_array_equal(g['representative_rows'],[0]) np.testing.assert_array_equal(g['same_cell_distance_m'],0.)
def test_determinism_input_unchanged_and_bound(self): c=case();snapshot=copy.deepcopy(c) a=voxel.select(**c);b=voxel.select(**c) for key in ('R','P','F','xyz'): np.testing.assert_array_equal(a[key],b[key]) for key,value in c.items(): if isinstance(value,np.ndarray):np.testing.assert_array_equal(value,snapshot[key]) self.assertLessEqual(a['grouping']['same_cell_distance_m'].max(),a['scale']['epsilon_m']+1e-12)
def test_invalid_grid_and_source_inputs_fail_closed(self): for a in (0,-1,np.inf,np.nan): with self.assertRaises(ValueError):voxel.voxel_keys(np.ones((1,3)),a) for xyz in (np.array([[np.nan,1,1]]),np.array([[2.**63,0,0]]),np.array([[-2.**64,0,0]])): with self.assertRaises(ValueError):voxel.voxel_keys(xyz,1.) for flat in (np.array([1,1]),np.array([2,1]),np.array([-1,2]),np.array([1.,2.])): with self.assertRaises(ValueError):voxel.representatives(flat,np.ones((2,3)),1.)
def test_scale_median_robust_to_extreme_max_and_uses_only_X(self): x=np.array([[0,0,1],[0,0,2],[0,0,30.726]]) s=voxel.nominal_scale(x,np.diag([256.,128.,1.])) self.assertEqual(s['z_ref_m'],2.) self.assertAlmostEqual(s['epsilon_m'],2*np.hypot(2/256,2/128)) self.assertAlmostEqual(s['a_m']*np.sqrt(3),s['epsilon_m']) self.assertEqual(voxel.nominal_scale(np.empty((0,3)),np.eye(3))['status'],'N/A') for x,k in ((np.array([[0,0,-1]]),np.eye(3)),(x,np.diag([0,1,1]))): with self.assertRaises(ValueError):voxel.nominal_scale(x,k)
def test_dyadic_parent_nesting_first_count_and_nonexact32(self): keys=np.column_stack((np.arange(-40,40),np.zeros(80,int),np.zeros(80,int))).astype(np.int64) d=voxel.dyadic_counts(keys,.01) self.assertEqual([v['occupied'] for v in d['levels']],[80,40,20]) self.assertEqual(d['ratio'],4);self.assertFalse(d['used_for_selection']) self.assertEqual(voxel.dyadic_counts(keys,.01,0)['status'],'impossible') self.assertEqual(voxel.dyadic_counts(np.empty((0,3),np.int64),.01)['occupied'],0)
def test_dyadic_signed_int64_extremes_terminate(self): vals=np.array([np.iinfo(np.int64).min,np.iinfo(np.int64).max],np.int64) keys=np.array(np.meshgrid(vals,vals,vals)).reshape(3,-1).T d=voxel.dyadic_counts(keys,.001) self.assertLessEqual(d['occupied'],32) # General, non-nested voxel sizes do not imply monotone cell counts. xyz=np.array([[.9,0,0],[1.1,0,0],[1.9,0,0]]) self.assertEqual(len(np.unique(voxel.voxel_keys(xyz,1.),axis=0)),2)
class SelectionTests(unittest.TestCase): def test_more_equal_fewer_occupied_and_zero_cap(self): for n in (0,1,10,32,45): flat=np.arange(n,dtype=np.int64);xyz=np.column_stack((flat*2.,flat*0,flat*0+1)) g=voxel.choose_priority(flat,xyz,1.,47,0 if n else None,32,(10,10)) self.assertEqual(len(g['P']),min(n,32));self.assertEqual(len(g['R']),n) self.assertLessEqual(len(np.unique(g['P'])),32) if n<=32: np.testing.assert_array_equal(np.sort(g['P']),flat) z=voxel.choose_priority(flat,xyz,1.,47,0,0) self.assertEqual(len(z['P']),0)
def test_anchor_maps_to_representative_records_distance_pixels(self): f=np.array([0,1,2],np.int64);x=np.array([[.1,0,1],[.2,0,1],[.4,0,1]]) g=voxel.choose_priority(f,x,1.,0,0,32,(1,3)) self.assertEqual(g['anchor']['original_source'],0);self.assertEqual(g['anchor']['mapped_source'],1) self.assertAlmostEqual(g['anchor']['distance_m'],.1) self.assertEqual(g['anchor']['delta_pixel_uv'],[1,0]);self.assertEqual(g['anchor']['pixel_distance_px'],1) np.testing.assert_array_equal(g['P'],[1])
def test_cap_reuses_existing_3d_fps_and_exact_source(self): c=case();c['intrinsic']=np.diag([10000.,10000.,1.]) with patch.object(voxel,'fps_indices',wraps=fps_indices) as spy: s=voxel.select(**c) self.assertEqual(spy.call_count,2) rxyz=c['candidate_xyz'][np.searchsorted(c['candidate_flat'],s['R'])] np.testing.assert_array_equal(spy.call_args_list[0].args[0],rxyz) self.assertEqual(spy.call_args_list[0].kwargs['initial'],[int(np.searchsorted(s['R'],s['grouping']['anchor']['mapped_source']))]) np.testing.assert_array_equal(s['F'][:len(s['P'])],s['P']) np.testing.assert_array_equal(s['xyz'],c['support_xyz'][np.searchsorted(c['support_flat'],s['F'])]) self.assertTrue(set(s['P'])<=set(s['R'])<=set(c['candidate_flat'])<=set(c['support_flat'])) self.assertEqual(len(s['F']),len(np.unique(s['F'])))
def test_underfill_surface_empty_candidate_small_support_and_empty(self): for n,nc in ((10,2),(10,0),(0,0)): c=case(n);c['candidate_flat']=c['support_flat'][:nc];c['candidate_xyz']=c['support_xyz'][:nc] c['anchor']=0 if nc else None s=voxel.select(**c) self.assertEqual(len(s['F']),n);self.assertLessEqual(len(s['P']),nc) self.assertEqual(len(s['S']),n-len(s['P']));self.assertEqual(s['shortfall'],64-n)
def test_invalid_membership_coordinates_anchor_target(self): c=case();c['candidate_xyz'][0,0]=42 with self.assertRaises(AssertionError):voxel.select(**c) c=case();c['anchor']=99 with self.assertRaises(ValueError):voxel.select(**c) c=case();c['final_target']=-1 with self.assertRaises(ValueError):voxel.select(**c)
def test_decomposition_nn_extra_and_ties(self): c=case();s=voxel.select(**c) metrics,a=voxel.distance_decomposition(c['candidate_flat'],c['candidate_xyz'],s,c['shape']) self.assertTrue((a['budget_extra_m']>=-1e-12).all()) np.testing.assert_allclose(a['C_to_R_m']+a['budget_extra_m'],a['C_to_P_m']) self.assertTrue((a['C_to_R_m']<=a['same_cell_m']+1e-12).all()) d,near=voxel.nearest_sources(np.array([[0.,0,1]]),np.array([9,1]),np.array([[1,0,1],[-1,0,1]])) self.assertEqual(near[0],1);self.assertEqual(d[0],1) self.assertEqual(metrics['nominal_occupied']-metrics['selected_occupied'],metrics['discarded_occupied'])
def test_empty_P_distance_is_missing_not_zero(self): c=case();g=voxel.choose_priority(c['candidate_flat'],c['candidate_xyz'],.01,0,0,0,c['shape']) s=dict(grouping=g,R=g['R'],P=g['P'],scale=dict(epsilon_m=.01,a_m=.01)) row,a=voxel.distance_decomposition(c['candidate_flat'],c['candidate_xyz'],s,c['shape']) self.assertIsNone(row['C_to_P_m']['mean']);self.assertEqual(row['C_to_P_m']['missing_count'],50) self.assertTrue(np.isnan(a['C_to_P_m']).all())
class EvaluationContracts(unittest.TestCase): def test_selection_signature_has_no_annotations_and_freeze_before_GT(self): forbidden=('gt','roi','pose','score','label','reference','annotation') for f in (voxel.select,voxel.choose_priority,voxel.representatives,voxel.nominal_scale): self.assertFalse(any(bad in p.lower() for p in inspect.signature(f).parameters for bad in forbidden)) c=case();s=voxel.select(**c) case_data=dict(c,budget=64) with tempfile.TemporaryDirectory() as temp,patch.object(voxel.prior,'evaluation_inputs',side_effect=AssertionError('GT forbidden')): sha,arrays=voxel.freeze_selection(Path(temp),{'peg':case_data},{'peg':s},{}) self.assertEqual(voxel.prior.sha(Path(temp)/'selection_before_gt.npz'),sha) self.assertIn('peg/R',arrays) with self.assertRaises(FileExistsError):voxel.freeze_selection(Path(temp),{'peg':case_data},{'peg':s},{})
def test_available_feature_exact_gather_variable_priority(self): c=dict(saved_flat=np.array([1,3,7]),saved_features={'score':np.array([.1,.3,.7]),'normal_valid':np.array([True,False,True])}) mask,pos,fields=voxel.prior.feature_rows(c,np.array([3,4,1,9])) np.testing.assert_array_equal(mask,[True,False,True,False]);np.testing.assert_array_equal(pos,[0,2]) np.testing.assert_array_equal(fields['score'],[.3,.1]);np.testing.assert_array_equal(fields['normal_valid'],[False,True])
def test_GT_stage_unique_node_reference_same_pair_and_subset_losses(self): xyz=np.array([[[0,0,1],[.001,0,1],[.002,0,1]]],np.float32) geometry=OrganizedGeometry(xyz,np.ones((1,3),bool),{0:np.ones((1,3),bool)},np.zeros((1,3),bool)) reference=(np.array([[0,0],[1,0],[2,0]]),xyz.reshape(-1,3).copy()) matcher=CoverageMatcher(geometry,0,reference) context=dict(matcher=matcher,reference=reference,observable=np.ones(3,bool)) row,arrays=voxel.stage_gt(np.array([0]),context,np.array(['a']*3),{},None) self.assertEqual(row['matching_node_count'],1);self.assertEqual(row['unique_reference_count'],3) self.assertEqual(len(arrays['joint_reference_id']),3) bad=CoverageMatcher(geometry,0,(np.array([[0,0],[99,0]]),np.array([[0,0,2],[0,0,1]]))) context.update(matcher=bad,reference=(bad.ref_uv,bad.ref_xyz),observable=np.ones(2,bool)) row,_=voxel.stage_gt(np.array([0]),context,np.array(['a','a']),{},None) self.assertEqual(row['unique_reference_count'],0)
def test_variable_P_adapter_and_separate_reference_losses(self): flat=np.array([0,3,6],np.int64);xyz=np.zeros((1,7,3),np.float32) xyz[0,flat]=np.column_stack((np.arange(3)*.01,np.zeros(3),np.ones(3))) support=np.zeros((1,7),bool);support[0,flat]=True geometry=OrganizedGeometry(xyz,support,{0:support},np.zeros_like(support)) reference=(np.column_stack((flat,np.zeros(3))),xyz[0,flat]) matcher=CoverageMatcher(geometry,0,reference) context=dict(matcher=matcher,reference=reference,observable=np.ones(3,bool),negatives={'test':np.zeros_like(support)}) c=dict(candidate_flat=flat,candidate_xyz=xyz[0,flat],support_flat=flat,support_xyz=xyz[0,flat], saved_flat=flat,saved_features={'test_feature':np.arange(3)},oid=0) chosen=dict(R=flat[:2],P=flat[:1],S=flat[2:],F=flat[[0,2]],xyz=xyz[0,flat[[0,2]]]) arrays={};row=voxel.evaluate_method(c,chosen,context,SimpleNamespace(depth=np.ones((1,7))),np.array(['a']*3),{},None,arrays,'test') self.assertEqual([row['stages'][k]['unique_reference_count'] for k in ('C','R','P','S','F')],[3,2,1,1,2]) self.assertEqual(row['reference_differences']['C_minus_R']['reference_ids'],[2]) self.assertEqual(row['reference_differences']['R_minus_P']['reference_ids'],[1]) self.assertEqual(row['reference_differences']['F_minus_P']['reference_ids'],[2]) np.testing.assert_array_equal(arrays['test/F_selection_role'],['Priority','Surface'])
def test_protected_hash_failure_is_not_ignored(self): with tempfile.TemporaryDirectory() as temp: p=Path(temp)/'original';p.write_bytes(b'original') baseline=dict(hashes={str(p):voxel.prior.sha(p)},head='unused') p.write_bytes(b'changed') with self.assertRaises(ValueError):voxel.preserved(baseline)
if __name__=='__main__': unittest.main()123version https://git-lfs.github.com/spec/v1oid sha256:88de6d8684943b17e29f1fbf7abe3ad2e44531fe153f69c73e5245b0b1dd419dsize 1467363123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907"""Task03-I: one approved nominal voxel precompression + 3D FPS cap control.
Offline saved ep000 Frame0 only. Production, detectors and saved FPS are read-only.WANDB_MODE=disabled .venv/bin/python -m visual.runtime.test.run_voxel_structural_sampling --baseline PATH"""from __future__ import annotations
import argparseimport hashlibimport htmlfrom html.parser import HTMLParserimport jsonimport osfrom pathlib import Pathimport platformimport reimport shutilimport subprocessimport sysfrom time import perf_counter
import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as pltimport numpy as npfrom scipy.spatial import cKDTree
from utils.experiment_logger import ExperimentLoggerfrom visual.runtime.sampling import fps_indicesfrom visual.runtime.test import run_local_structural_sampling as localfrom visual.runtime.test import run_priority_fps_metric_control as priorfrom visual.runtime.test.run_rim_bottleneck import occupancy, require_equalfrom visual.runtime.test.sampling_evaluation import staged_reference_coverage
REPO = prior.REPOSTEM = 'voxel_structural_sampling'REPORT = REPO/'docs/visual-graph-integration/03i_voxel_structural_sampling.md'PLAN = REPO/'docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md'FIXTURE_RUN = REPO/'experiments/1f7ad262dd2e4b2fb0ac805a4eda5278'FIGURES = ('primary_selection.png', 'resolution_budget.png', 'primary_distances.png', 'peg_gt.png', 'box_gt.png', 'depth_roi_surface.png', 'synthetic.png')TESTS = ['visual.runtime.test.'+n for n in ('test_voxel_structural_sampling', 'test_sampling', 'test_sampling_geometry', 'test_sampling_evaluation', 'test_priority_fps_metric_control', 'test_local_structural_sampling')]RULES = dict(frame=0, episode='ep000', camera='base_camera', method='S3 optimized PCA5', orientation='strict >20 degrees, stored C only', seed=0, priority_cap_per_object=32, final_targets=dict(peg=129, box=127), total_cap=256, structural_ratio=.25, scale='median Z of original X; epsilon=z*sqrt((2/fx)^2+(2/fy)^2); a=epsilon/sqrt(3)', multiplier=1., grid='CV camera metres; origin 0; float64 floor(xyz/a); int64; half-open', representative='float64 centroid nearest original C; exact squared-distance tie smallest source', order='C/R source ascending; mapped anchor first in P; rest FPS or source ascending', anchor='original whole-C seeded anchor cell representative', cap='existing Euclidean 3D fps_indices', surface='existing whole-X 3D FPS initial=P; unused Priority becomes Surface; no padding', dyadic='count-only; floor_divide nominal keys by 2; first count<=32; never used for selection', gt='only after all real/synthetic selections saved, read back and hashed; same-pair <=2px AND <=3mm', score='none; no optimized dense C score available', uv_bins=[4,4], xyz_bins=[2,2,2], synthetic_names=local.FIXTURES['names'], synthetic_scale='stored C median Z; stored focal=1600px', synthetic_uncertainty_calibration='N/A: no actual PCA5 estimator/localization evidence', interpretation='first feasibility of voxel precompression + 3D FPS cap; anchor also changes')
def serial(value): if isinstance(value, dict): return {str(k):serial(v) for k,v in value.items()} if isinstance(value, (list,tuple)): return [serial(v) for v in value] if isinstance(value, np.ndarray): return serial(value.tolist()) if isinstance(value, np.generic): return serial(value.item()) if isinstance(value, Path): return str(value) if isinstance(value, float) and not np.isfinite(value): return None return value
def write_json(path, value): Path(path).write_text(json.dumps(serial(value), ensure_ascii=False, indent=2, allow_nan=False)+'\n')
def sources(flat, xyz): flat, xyz = np.asarray(flat), np.asarray(xyz) if flat.ndim != 1 or flat.dtype.kind not in 'iu' or np.any(flat < 0): raise ValueError('nonnegative integer sources required') if len(flat)>1 and not np.all(flat[1:]>flat[:-1]): raise ValueError('strict source order required') if xyz.shape != (len(flat),3) or not np.isfinite(xyz).all(): raise ValueError('finite source XYZ required') return flat, xyz
def nominal_scale(xyz, intrinsic): xyz, k = np.asarray(xyz), np.asarray(intrinsic, float) if xyz.ndim!=2 or xyz.shape[1]!=3 or not np.isfinite(xyz).all() or (xyz[:,2]<=0).any(): raise ValueError('original positive-depth X required') if k.shape!=(3,3) or not np.isfinite(k).all() or min(k[0,0],k[1,1])<=0: raise ValueError('valid intrinsic required') if not len(xyz): return dict(status='N/A', z_ref_m=None, epsilon_m=None, a_m=None) z = float(np.median(xyz[:,2].astype(float))) epsilon = z*np.hypot(2/k[0,0], 2/k[1,1]) a = epsilon/np.sqrt(3) if not np.isfinite(a) or a<=0: raise ValueError('nonpositive nominal scale') return dict(status='defined', z_ref_m=z, fx_px=float(k[0,0]), fy_px=float(k[1,1]), epsilon_m=float(epsilon), a_m=float(a), multiplier=1., pair_footprint_m=float(z*max(np.hypot(3/k[0,0],2/k[1,1]),np.hypot(2/k[0,0],3/k[1,1]))))
def voxel_keys(xyz, a): xyz=np.asarray(xyz, float) if xyz.ndim!=2 or xyz.shape[1]!=3 or not np.isfinite(xyz).all() or not np.isfinite(a) or a<=0: raise ValueError('finite XYZ and positive size required') with np.errstate(over='ignore',invalid='ignore'): q=np.floor(xyz/a) # float64(int64.max) rounds to 2**63, so the upper comparison is strict. if not np.isfinite(q).all() or (q < -(2.**63)).any() or (q >= 2.**63).any(): raise ValueError('voxel key int64 overflow') return q.astype(np.int64)
def representatives(flat, xyz, a): flat,xyz=sources(flat,xyz) key=voxel_keys(xyz,a) cells,membership,capacity=np.unique(key,axis=0,return_inverse=True,return_counts=True) rep_rows=np.empty(len(cells),np.int64) for cell in range(len(cells)): rows=np.flatnonzero(membership==cell) # already source ascending points=xyz[rows].astype(float) centroid=points.mean(axis=0) distance=np.sum((points-centroid)**2,axis=1) rep_rows[cell]=rows[int(distance.argmin())] same_rows=rep_rows[membership] same_distance=np.linalg.norm(xyz.astype(float)-xyz[same_rows].astype(float),axis=1) if len(flat) and np.max(same_distance)>np.sqrt(3)*a+64*np.finfo(float).eps*max(1.,np.max(np.abs(xyz))): raise AssertionError('same-cell bound failed') return dict(keys=key,cells=cells,membership=membership,capacity=capacity, cell_rep_rows=rep_rows, representative_rows=np.sort(rep_rows), same_representative_source=flat[same_rows], same_cell_distance_m=same_distance)
def dyadic_counts(keys, a, cap=32): keys=np.asarray(keys) if keys.ndim!=2 or keys.shape[1]!=3 or keys.dtype!=np.int64 or not np.isfinite(a) or a<=0: raise ValueError('int64 keys and positive size required') if not isinstance(cap,int) or cap<0: raise ValueError('invalid cap') if cap==0 and len(keys): return dict(status='impossible',levels=[],a_budget_m=None,ratio=None) if cap<8 and len(keys): raise ValueError('termination only guaranteed for cap>=8') levels=[]; key=keys.copy() for level in range(65): count=len(np.unique(key,axis=0)) if levels and count>levels[-1]['occupied']: raise AssertionError('non-nested parent count') size=float(np.ldexp(a,level)) if not np.isfinite(size): raise ValueError('dyadic size overflow') levels.append(dict(level=level,occupied=count,a_m=size,ratio=2**level,bound_m=np.sqrt(3)*size)) if count<=cap: return dict(status='defined',levels=levels,a_budget_m=size,ratio=2**level, occupied=count,used_for_selection=False) key=np.floor_divide(key,2) raise AssertionError('dyadic iteration failed to terminate')
def choose_priority(flat, xyz, a, seed, anchor=None, cap=32, shape=None): if not isinstance(cap,int) or cap<0: raise ValueError('nonnegative integer cap required') t0=perf_counter(); g=representatives(flat,xyz,a); t1=perf_counter() flat,xyz=sources(flat,xyz); rrows=g['representative_rows']; rflat=flat[rrows] mapped=None; mapped_row=None if len(flat): if anchor is None: anchor=int(flat[np.random.default_rng(seed).integers(len(flat))]) ar=np.flatnonzero(flat==anchor) if len(ar)!=1: raise ValueError('anchor outside C') mapped=int(g['same_representative_source'][ar[0]]) mapped_row=int(np.searchsorted(rflat,mapped)) if len(rrows)>cap: chosen=fps_indices(xyz[rrows],cap,seed=seed,initial=[mapped_row] if cap else ()) elif len(rrows) and cap: chosen=np.r_[mapped_row,np.flatnonzero(rflat!=mapped)].astype(np.int64) else: chosen=np.empty(0,np.int64) prows=rrows[chosen]; t2=perf_counter() anchor_info=dict(original_source=anchor if len(flat) else None,mapped_source=mapped,distance_m=None, delta_pixel_uv=None,pixel_distance_px=None) if len(flat): anchor_info['distance_m']=float(np.linalg.norm(xyz[int(ar[0])].astype(float)-xyz[rrows[mapped_row]].astype(float))) if shape is not None: uvs=np.column_stack(np.unravel_index([anchor,mapped],shape))[:,::-1] delta=uvs[1]-uvs[0] anchor_info.update(delta_pixel_uv=delta.tolist(),pixel_distance_px=float(np.linalg.norm(delta))) g.update(R=rflat.copy(),P=flat[prows].copy(),priority_rows=prows,anchor=anchor_info, timings_ms=dict(grid_representatives=(t1-t0)*1000,cap_fps=(t2-t1)*1000)) return g
def select(candidate_flat,candidate_xyz,support_flat,support_xyz,shape,intrinsic,seed,anchor,final_target,cap=32): if not isinstance(cap,int) or cap<0: raise ValueError('invalid Priority cap') c,cxyz=sources(candidate_flat,candidate_xyz); x,xxyz=sources(support_flat,support_xyz) local.uv_from_flat(c,shape);local.uv_from_flat(x,shape) rows=np.searchsorted(x,c) if (rows>=len(x)).any() or not np.array_equal(x[rows],c): raise ValueError('C outside X') np.testing.assert_array_equal(xxyz[rows],cxyz) if not isinstance(final_target,int) or final_target<0: raise ValueError('invalid final target') t0=perf_counter();scale=nominal_scale(xxyz,intrinsic);t1=perf_counter() if len(x): g=choose_priority(c,cxyz,scale['a_m'],seed,anchor,min(cap,final_target),shape) dyadic=dyadic_counts(g['keys'],scale['a_m'],cap) else: g=dict(R=c.copy(),P=c.copy(),keys=np.empty((0,3),np.int64),cells=np.empty((0,3),np.int64), membership=np.empty(0,np.int64),capacity=np.empty(0,np.int64),cell_rep_rows=np.empty(0,np.int64), representative_rows=np.empty(0,np.int64),same_representative_source=c.copy(),same_cell_distance_m=np.empty(0), anchor=dict(original_source=None,mapped_source=None,distance_m=None,delta_pixel_uv=None,pixel_distance_px=None), timings_ms=dict(grid_representatives=0.,cap_fps=0.)) dyadic=dict(status='N/A',levels=[],a_budget_m=None,ratio=None) t2=perf_counter(); initial=np.searchsorted(x,g['P']) frows=fps_indices(xxyz,final_target,seed=seed,initial=initial);f=x[frows];t3=perf_counter() return dict(P=g['P'],R=g['R'],S=f[len(initial):],F=f,xyz=xxyz[frows].copy(),grouping=g,scale=scale, dyadic=dyadic,shortfall=max(0,final_target-len(f)), timings_ms=dict(scale=(t1-t0)*1000,selection_and_dyadic=(t2-t1)*1000,surface_fps=(t3-t2)*1000,**g['timings_ms']))
def nearest_sources(query,flat,xyz): """Exact tie resolution by ascending source, independent of cKDTree ordering.""" flat=np.asarray(flat); xyz=np.asarray(xyz,float);query=np.asarray(query,float) if not len(flat): return np.full(len(query),np.nan),np.full(len(query),-1,np.int64) order=np.argsort(flat,kind='stable');flat=flat[order];xyz=xyz[order] distances=np.empty(len(query));near=np.empty(len(query),np.int64) for i,q in enumerate(query): d=np.sum((xyz-q)**2,axis=1);j=int(d.argmin());distances[i]=np.sqrt(d[j]);near[i]=flat[j] return distances,near
def distance_decomposition(c,cxyz,chosen,shape): g=chosen['grouping']; r=chosen['R'];p=chosen['P'] rxyz=cxyz[np.searchsorted(c,r)]; pxyz=cxyz[np.searchsorted(c,p)] dr,nr=nearest_sources(cxyz,r,rxyz);dp,np_=nearest_sources(cxyz,p,pxyz) budget=dp-dr if np.isfinite(budget).any() and np.nanmin(budget)<-1e-12: raise AssertionError('P not subset of R distance') arrays=dict(same_cell_m=g['same_cell_distance_m'],C_to_R_m=dr,C_to_P_m=dp,budget_extra_m=budget, C_to_R_source=nr,C_to_P_source=np_,same_cell_source=g['same_representative_source']) result={} for key in ('same_cell_m','C_to_R_m','C_to_P_m','budget_extra_m'): d=arrays[key];finite=np.isfinite(d);worst=int(np.nanargmax(d)) if finite.any() else None result[key]=dict(**local.summary(d*1000),unit='mm',missing_count=int((~finite).sum()), worst=None if worst is None else dict(source=int(c[worst]),xyz_m=cxyz[worst].tolist(), pixel_uv=local.uv_from_flat(c[[worst]],shape)[0].tolist(),distance_mm=float(d[worst]*1000))) arrays[key+'_ecdf']=np.sort(d[finite]) eps=chosen['scale']['epsilon_m'] selected_cells=np.unique(g['membership'][np.searchsorted(c,p)]) if len(p) else np.empty(0,np.int64) discarded=np.setdiff1d(np.arange(len(r)),selected_cells) above=dp>eps if eps is not None else np.zeros(len(c),bool) result.update(candidate_count=len(c),nominal_occupied=len(r),selected_occupied=len(selected_cells), discarded_occupied=len(discarded),occupied_over_32=len(r)/32,priority_count=len(p), resolution_budget_conflict=len(r)>32,above_epsilon_count=int(above.sum()), above_epsilon_fraction=float(above.mean()) if len(c) else None, a_used_m=chosen['scale']['a_m'],used_over_nominal=1. if eps is not None else None, discarded_cells=[dict(cell=int(i),key=g['cells'][i].tolist(),candidate_count=int(g['capacity'][i]), C_to_P_mm=local.summary(dp[g['membership']==i]*1000)) for i in discarded]) arrays.update(selected_cell_ids=selected_cells,discarded_cell_ids=discarded,above_epsilon=above) return result,arrays
def add_arrays(target,prefix,values): for k,v in values.items(): target[prefix+'/'+k]=np.asarray(v)
def selection_arrays(cases,selections,synthetic): arrays={} for name,case in cases.items(): chosen=selections[name] add_arrays(arrays,name,{k:case[k] for k in ('candidate_flat','candidate_xyz','support_flat','support_xyz')}) add_arrays(arrays,name,{k:chosen[k] for k in ('R','P','S','F','xyz')}) add_arrays(arrays,name+'/voxel',{k:chosen['grouping'][k] for k in ('keys','cells','membership','capacity', 'cell_rep_rows','representative_rows','same_representative_source','same_cell_distance_m')}) for name,data in synthetic.items(): add_arrays(arrays,'synthetic/'+name,dict(candidate_flat=data['flat'],candidate_xyz=data['xyz'], R=data['chosen']['R'],P=data['chosen']['P'],keys=data['chosen']['grouping']['keys'])) return arrays
def freeze_selection(output,cases,selections,synthetic): path=output/'selection_before_gt.npz' if path.exists(): raise FileExistsError('selection already frozen') arrays=selection_arrays(cases,selections,synthetic) np.savez_compressed(path,**arrays) with np.load(path,allow_pickle=False) as saved: require_equal(set(saved.files),set(arrays),'frozen keys') for key,value in arrays.items(): np.testing.assert_array_equal(saved[key],value,err_msg=key) return prior.sha(path),arrays
def check_selection(case,chosen): c,x=case['candidate_flat'],case['support_flat'];p,r,s,f=(chosen[k] for k in ('P','R','S','F')) if not set(p)<=set(r)<=set(c)<=set(x): raise AssertionError('P subset R subset C subset X') for key in ('R','P','S','F'): if len(np.unique(chosen[key]))!=len(chosen[key]): raise AssertionError('duplicate '+key) if len(p)>32 or len(f)>case['budget'] or len(f)!=min(len(x),case['budget']): raise AssertionError('budget') np.testing.assert_array_equal(f,np.r_[p,s]);np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(x,f)])
def load_baselines(cases,zero,samples): baselines={} with np.load(local.BASELINE/(prior.STEM+'.npz'),allow_pickle=False) as e: for name,case in cases.items(): one={stage:case['saved_flat'][sl].copy() for stage,sl in (('P',slice(0,32)),('S',slice(32,None)),('F',slice(None)))} one['xyz']=case['support_xyz'][np.searchsorted(case['support_flat'],one['F'])].copy() for stage in ('P','S','F'): np.testing.assert_array_equal(one[stage],e[f'S3/{name}/1.0/{stage}/flat_index']) for method,chosen in dict(global1=one,global0=zero[name]).items(): require_equal((len(chosen['P']),len(chosen['F']),int(chosen['P'][0])), (32,case['budget'],case['first']),'stored baseline count/anchor') np.testing.assert_array_equal(chosen['F'],np.r_[chosen['P'],chosen['S']]) np.testing.assert_array_equal(chosen['xyz'],case['support_xyz'][np.searchsorted(case['support_flat'],chosen['F'])]) key='S3_n256_r0.25_t20_s0';mask=samples[key+'/object_id']==case['oid'] np.testing.assert_array_equal(samples[key+'/points'][mask],one['xyz']) np.testing.assert_array_equal(samples[key+'/priority_selected'][mask],np.arange(case['budget'])<32) for flag in ('orientation_candidate','structural_candidate'): np.testing.assert_array_equal(case['saved_features'][flag],np.isin(one['F'],case['candidate_flat'])) baselines[name]=dict(global1=one,global0=zero[name]) return baselines
def load_synthetic_observations(): """Read observations and saved baseline selections only; no annotation field.""" manifest=json.loads((FIXTURE_RUN/'fixture_manifest.json').read_text()) output={} with np.load(FIXTURE_RUN/(local.STEM+'.npz'),allow_pickle=False) as saved: for name in RULES['synthetic_names']: pre='synthetic/'+name+'/' flat,xyz=saved[pre+'candidate_flat'].copy(),saved[pre+'candidate_xyz'].copy() sources(flat,xyz) if len(flat)!=manifest[name]['counts']['observed_count']: raise AssertionError('fixture count') require_equal(prior.array_sha(flat),manifest[name]['flat_sha256'],'saved fixture source hash') require_equal(prior.array_sha(xyz),manifest[name]['xyz_sha256'],'saved fixture XYZ hash') shape=tuple(local.FIXTURES['shape']);local.uv_from_flat(flat,shape) seed=prior.fps_seed(0,0);anchor=int(flat[np.random.default_rng(seed).integers(len(flat))]) k=np.array([[1600.,0,511.5],[0,1600.,511.5],[0,0,1]]) scale=nominal_scale(xyz,k) g=choose_priority(flat,xyz,scale['a_m'],seed,anchor,32,shape) chosen=dict(R=g['R'],P=g['P'],grouping=g,scale=scale,dyadic=dyadic_counts(g['keys'],scale['a_m'])) output[name]=dict(flat=flat,xyz=xyz,shape=shape,chosen=chosen, saved_global=saved[pre+'global/P'].copy(),saved_uv=saved[pre+'local/P'].copy()) return output
def stage_gt(flat,context,labels,specs,transform): """Thin variable-cardinality adapter over the existing joint matcher.""" matcher=context['matcher'];rows=np.searchsorted(matcher.flat,flat) ids,matched=matcher.reference_hits(flat);adj=matcher.adjacencies['2px_3mm'][rows] covered=np.zeros(matcher.nref,bool);covered[ids]=True xyz=matcher.xyz[rows];uv=matcher.uv[rows] segments={} for label in sorted(set(labels)): mask=labels==label;hit=adj[:,mask].getnnz(axis=1)>0 spacing=dict(status='N/A',reason='physical single-line order unverified') if label in specs and transform is not None: wt=transform['world_to_cv'];rot=transform['rot'] world=(xyz[hit]-wt[:3,3])@np.linalg.inv(wt[:3,:3].T) loc=(world-transform['box_pose'][:3])@np.linalg.inv(rot.T) spacing=prior.segment_spacing(specs[label]['local'][mask],covered[mask],loc[:,specs[label]['axis']],order_verified=True) segments[str(label)]=dict(reference_count=int(mask.sum()),observed_reference_count=int((mask&context['observable']).sum()), unique_reference_count=int((covered&mask).sum()),covered_reference_ids=np.flatnonzero(covered&mask).tolist(), matching_node_count=int(hit.sum()),matching_sources=flat[hit].tolist(),spacing=spacing) distance,nearest=nearest_sources(xyz,np.arange(matcher.nref,dtype=np.int64),context['reference'][1]) coo=adj.tocoo() return dict(node_count=len(flat),matching_node_count=len(matched),unique_reference_count=len(ids), covered_reference_ids=ids.tolist(),matching_sources=matched.tolist(),segments=segments, candidate_to_GT_reference_mm=local.summary(distance*1000)),dict(flat_index=flat,xyz=xyz,pixel_uv=uv, covered=covered,matching_source=matched,joint_node_row=coo.row,joint_reference_id=coo.col, to_GT_reference_m=distance,to_GT_reference_id=nearest)
def evaluate_method(case,chosen,context,frame,labels,specs,transform,arrays,prefix): c=case['candidate_flat'];x=case['support_flat'];stages=dict(C=c,P=chosen['P'],S=chosen['S'],F=chosen['F']) if 'R' in chosen: stages['R']=chosen['R'] details={} for stage,flat in stages.items(): details[stage],raw=stage_gt(flat,context,labels,specs,transform) add_arrays(arrays,prefix+'/'+stage,raw) available,positions,features=prior.feature_rows(case,flat) add_arrays(arrays,prefix+'/'+stage,dict(feature_available=available,feature_available_positions=positions)) add_arrays(arrays,prefix+'/'+stage+'/available_features',features) details[stage]['feature_available_count']=int(available.sum()) details[stage]['feature_unavailable_count']=int((~available).sum()) coverage=staged_reference_coverage(context['matcher'],c,chosen['P'],chosen['S'],chosen['F']) sets={k:set(v['covered_reference_ids']) for k,v in details.items()} differences={} for label,first,second in [('C_minus_R','C','R'),('R_minus_P','R','P'),('F_minus_P','F','P'),('P_intersect_S','P','S')]: if first in sets and second in sets: ids=sets[first]&sets[second] if label=='P_intersect_S' else sets[first]-sets[second] differences[label]=dict(count=len(ids),reference_ids=sorted(ids)) occ=occupancy(frame,dict(X=x,**stages),context['negatives']) bounds=occ['depth_band_bounds_m'];zc=frame.depth.ravel()[c];zp=frame.depth.ravel()[chosen['P']] band=lambda z:(z<=bounds['median'],(z>bounds['median'])&(z<=bounds['p95']),z>bounds['p95']) occ['candidate_band_priority_selection_rates']=[dict(candidate_count=int(a.sum()),priority_count=int(b.sum()), rate=float(b.sum()/a.sum()) if a.any() else None) for a,b in zip(band(zc),band(zp))] spatial,raw=local.spatial_metrics(c,case['candidate_xyz'],chosen['P'], case['support_xyz'][np.searchsorted(x,chosen['P'])],x,case['support_xyz'],frame.depth.shape) add_arrays(arrays,prefix+'/spatial',raw) ds=local.nearest(case['support_xyz'],chosen['xyz'])*1000 add_arrays(arrays,prefix,dict(X_to_F_mm=ds,F_selection_role=np.where(np.arange(len(chosen['F']))<len(chosen['P']),'Priority','Surface'))) return dict(stages=details,coverage=coverage,reference_differences=differences,occupancy=occ, spatial=spatial,surface_mm=local.summary(ds))
def evaluate_after_freeze(output,selection_sha,frame,geometry,samples,cases,selections,baselines,synthetic,input_config): require_equal(prior.sha(output/'selection_before_gt.npz'),selection_sha,'pre-GT selection hash') arrays={};actual={} with np.load(prior.EDGES,allow_pickle=False) as edges,np.load(prior.NORMAL,allow_pickle=False) as normal: contexts=prior.evaluation_inputs(frame,geometry,samples,edges,normal) peg_labels,_=prior.peg_labels(normal['evaluation/peg/face'],normal['evaluation/peg/gt_visible'], normal['evaluation/peg/seam_endpoints'],contexts['peg']['reference'][0]) with np.load(input_config['input'],allow_pickle=False) as episode: box_labels,specs,transform=prior.rim_labels(contexts['box']['reference'][1],frame.cam2world, episode['box_pose'][0],episode['box_hole_pose'][0],float(episode['box_hole_radii'])) for name,case in cases.items(): context=contexts[name];labels=peg_labels if name=='peg' else box_labels add_arrays(arrays,'evaluation/'+name,dict(reference_uv=context['reference'][0],reference_xyz=context['reference'][1], observable=context['observable'],segment=labels)) methods={} for method,chosen in dict(**baselines[name],voxel=selections[name]).items(): methods[method]=evaluate_method(case,chosen,context,frame,labels,{} if name=='peg' else specs, None if name=='peg' else transform,arrays,name+'/'+method) original_metrics=json.loads((local.SOURCE/'f0000_metrics.json').read_text())['S3_n256_r0.25_t20_s0']['objects'][name] score=context['matcher'].score(baselines[name]['global1']['F'])[0] require_equal(score,original_metrics['structural'],'original structural exact') require_equal(prior.stats(arrays[name+'/global1/X_to_F_mm']),original_metrics['surface']['all']['distance_mm'],'original Surface exact') saved_e=json.loads((local.BASELINE/(prior.STEM+'.json')).read_text())['cases']['S3/'+name]['conditions']['0.0'] for stage in ('C','P','S','F'): require_equal(methods['global0']['stages'][stage]['unique_reference_count'],saved_e['stages'][stage]['unique_reference_count'],'E saved refs') require_equal(methods['global0']['stages'][stage]['matching_node_count'],saved_e['stages'][stage]['structural_matching_nodes'],'E saved nodes') compression,raw=distance_decomposition(case['candidate_flat'],case['candidate_xyz'],selections[name],frame.depth.shape) add_arrays(arrays,name+'/compression',raw) r=selections[name]['R'];rxyz=case['candidate_xyz'][np.searchsorted(case['candidate_flat'],r)] rspatial,rraw=local.spatial_metrics(case['candidate_flat'],case['candidate_xyz'],r,rxyz,case['support_flat'],case['support_xyz'],frame.depth.shape) add_arrays(arrays,name+'/R_spatial',rraw) support_scales=case['candidate_xyz'][:,2].astype(float)*np.hypot(2/frame.intrinsic[0,0],2/frame.intrinsic[1,1]) add_arrays(arrays,name,dict(candidate_r5_m=support_scales)) actual[name]=dict(scale=selections[name]['scale'],dyadic=selections[name]['dyadic'],anchor=selections[name]['grouping']['anchor'], compression=compression,R_spatial=rspatial,candidate_r5_mm=local.summary(support_scales*1000),methods=methods, timings_ms=selections[name]['timings_ms']) synth_result={} with np.load(FIXTURE_RUN/(local.STEM+'.npz'),allow_pickle=False) as saved: for name,data in synthetic.items(): pre='synthetic/'+name+'/' annotation={k:saved[pre+k].copy() for k in ('structure_id','reference_xyz','reference_structure_id','reference_visible','lengths_m','generated_id')} annotation['occluded']=name=='camera_occluded' compression,raw=distance_decomposition(data['flat'],data['xyz'],data['chosen'],data['shape']) add_arrays(arrays,pre.rstrip('/')+'/compression',raw) row={} for method,p in dict(global0=data['saved_global'],uv=data['saved_uv'],voxel=data['chosen']['P']).items(): row[method],raw=local.evaluate_synthetic(data,annotation,p) add_arrays(arrays,pre+method,raw) synth_result[name]=dict(scale=data['chosen']['scale'],dyadic=data['chosen']['dyadic'],compression=compression, anchor=data['chosen']['grouping']['anchor'],methods=row,uncertainty_calibration='N/A',surface='N/A') data['annotation']=annotation require_equal(prior.sha(output/'selection_before_gt.npz'),selection_sha,'post-GT selection unchanged') return actual,synth_result,arrays,contexts
def plot_results(output,frame,cases,selections,result,arrays,synthetic,contexts): def save(fig,name): fig.savefig(output/name,dpi=150,bbox_inches='tight');plt.close(fig) def points(ax,flat,color,label,marker='o',size=10): uv=local.uv_from_flat(flat,frame.depth.shape) ax.scatter(uv[:,0],uv[:,1],s=size,c=color,label=label,marker=marker,linewidths=.5) def view(ax,case): uv=local.uv_from_flat(case['support_flat'],frame.depth.shape);lo,hi=uv.min(0),uv.max(0) ax.imshow(frame.rgb);ax.set_xlim(lo[0]-8,hi[0]+8);ax.set_ylim(hi[1]+8,lo[1]-8) ax.set_xlabel('source u [px]');ax.set_ylabel('source v [px]') fig,axes=plt.subplots(2,3,figsize=(15,9)) for row,(name,case) in enumerate(cases.items()): chosen=selections[name] for ax in axes[row]:view(ax,case) points(axes[row,0],case['candidate_flat'],'#38bdf8','C',size=8) points(axes[row,1],case['candidate_flat'],'#64748b','C',size=5) points(axes[row,1],chosen['R'],'#ff9f1c','R',size=12) points(axes[row,2],chosen['S'],'#a3e635','S',size=9) points(axes[row,2],chosen['P'],'#e879f9','P','*',35) for ax,title in zip(axes[row],(f'{name}: original C={len(case["candidate_flat"])}', f'nominal R={len(chosen["R"])} (not budget matched)',f'P={len(chosen["P"])} + S={len(chosen["S"])} = F={len(chosen["F"])}')): ax.set_title(title);ax.legend(fontsize=8) fig.suptitle('Observed source points: C / nominal representatives R / actual P + S = F',fontsize=15) save(fig,'primary_selection.png')
fig,axes=plt.subplots(2,2,figsize=(12,8)) for col,(name,row) in enumerate(result['actual'].items()): co=row['compression'];dy=row['dyadic'];s=row['scale'] ax=axes[0,col];counts=[co['candidate_count'],co['nominal_occupied'],co['selected_occupied'],co['discarded_occupied']] ax.bar(['C','R occupied','P occupied','discarded'],counts,color=['#38bdf8','#ff9f1c','#d946ef','#64748b']) ax.axhline(32,color='red',ls='--',label='Priority cap=32');ax.legend() ax.set_title(f'{name}: epsilon={s["epsilon_m"]*1000:.3f} mm; a={s["a_m"]*1000:.3f} mm') for i,c in enumerate(counts):ax.text(i,c+3,str(c),ha='center') ax=axes[1,col];lev=dy['levels'];ax.plot([r['ratio'] for r in lev],[r['occupied'] for r in lev],'o-') ax.axhline(32,color='red',ls='--');ax.set_xscale('log',base=2) ax.set_xlabel('dyadic metric size / nominal (count only; not selected)');ax.set_ylabel('occupied cells') ax.set_title(f'First <=32: {dy["occupied"]} cells at {dy["ratio"]}x; actual selection stays 1x') fig.tight_layout();save(fig,'resolution_budget.png')
fig,axes=plt.subplots(2,2,figsize=(13,9)) for col,(name,row) in enumerate(result['actual'].items()): ax=axes[0,col] for field,label in [('same_cell_m','same-cell'),('C_to_R_m','C -> R'),('C_to_P_m','C -> P'),('budget_extra_m','budget extra')]: d=arrays[f'{name}/compression/{field}_ecdf']*1000 ax.step(d,np.arange(1,len(d)+1)/max(1,len(d)),where='post',label=label) ax.axvline(row['scale']['epsilon_m']*1000,color='grey',ls='--',label='nominal epsilon (R cell only)') ax.set_xlabel('Euclidean distance [mm]');ax.set_ylabel('fraction');ax.set_title(name+' distance decomposition');ax.legend(fontsize=8) ax=axes[1,col] for method in ('global1','global0','voxel'): d=arrays[f'{name}/{method}/spatial/distance_mm'];d=np.sort(d) ax.step(d,np.arange(1,len(d)+1)/len(d),where='post',label=method) ax.set_xlabel('C -> actual Priority [mm]');ax.set_ylabel('fraction');ax.set_title(name+' fixed-cap comparison');ax.legend() fig.tight_layout();save(fig,'primary_distances.png')
for name,case in cases.items(): row=result['actual'][name]['methods']['voxel'];context=contexts[name];uv=context['reference'][0] fig,axes=plt.subplots(2,3,figsize=(15,9)) for ax,stage in zip(axes.flat,('C','R','P','S','F')): view(ax,case);covered=np.asarray(arrays[f'{name}/voxel/{stage}/covered']) ax.scatter(uv[:,0],uv[:,1],c='#ef4444',s=10,label='uncovered reference') ax.scatter(uv[covered,0],uv[covered,1],c='#22c55e',s=12,label='covered reference') points(ax,arrays[f'{name}/voxel/{stage}/flat_index'],'#c084fc',stage,'x',15) st=row['stages'][stage] ax.set_title(f'{stage}: nodes={st["node_count"]}; matching={st["matching_node_count"]}; unique refs={st["unique_reference_count"]}') ax=axes.flat[-1];view(ax,case) ax.scatter(uv[:,0],uv[:,1],s=8,c='#64748b',label='all refs') for key,color,label in [('C_minus_R','#ef4444','lost C -> R'),('R_minus_P','#f59e0b','lost R -> P'),('F_minus_P','#22c55e','added Surface')]: ids=row['reference_differences'][key]['reference_ids'] ax.scatter(uv[ids,0],uv[ids,1],c=color,s=24,label=f'{label}: {len(ids)}') ax.set_title('Loss at compression / cap; Surface additions');ax.legend(fontsize=8) fig.suptitle(name+' auxiliary GT only: same-pair <=2px AND <=3mm; references != matching nodes') fig.tight_layout();save(fig,name+'_gt.png')
fig,axes=plt.subplots(2,3,figsize=(15,9)) for row,(name,data) in enumerate(result['actual'].items()): ax=axes[row,0] for stage,color in [('C','#38bdf8'),('R','#ff9f1c'),('P','#d946ef'),('S','#84cc16'),('F','#8b5cf6')]: flat=arrays[f'{name}/voxel/{stage}/flat_index'];z=np.sort(frame.depth.ravel()[flat]) ax.step(z,np.arange(1,len(z)+1)/len(z),where='post',label=stage,color=color) ax.set_xscale('log');ax.set_xlabel('original depth Z [m], log scale');ax.set_title(name+' retained depth tails');ax.legend() methods=list(data['methods']);x=np.arange(len(methods));ax=axes[row,1] for offset,stage in [(-.2,'P'),(0,'S'),(.2,'F')]: vals=[data['methods'][m]['occupancy']['negative_roi']['known_negative_union'][stage]['fraction_of_path']['value'] for m in methods] ax.bar(x+offset,vals,width=.2,label=stage) ax.set_xticks(x,methods);ax.set_ylabel('ROI fraction (not noise ground truth)');ax.set_title(name+' existing negative union');ax.legend() ax=axes[row,2] for offset,metric in [(-.2,'mean'),(0,'p95'),(.2,'max')]: ax.bar(x+offset,[data['methods'][m]['surface_mm'][metric] for m in methods],width=.2,label=metric) ax.set_xticks(x,methods);ax.set_ylabel('X -> F [mm]');ax.set_title(name+' Surface trade-off');ax.legend() fig.tight_layout();save(fig,'depth_roi_surface.png')
fig,axes=plt.subplots(7,3,figsize=(15,23)) for row,(name,data) in enumerate(synthetic.items()): for col,(method,p) in enumerate(dict(global0=data['saved_global'],uv=data['saved_uv'],voxel=data['chosen']['P']).items()): ax=axes[row,col];xyz=data['xyz'];pxyz=xyz[np.searchsorted(data['flat'],p)] ax.scatter(xyz[:,0]*1000,xyz[:,1]*1000,s=7,c='#94a3b8',label='stored C') if method=='voxel': r=xyz[np.searchsorted(data['flat'],data['chosen']['R'])] ax.scatter(r[:,0]*1000,r[:,1]*1000,s=13,c='#ff9f1c',label='nominal R') ax.scatter(pxyz[:,0]*1000,pxyz[:,1]*1000,s=28,c='#d946ef',marker='*',label='P') m=result['synthetic'][name]['methods'][method] ax.set_title(f'{name} / {method}: P={len(p)}, p95={m["mm"]["raw"]["p95"]:.3f}mm, noise={m["noise_selected"]}') ax.set_xlabel('camera X [mm]');ax.set_ylabel('camera Y [mm]');ax.legend(fontsize=7) fig.suptitle('Stored seven fixtures only; PCA5 localization calibration and Surface: N/A',y=1.001) fig.tight_layout();save(fig,'synthetic.png')
def report_blocks(result): b=[] p=lambda text:b.append(('p',text)) h=lambda text:b.append(('h',text)) table=lambda headers,rows:b.append(('table',(headers,rows))) image=lambda name,caption:b.append(('image',(name,caption))) fmt=lambda x:'N/A' if x is None else f'{x:.4f}' h('두 연구 질문에 대한 판단') for name,row in result['actual'].items(): co=row['compression'];v=row['methods']['voxel'];g1=row['methods']['global1'];g0=row['methods']['global0'] p(f'{name}: C={co["candidate_count"]} → nominal R={co["nominal_occupied"]} → P={co["priority_count"]}. ' f'Nominal occupied/cap={co["occupied_over_32"]:.3f}배이며 {co["discarded_occupied"]}개 cell이 cap에서 제거됐다. ' f'C→P p95는 voxel {fmt(v["spatial"]["mm"]["raw"]["p95"])}mm, 저장 Global λ=1 {fmt(g1["spatial"]["mm"]["raw"]["p95"])}mm, ' f'λ=0 {fmt(g0["spatial"]["mm"]["raw"]["p95"])}mm다. ' f'GT unique refs C/R/P/F={v["stages"]["C"]["unique_reference_count"]}/{v["stages"]["R"]["unique_reference_count"]}/' f'{v["stages"]["P"]["unique_reference_count"]}/{v["stages"]["F"]["unique_reference_count"]}다.') p('이번 결과는 Voxel precompression + 3D FPS cap의 첫 feasibility 평가다. 순수 Voxel Sampling이나 일반적으로 유효한 Shape-First Sampling의 검증이 아니다. ' 'Nominal R 전체는 cap 없는 해상도 진단 집합이므로 32점 기준선과 동등 budget 성능으로 비교하지 않는다. ' '32점 cap 뒤의 거리·local coverage와 Surface/GT trade-off를 함께 해석한다.') p('A — 전반적 우월성을 지지하지 않는다. Peg는 λ=0보다 C→P tail이 개선됐지만 λ=1보다 p95/max가 소폭 악화했고, ' 'Final seam은 151/160(λ=1/0)에서 142로 줄었다. Box는 p95가 두 기준선보다 작지만 mean은 두 기준선보다 크고, ' 'Final rim은 3(λ=1)보다 많은 6이지만 12(λ=0)보다 적다. Surface p95는 개선됐으나 λ=1 대비 Surface mean은 두 물체 모두 소폭 악화했다. ' 'Box 한 지표의 개선만으로 형상 보존에 유리하다고 채택하지 않는다.') p('B — nominal 해상도와 32점은 양립하지 않았다. Peg/Box의 R은 432/356개로 cap의 13.5/11.125배다. ' 'C→R의 GT 손실은 0/9 reference였고 R→P에서 320/76개가 추가로 소실됐다. ' '따라서 이 고정 경로에서는 cap 단계의 손실이 압축 단계보다 훨씬 컸다. ' '다만 cap 수 자체의 효과와 그 32개를 고른 FPS 정책의 효과를 분리한 budget sweep은 하지 않았다.') p('N_occupied>32인 물체는 원래 해상도의 모든 voxel을 최종 보존하지 못했다. ' 'R 단계의 작은 오차와 R→P 추가 손실은 이 관측에서 예산 충돌의 크기를 보여주지만, ' '32점이 유일한 인과적 병목이거나 더 큰 budget이 일반적인 최적값임을 증명하지 않는다. ' '후보 오염, FPS 거리 경쟁과 anchor 이동이 남아 있다. 결과에 따른 재선택·파라미터 변경은 하지 않았다.') h('고정 조건·scale·실제 PCA5 지원 범위') p('ep000 Frame 0 / base_camera / S3 optimized PCA5 / orientation-only >20° / seed0. ' 'Final Peg129/Box127, 총256; Priority 상한 각32/총64, structural_ratio=.25는 현재 조건이다. ' '전체 원본 X의 camera Z median, 저장 fx=fy=256px, multiplier=1로 epsilon=z_ref*sqrt((2/fx)^2+(2/fy)^2), a=epsilon/sqrt(3)를 정했다.') p('PCA5 normal은 중심 ±2px 5×5 내부의 same-object 4-connected support를 사용한다. ' 'Depth jump >.01+.02*min(z1,z2)에서 연결을 끊고, 최소6점·rank2·unique smallest eigenvector를 요구한다. ' '불완전 patch를 허용하며 부족한 normal은 invalid다. Pair는 인접 normal을 비교해 >20°일 때 양 끝을 후보로 표시한다. ' '두 normal support 합집합은 6×5 또는 5×6, 한 endpoint의 모든 비교 footprint는 7×7 bbox의 네 모서리를 제외한다. ' '단순 5×5 window와 전체 반응 띠를 혼동하지 않는다.') p('Spatial support, 실제 edge localization error, voxel approximation error는 서로 다르다. ' 'Nominal epsilon은 동일 depth 평면의 half-window 근사에서 정한 compression scale이며 edge 오차의 추정값·상한이 아니다. ' '경사·깊이 불연속에서는 근사가 깨진다. Same-cell 후보→대표점 bound sqrt(3)*a는 R 단계에서만 보장된다. ' 'Cell을 버린 P와 2px AND 3mm matcher 통과에는 보장되지 않는다. 새 normal/score/GT calibration은 없다.') table(['object','X median m','epsilon mm','a nominal=used mm','R occupied','R/32','P cells','removed','P>epsilon count/fraction','dyadic a mm / ratio / cells'],[ [name,fmt(row['scale']['z_ref_m']),fmt(row['scale']['epsilon_m']*1000),fmt(row['scale']['a_m']*1000), row['compression']['nominal_occupied'],fmt(row['compression']['occupied_over_32']),row['compression']['selected_occupied'],row['compression']['discarded_occupied'], f'{row["compression"]["above_epsilon_count"]}/{row["compression"]["candidate_count"]} ({row["compression"]["above_epsilon_fraction"]:.2%})', f'{row["dyadic"]["a_budget_m"]*1000:.4f} / {row["dyadic"]["ratio"]}x / {row["dyadic"]["occupied"]}'] for name,row in result['actual'].items()]) p('실제 used/nominal ratio는 1이다. Dyadic은 nominal integer key를 음수에도 floor_divide(2)하여 만든 nested count-only 진단이다. ' '최초 occupied≤32에서 멈췄고 그 크기를 선택에 사용하지 않았다. 임의 크기 grid의 단조성이나 정확히32 cell 존재를 가정하지 않았다. ' '이 dyadic family의 첫 크기를 전역 최소·물리적 최적 해상도로 읽지 않는다.') image('resolution_budget.png','Nominal 해상도와 현재 Priority 상한; coarse 진단은 선택에 미사용') h('선택 규칙·anchor 이동·원본 provenance') p('Camera origin=(0,0,0), 원본 CV XYZ(m)의 float64 floor(XYZ/a) int64 key, half-open cell을 사용했다. ' 'BBox 최소점으로 이동하지 않았다. Cell centroid에 가장 가까운 원본 C 하나, exact squared-distance tie는 최소 source다. ' 'R은 source ascending, original anchor cell의 대표점을 initial로 기존 Euclidean 3D FPS cap32를 수행했다. ' 'R≤32면 전부 사용하고 남는 예산은 전체 X의 기존 3D Surface FPS로 넘긴다. Padding·복제·좌표 평균 node는 없다.') table(['object','original anchor','mapped R source','3D shift mm','delta(u,v) px','pixel shift px'],[ [name,row['anchor']['original_source'],row['anchor']['mapped_source'],fmt(row['anchor']['distance_m']*1000), str(row['anchor']['delta_pixel_uv']),fmt(row['anchor']['pixel_distance_px'])] for name,row in result['actual'].items()]) p('Anchor source가 바뀌면 grouping/precompression과 FPS 시작점 효과가 함께 달라진다. ' '추가 anchor-only arm은 실행하지 않았으므로 두 효과를 인과적으로 분해하지 않는다. ' 'C 전체 optimized score가 저장돼 있지 않아 score-free만 사용했다. Task02 reference PCA5 angle을 optimized score로 대체하지 않았다.') image('primary_selection.png','PCA5 원본 C / nominal 대표점 R / 실제 Priority P와 Surface S=Final F') h('Primary: 압축 오차와 budget 추가 손실') table(['object','distance (mm)','mean','p50','p95','max','worst source'],[ [name,key,*[fmt(row['compression'][key][k]) for k in ('mean','p50','p95','max')],row['compression'][key]['worst']['source']] for name,row in result['actual'].items() for key in ('same_cell_m','C_to_R_m','C_to_P_m','budget_extra_m')]) p('same_cell은 자기 cell의 대표점 거리, C→R은 모든 대표점 중 최근접 거리다. ' 'Budget extra=C→P−C→R≥0이며 same_cell을 빼지 않았다. 네 raw 배열, ECDF와 worst source/XYZ/pixel을 NPZ/JSON에 저장했다. ' 'Same-cell bound 확인과 성능 개선은 별개다.') table(['object','method','P','C→P mean/p50/p95/max mm','X→F mean/p95/max mm','Final unique GT refs'],[ [name,method,m['stages']['P']['node_count'],' / '.join(fmt(m['spatial']['mm']['raw'][k]) for k in ('mean','p50','p95','max')), ' / '.join(fmt(m['surface_mm'][k]) for k in ('mean','p95','max')),m['stages']['F']['unique_reference_count']] for name,row in result['actual'].items() for method,m in row['methods'].items()]) table(['object','method','UV selected/occupied; P=0 IDs','XYZ selected/occupied; P=0 IDs','UV equal-region mean p95 mm'],[ [name,method,*[f'{g["candidate_occupied_regions"]-len(g["empty_priority_region_ids"])}/{g["candidate_occupied_regions"]}; {g["empty_priority_region_ids"]}' for g in (m['spatial']['grids']['uv'],m['spatial']['grids']['xyz'])],fmt(m['spatial']['grids']['uv']['equal_region_mean_p95_mm'])] for name,row in result['actual'].items() for method,m in row['methods'].items()]) p('독립 UV4×4/XYZ 최대2×2×2 구역은 같은 X bbox로 고정했다. 구역별 후보 밀도·선택률·거리 tail과 R 단계 구역 통계는 JSON/NPZ에 있다. ' 'Box의 30.726m outlier는 그대로 남아 coarse XYZ 구역과 bbox 정규화를 왜곡하므로 raw mm와 UV를 함께 본다. ' '단순 구역 점유가 같아도 국소 geometry가 같다는 뜻은 아니다.') image('primary_distances.png','Same-cell / C→R / C→P / budget extra ECDF와 저장 FPS 비교') h('Secondary: 선택 후 GT, C/R/P/S/F reference 손실') p('Same-pair ≤2px AND ≤3mm를 유지했다. Peg observed462/visible464, Box observed103/visible103이다. ' '한 node는 여러 reference를 덮고 한 reference는 여러 node에 매칭될 수 있다. Pair count·matching node·unique reference는 서로 다르다.') table(['object','voxel stage','nodes','matching nodes','unique refs','available/unavailable feature rows'],[ [name,stage,m['node_count'],m['matching_node_count'],m['unique_reference_count'],f'{m["feature_available_count"]}/{m["feature_unavailable_count"]}'] for name,row in result['actual'].items() for stage,m in row['methods']['voxel']['stages'].items()]) table(['object','C→R lost refs','R→P additional lost refs','Surface added refs','P/S overlapping refs'],[ [name,*[row['methods']['voxel']['reference_differences'][key]['count'] for key in ('C_minus_R','R_minus_P','F_minus_P','P_intersect_S')]] for name,row in result['actual'].items()]) table(['Box segment','reference count','C','R','P','S','F','Global λ1 P/F','Global λ0 P/F'],[ [label,seg['reference_count'],*[result['actual']['box']['methods']['voxel']['stages'][stage]['segments'][label]['unique_reference_count'] for stage in ('C','R','P','S','F')], *[' / '.join(str(result['actual']['box']['methods'][method]['stages'][stage]['segments'][label]['unique_reference_count']) for stage in ('P','F')) for method in ('global1','global0')]] for label,seg in result['actual']['box']['methods']['voxel']['stages']['C']['segments'].items()]) p('각 단계 reference ID 집합·joint pairs·matching source·구간별 matching node/reference·Box line spacing을 저장했다. ' 'Surface 추가분은 refs(F)−refs(P)이며 S 전체 hit 수와 다르다. C→R과 R→P 손실은 P⊆R⊆C에서 구분했다. ' 'Peg 물리적 line 순서/간격은 N/A다. GT 후보→reference 거리에는 depth noise, reference 이산화, 가시성·matcher 정의가 섞여 ' '순수 detector localization error가 아니다. 이를 epsilon calibration에 사용하지 않았다.') image('peg_gt.png','Peg seam: C/R/P/S/F coverage와 압축/예산 손실') image('box_gt.png','Box rim: C/R/P/S/F coverage와 압축/예산 손실') h('Depth·ROI·일반 Surface trade-off') table(['object','stage','depth median/p95/max m','negative union count / nodes'],[ [name,stage,' / '.join(fmt(row['methods']['voxel']['occupancy']['depth_m'][stage][k]) for k in ('median','p95','max')), f'{row["methods"]["voxel"]["occupancy"]["negative_roi"]["known_negative_union"][stage]["count"]} / ' f'{row["methods"]["voxel"]["occupancy"]["negative_roi"]["known_negative_union"][stage]["fraction_of_path"]["denominator"]}'] for name,row in result['actual'].items() for stage in ('X','C','R','P','S','F')]) p('원거리 positive depth를 제거하지 않았다. ROI는 중첩되므로 union을 별도 집계했다. ' 'ROI/far는 실제 noise 정답이 아니며 일반 Surface 점유를 자동 오선택으로 분류하지 않는다. ' 'X median/p95 기반 depth bands와 candidate별 P 선택률도 저장했다. ' 'Median은 단일 extreme max 영향은 줄이지만 mask 오염과 물체 내 depth 차이를 해결하지 않는다. ' 'Peg/Box는 같은 공식으로 서로 다른 metric a를 사용하며 동일 절대 해상도 비교가 아니다.') image('depth_roi_surface.png','원본 depth tail, 기존 negative union, 전체 X→F Surface 비교') h('기존 7개 synthetic의 저장 입력 재사용') table(['fixture','C/R/P','a mm','dyadic ratio','Global/UV/Voxel C→P p95 mm','Global/UV/Voxel ref→P p95 mm','noise P G/UV/V'],[ [name,f'{row["compression"]["candidate_count"]}/{row["compression"]["nominal_occupied"]}/{row["compression"]["priority_count"]}', fmt(row['scale']['a_m']*1000),row['dyadic']['ratio'], ' / '.join(fmt(row['methods'][m]['mm']['raw']['p95']) for m in ('global0','uv','voxel')), ' / '.join(fmt(row['methods'][m]['reference_mm']['p95']) for m in ('global0','uv','voxel')), ' / '.join(str(row['methods'][m]['noise_selected']) for m in ('global0','uv','voxel'))] for name,row in result['synthetic'].items()]) p('Task03-F 저장 C/source/XYZ와 Global/UV 선택을 읽었으며 새 fixture·기준선 FPS를 만들지 않았다. ' 'Dense X가 없는 stress test에서 관측 C median과 기존 focal1600px로 같은 scale 공식을 적용했다. ' 'Annotation은 모든 선택 저장 후에만 noise/reference/구조별 평가에 사용했다. ' '실제 PCA5 5×5 localization uncertainty calibration과 Synthetic Surface는 N/A다. ' '계약/geometry stress test 통과가 uncertainty calibration 타당성을 뜻하지 않는다.') image('synthetic.png','기존 일곱 fixture의 저장 Global/UV와 단일 voxel precompression control') h('검증·재현·한계·완료 범위') p(f'실행 UUID {result["run_id"]}. 필수 계약 테스트: {result["tests_summary"]}. ' '성능 개선을 PASS 조건으로 두지 않았다. selection_before_gt.npz를 real/synthetic 선택 전체의 저장·readback·hash 이후에만 ' 'GT evaluator/annotation에 연결했다. 평가 후 선택 hash 불변, 원본 C/X·baseline exact alignment, 원본 feature available-only exact gather를 확인했다.') p('기존 ExperimentLogger(team=visual, job_type=evaluate), WANDB_MODE=disabled 및 로컬 artifact inventory를 재사용했다. ' '기존 UUID/project/group 규칙을 바꾸지 않았다. Git 시작 상태는 dirty이며 source snapshot·input/artifact hashes·시작 diff·implementation diff를 함께 보존했다. ' 'Production sampling/normal/tracking/shared simulator와 기존 dirty/untracked 파일은 변경하지 않았다. ' '같은 S3 조건에서 저장된 feature가 없는 source는 unavailable로 남겼으며 feature를 추정하지 않았다.') p('보호 대상 기존 파일 3,092개의 SHA-256와 HEAD 불변을 확인했다. Markdown↔HTML 및 JSON/NPZ/PNG 상대 링크, ' 'PNG 7개 decode는 PASS다. 실제 브라우저 로딩은 computer-use 권한이 없어 진행하지 못했고, 사용자의 후속 지시에 따라 생략했다. ' '이 미실행 항목을 검증 PASS로 계산하지 않는다. 수치 실행 source_snapshot과 선택·JSON/NPZ는 유지하고 ' '최종 해석 문구/검증 상태를 보완한 보고 source는 report_source_snapshot과 report_generation_sources로 구분한다.') p('CPU NumPy/SciPy offline 실행이다. 단계별 wall time은 JSON에 기록했으며 Graph/GNN 20Hz 성능을 주장하지 않는다. ' 'Simulator/renderer/CUDA/MPS/GPU/PCL, 새 episode/fixture/score/normal, threshold/scale sweep, 두 번째 selection arm, ' 'GT calibration/quota, depth filtering, ratio/Adaptive Budget, Graph/GNN/BC, dependency 설치·외부 업로드·Git commit은 미실행이다. ' 'Task03-H의 동일 count 기대 coverage는 후보 해석 근거, Task03-F/G는 기존 실패 비교군으로만 유지했다. ' '보고서 제출 후 추가 알고리즘 실행 없이 중단한다.') return b
def write_reports(output,result): blocks=report_blocks(result);relative='../../experiments/'+output.name+'/' artifacts=[STEM+'.html',STEM+'.json',STEM+'.npz','selection_before_gt.npz','selection_before_gt.json', 'verification.json','tests.log','source_hashes.json','preregistered_config.json','implementation.patch','git_start.diff'] md=['# Task03-I — Shape-First Voxel Precompression + 3D FPS Cap','', ' · '.join(f'[{f}]({relative+f})' for f in artifacts),'', '[승인 계획](03i_voxel_structural_sampling_plan.md) · [Task03-H](03h_candidate_count_matched.md) · ' '[Task03-F](03f_local_structural_sampling.md) · [Task03-G](03g_geometry_aware_sampling.md)',''] page=['<!doctype html><html lang="ko"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">', '<title>Task03-I — Voxel precompression + FPS cap</title><style>body{font:16px/1.65 system-ui,sans-serif;background:#f4f6f9;color:#17212e;margin:auto;max-width:1450px;padding:30px}h1,h2{line-height:1.25}h2{margin-top:2.5em;border-bottom:2px solid #cbd5e1;padding-bottom:12px}p{max-width:1150px}table{border-collapse:collapse;width:100%;font-size:14px;background:white}td,th{border:1px solid #cbd5e1;padding:9px;text-align:left}th{background:#e2e8f0}tr:nth-child(even){background:#f8fafc}.scroll{overflow:auto}img{width:100%;height:auto;background:white;border:1px solid #cbd5e1}figure{margin:25px 0}figcaption{color:#475569}a{color:#155eab}nav{padding:18px;background:#e0f2fe}code,pre{overflow:auto}</style>', '<h1>Task03-I — Shape-First Voxel Precompression + 3D FPS Cap</h1>', f'<nav>Run {output.name}<br><a href="../../docs/visual-graph-integration/03i_voxel_structural_sampling.md">결과 Markdown</a> · ' '<a href="../../docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md">승인 계획</a><br>'+ ' · '.join(f'<a href="{f}">{f}</a>' for f in artifacts if not f.endswith('.html'))+'</nav>'] for kind,value in blocks: if kind=='h':md.extend(['## '+value,'']);page.append('<h2>'+html.escape(value)+'</h2>') elif kind=='p':md.extend([value,'']);page.append('<p>'+html.escape(value)+'</p>') elif kind=='image': filename,caption=value;md.extend([f'','']) page.append(f'<figure><a href="{filename}"><img src="{filename}" alt="{html.escape(caption)}"></a><figcaption>{html.escape(caption)}</figcaption></figure>') else: headers,rows=value esc=lambda x:str(x).replace('|','/').replace('\n',' ') md.extend(['| '+' | '.join(map(esc,headers))+' |','| '+' | '.join(['---']*len(headers))+' |']) md.extend('| '+' | '.join(map(esc,row))+' |' for row in rows);md.append('') page.append('<div class="scroll"><table><thead><tr>'+''.join('<th>'+html.escape(str(v))+'</th>' for v in headers)+'</tr></thead><tbody>'+''.join('<tr>'+''.join('<td>'+html.escape(str(v))+'</td>' for v in row)+'</tr>' for row in rows)+'</tbody></table></div>') page.append('</html>') REPORT.write_text('\n'.join(md));(output/(STEM+'.html')).write_text('\n'.join(page))
def verify_documents(output): class Links(HTMLParser): def __init__(self):super().__init__();self.targets=[] def handle_starttag(self,tag,attrs):self.targets.extend(v for k,v in attrs if k in ('href','src')) parser=Links();page=(output/(STEM+'.html')).read_text();parser.feed(page) if re.search(r'<script[^>]+src=|\bfetch\s*\(|https?://',page):raise AssertionError('external/dynamic HTML dependency') for target in parser.targets: if Path(target).is_absolute() or not (output/target).is_file():raise AssertionError('bad HTML link '+target) mdlinks=re.findall(r'\]\(([^)]+)\)',REPORT.read_text()) for target in mdlinks: if Path(target).is_absolute() or not (REPORT.parent/target).is_file():raise AssertionError('bad Markdown link '+target) decoded={} for filename in FIGURES: a=plt.imread(output/filename) if min(a.shape[:2])<400 or not np.isfinite(a).all() or a.std()<.01:raise AssertionError('bad PNG '+filename) decoded[filename]=list(a.shape) return dict(status='PASS',html_relative_links=len(parser.targets),markdown_relative_links=len(mdlinks),png_decoded=decoded, static_no_cdn_no_fetch=True)
def preserved(baseline): current={p:prior.sha(Path(p)) for p in baseline['hashes']} require_equal(current,baseline['hashes'],'protected original hashes') require_equal(subprocess.check_output(['git','rev-parse','HEAD'],cwd=REPO,text=True).strip(),baseline['head'],'HEAD unchanged') return dict(status='PASS',protected_file_count=len(current),all_sha256_unchanged=True,HEAD_unchanged=True)
def run(baseline_path): if REPORT.exists():raise FileExistsError('existing result report; refusing overwrite') if os.environ.get('WANDB_MODE')!='disabled':raise ValueError('WANDB_MODE=disabled required') baseline=json.loads(baseline_path.read_text());preserved(baseline) source_paths=sorted(set([Path(__file__),Path(__file__).with_name('test_voxel_structural_sampling.py'),PLAN, *[p for p in (REPO/'visual/runtime').rglob('*.py')],REPO/'utils/experiment_logger.py',REPO/'utils/experiment_artifacts.py'])) source_hash=prior.hashes(source_paths) config=dict(task='03-I',rules=RULES,source_sha256=source_hash,protected_baseline_sha256=prior.sha(baseline_path), source_run_id=prior.SOURCE_RUN,baseline_run_id=local.BASELINE_ID,fixture_run_id=FIXTURE_RUN.name, python=platform.python_version(),numpy=np.__version__,platform=platform.platform(),device='cpu', simulator_executed=False,gpu_executed=False,baseline_FPS_executed=False,production_policy_adopted=False) with ExperimentLogger(team='visual',config=config,seed=0,model='task03i_voxel_precompression_3d_fps_cap',job_type='evaluate') as logger: output=logger.directory def registered(path,kind='reports'):logger.link_output(path,kind=kind) try: write_json(output/'git_start.json',dict(head=baseline['head'],status=baseline['git_status'])) (output/'git_start.diff').write_text(baseline['git_diff']) shutil.copyfile(baseline_path,output/'protected_baseline.json') write_json(output/'preregistered_config.json',config);config_sha=prior.sha(output/'preregistered_config.json') for path in source_paths: dest=output/'source_snapshot'/path.relative_to(REPO);dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,dest) for filename in ('git_start.json','git_start.diff','protected_baseline.json','preregistered_config.json'):registered(output/filename) with (output/'tests.log').open('w') as log: process=subprocess.run([sys.executable,'-m','unittest',*TESTS,'-v'],cwd=REPO,stdout=log,stderr=subprocess.STDOUT) registered(output/'tests.log') if process.returncode:raise RuntimeError('required contracts failed; no real selection performed') tests=(output/'tests.log').read_text();summary=next(s for s in tests.splitlines() if s.startswith('Ran '))+'; '+tests.splitlines()[-1] print(summary,flush=True) frame,geometry,samples,cases,zero,old,input_config,contracts=local.load_actual() baselines=load_baselines(cases,zero,samples) selections={} for name,case in cases.items(): selections[name]=select(case['candidate_flat'],case['candidate_xyz'],case['support_flat'],case['support_xyz'], frame.depth.shape,frame.intrinsic,case['seed'],case['first'],case['budget']) check_selection(case,selections[name]) require_equal(sum(len(s['F']) for s in selections.values()),256,'total Final budget') synthetic=load_synthetic_observations() selection_sha,selection_data=freeze_selection(output,cases,selections,synthetic) registered(output/'selection_before_gt.npz') write_json(output/'selection_before_gt.json',dict(sha256=selection_sha,gt_connected=False, actual={name:dict(scale=s['scale'],dyadic=s['dyadic'],anchor=s['grouping']['anchor'], counts={k:len(s[k]) for k in ('R','P','S','F')}) for name,s in selections.items()}, synthetic={name:dict(scale=s['chosen']['scale'],anchor=s['chosen']['grouping']['anchor']) for name,s in synthetic.items()})) registered(output/'selection_before_gt.json') print('All selections frozen before GT:',output.name,flush=True) t0=perf_counter() actual,synth_result,arrays,contexts=evaluate_after_freeze(output,selection_sha,frame,geometry,samples,cases,selections,baselines,synthetic,input_config) result=dict(run_id=logger.run_id,config=config,tests_summary=summary,actual=actual,synthetic=synth_result, selection_before_gt_sha256=selection_sha,evaluation_ms=(perf_counter()-t0)*1000,source_contract=contracts, real_FPS_calls=dict(baseline=0,priority_cap=sum(len(s['R'])>32 for s in selections.values()),surface=2), synthetic_FPS_calls=dict(baseline=0,priority_cap=sum(len(d['chosen']['R'])>32 for d in synthetic.values())), policy_adopted=False) arrays.update(selection_data) np.savez_compressed(output/(STEM+'.npz'),**arrays);registered(output/(STEM+'.npz')) with np.load(output/(STEM+'.npz'),allow_pickle=False) as saved: for key,value in arrays.items():np.testing.assert_array_equal(saved[key],value,err_msg=key) write_json(output/(STEM+'.json'),result);registered(output/(STEM+'.json'),'metrics') plot_results(output,frame,cases,selections,result,arrays,synthetic,contexts) for filename in FIGURES:registered(output/filename) preservation=preserved(baseline) require_equal(prior.hashes(source_paths),source_hash,'executed source hashes') require_equal(prior.sha(output/'preregistered_config.json'),config_sha,'frozen config') require_equal(prior.sha(output/'selection_before_gt.npz'),selection_sha,'frozen selection after evaluation') write_json(output/'source_hashes.json',dict(sources_before=source_hash,sources_after=prior.hashes(source_paths), protected_before=baseline['hashes'],protected_after={p:prior.sha(Path(p)) for p in baseline['hashes']},preservation=preservation)) registered(output/'source_hashes.json') patch_text='' for path in (Path(__file__),Path(__file__).with_name('test_voxel_structural_sampling.py')): patch_text+=subprocess.run(['git','diff','--no-index','--','/dev/null',str(path.relative_to(REPO))],cwd=REPO,capture_output=True,text=True).stdout (output/'implementation.patch').write_text(patch_text);registered(output/'implementation.patch') verification=dict(status='pending report verification',required_tests=dict(summary=summary,modules=TESTS, pass_count=sum(' ... ok' in line for line in tests.splitlines()),fail_count=0,skip_count=sum(' ... skipped' in line for line in tests.splitlines())), baseline_exact=True,C_X_source_XYZ_exact=True,P_subset_R_subset_C_subset_X=True,no_padding_duplicates=True, fixed_origin_floor=True,centroid_representatives_original_only=True,variable_P_contract=True,dyadic_nested_counts=True, pre_GT_saved_readback_hash=selection_sha,selection_hash_unchanged_after_GT=True,feature_exact_available_only=True, same_pair_2px_AND_3mm=True,source_preservation=preservation,config_sha256=config_sha,NPZ_exact_readback=True, simulator_executed=False,gpu_executed=False,performance_improvement_is_PASS_condition=False, source_snapshots='source_snapshot/',static_browser_loading='pending') write_json(output/'verification.json',verification) write_reports(output,result) verification['documents']=verify_documents(output) verification['status']='PASS; static browser loading pending' write_json(output/'verification.json',verification);registered(output/'verification.json') registered(output/(STEM+'.html'));registered(REPORT) write_json(output/'git_end.json',dict(status=subprocess.check_output(['git','status','--short'],cwd=REPO,text=True),preservation=preserved(baseline))) registered(output/'git_end.json') logger.log({name:dict(compression=row['compression'],surface=row['methods']['voxel']['surface_mm']) for name,row in actual.items()},step=0,prefix='eval') print(output,flush=True) except Exception as exc: write_json(output/'attempt_failure.json',dict(error_type=type(exc).__name__,message=str(exc),real_selection_saved=(output/'selection_before_gt.npz').exists())) registered(output/'attempt_failure.json');raise return output
def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--baseline',type=Path,required=True) parser.add_argument('--finalize-saved',type=Path,help='Report/verification only; no FPS, evaluation, tests or new UUID') args=parser.parse_args() if args.finalize_saved:finalize_saved(args.finalize_saved,args.baseline) else:run(args.baseline)
def finalize_saved(output,baseline_path): """Finalize the completed local run after browser validation was waived.""" from utils.experiment_artifacts import register_existing_output result=json.loads((output/(STEM+'.json')).read_text()) require_equal(output.name,result['run_id'],'saved identity') metadata=json.loads((output/'metadata.json').read_text()) require_equal(metadata['status'],'finished','completed numerical run') immutable=[output/(STEM+'.json'),output/(STEM+'.npz'),output/'selection_before_gt.npz',output/'tests.log'] before={str(p):prior.sha(p) for p in immutable} require_equal(before[str(output/'selection_before_gt.npz')],result['selection_before_gt_sha256'],'saved pre-GT hash') baseline=json.loads(baseline_path.read_text());preservation=preserved(baseline) current=[Path(__file__),Path(__file__).with_name('test_voxel_structural_sampling.py')] for path in current: destination=output/'report_source_snapshot'/path.relative_to(REPO) destination.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(path,destination) report_patch='' for path in current: report_patch+=subprocess.run(['git','diff','--no-index','--',str(output/'source_snapshot'/path.relative_to(REPO)),str(path)], cwd=REPO,capture_output=True,text=True).stdout (output/'report_refinement.patch').write_text(report_patch) write_reports(output,result) verification=json.loads((output/'verification.json').read_text()) verification['documents']=verify_documents(output) verification['static_browser_loading']=dict(status='SKIP',reason='Computer-use permissions unavailable; user explicitly requested completion without browser execution',images_verified_by_decode=7) verification['status']='PASS for executed checks; browser loading SKIP by user instruction' ran=int(re.search(r'Ran (\d+) tests',result['tests_summary']).group(1)) verification['required_tests']['pass_count']=ran-verification['required_tests']['skip_count'] verification['source_preservation']=preservation verification['report_only_postprocessing']=dict(new_UUID=False,new_FPS=False,new_evaluation=False,numerical_artifacts_unchanged=True) write_json(output/'verification.json',verification) hashes=json.loads((output/'source_hashes.json').read_text()) hashes['report_generation_sources']=prior.hashes(current) hashes['final_protected_preservation']=preservation hashes['numerical_artifacts_before_after']=dict(before=before,after={str(p):prior.sha(p) for p in immutable}) require_equal(hashes['numerical_artifacts_before_after']['before'],hashes['numerical_artifacts_before_after']['after'],'report only preserves numerical artifacts') write_json(output/'source_hashes.json',hashes) for path in (REPORT,output/(STEM+'.html'),output/'verification.json',output/'source_hashes.json',output/'report_refinement.patch', *[(output/'report_source_snapshot'/p.relative_to(REPO)) for p in current]): register_existing_output(output,path,kind='reports') write_json(output/'git_end.json',dict(status=subprocess.check_output(['git','status','--short'],cwd=REPO,text=True),preservation=preserved(baseline))) register_existing_output(output,output/'git_end.json',kind='reports') print(json.dumps(dict(run_id=output.name,documents=verification['documents'],preservation=preservation,browser='SKIP',no_new_numerical_work=True)))
if __name__=='__main__':main()123version https://git-lfs.github.com/spec/v1oid sha256:9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426size 1998891234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495{ "status": "PASS for executed checks; browser loading SKIP by user instruction", "required_tests": { "summary": "Ran 86 tests in 0.677s; OK", "modules": [ "visual.runtime.test.test_voxel_structural_sampling", "visual.runtime.test.test_sampling", "visual.runtime.test.test_sampling_geometry", "visual.runtime.test.test_sampling_evaluation", "visual.runtime.test.test_priority_fps_metric_control", "visual.runtime.test.test_local_structural_sampling" ], "pass_count": 86, "fail_count": 0, "skip_count": 0 }, "baseline_exact": true, "C_X_source_XYZ_exact": true, "P_subset_R_subset_C_subset_X": true, "no_padding_duplicates": true, "fixed_origin_floor": true, "centroid_representatives_original_only": true, "variable_P_contract": true, "dyadic_nested_counts": true, "pre_GT_saved_readback_hash": "9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426", "selection_hash_unchanged_after_GT": true, "feature_exact_available_only": true, "same_pair_2px_AND_3mm": true, "source_preservation": { "status": "PASS", "protected_file_count": 3092, "all_sha256_unchanged": true, "HEAD_unchanged": true }, "config_sha256": "b5c251c7ad9d7cbc9d7c49cae3ffa0faa3505e5de918e705b2d2fb80bb36ae99", "NPZ_exact_readback": true, "simulator_executed": false, "gpu_executed": false, "performance_improvement_is_PASS_condition": false, "source_snapshots": "source_snapshot/", "static_browser_loading": { "status": "SKIP", "reason": "Computer-use permissions unavailable; user explicitly requested completion without browser execution", "images_verified_by_decode": 7 }, "documents": { "status": "PASS", "html_relative_links": 26, "markdown_relative_links": 22, "png_decoded": { "primary_selection.png": [ 1269, 1831, 4 ], "resolution_budget.png": [ 1184, 1783, 4 ], "primary_distances.png": [ 1334, 1934, 4 ], "peg_gt.png": [ 1330, 2051, 4 ], "box_gt.png": [ 1330, 2135, 4 ], "depth_roi_surface.png": [ 1334, 2235, 4 ], "synthetic.png": [ 3460, 2284, 4 ] }, "static_no_cdn_no_fetch": true }, "report_only_postprocessing": { "new_UUID": false, "new_FPS": false, "new_evaluation": false, "numerical_artifacts_unchanged": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124{ "task": "03-I", "rules": { "frame": 0, "episode": "ep000", "camera": "base_camera", "method": "S3 optimized PCA5", "orientation": "strict >20 degrees, stored C only", "seed": 0, "priority_cap_per_object": 32, "final_targets": { "peg": 129, "box": 127 }, "total_cap": 256, "structural_ratio": 0.25, "scale": "median Z of original X; epsilon=z*sqrt((2/fx)^2+(2/fy)^2); a=epsilon/sqrt(3)", "multiplier": 1.0, "grid": "CV camera metres; origin 0; float64 floor(xyz/a); int64; half-open", "representative": "float64 centroid nearest original C; exact squared-distance tie smallest source", "order": "C/R source ascending; mapped anchor first in P; rest FPS or source ascending", "anchor": "original whole-C seeded anchor cell representative", "cap": "existing Euclidean 3D fps_indices", "surface": "existing whole-X 3D FPS initial=P; unused Priority becomes Surface; no padding", "dyadic": "count-only; floor_divide nominal keys by 2; first count<=32; never used for selection", "gt": "only after all real/synthetic selections saved, read back and hashed; same-pair <=2px AND <=3mm", "score": "none; no optimized dense C score available", "uv_bins": [ 4, 4 ], "xyz_bins": [ 2, 2, 2 ], "synthetic_names": [ "line_uniform", "line_dense", "separated_clean", "separated_noise", "camera_near", "camera_far", "camera_occluded" ], "synthetic_scale": "stored C median Z; stored focal=1600px", "synthetic_uncertainty_calibration": "N/A: no actual PCA5 estimator/localization evidence", "interpretation": "first feasibility of voxel precompression + 3D FPS cap; anchor also changes" }, "source_sha256": { "docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md": "5a1a63de2865ff3292bd03d00d3ff74842219f452c2b747e70b4b9b0a766e579", "utils/experiment_artifacts.py": "04a9eef116d5a56f9f4a9fd511d050a09ccc774c73a4bdb63f3cc00c09c8132f", "utils/experiment_logger.py": "76e0c1088377810d6415c1a33c1e4e3259bcfa918b0559d7b630f800727dbe45", "visual/runtime/edge_evidence.py": "2c896cc60e50f50f2b55ea377d34a6e15bffab875df2a8653dfe1b9830d30f2d", "visual/runtime/geometry.py": "36d20b7873d5ef9e1381e3bbe319da89e16fa5b44455488786dadd250bd814a9", "visual/runtime/grounding.py": "3c372c90aa3b77edb598e4222d2747cdd17ef979898b12602e14401cf3bcda7b", "visual/runtime/initialization.py": "27800d6c5b5cddff28209a371dbe6fe1c0e8c84bf2a54ad049345a3fb1fa1252", "visual/runtime/normal_estimators.py": "bf080a3ece0e2de6c7439257b943a3e44fdd8236010e526c202c15bcd57cdf2e", "visual/runtime/pca.py": "7a1a5fc459faed561497597d217f037b7b637d70497174d591d87c5156196517", "visual/runtime/rgbd.py": "be76fef13d5f58a7199f3952c1f59ce3bf9d1a2ddac09a6773dce39e9f891164", "visual/runtime/sampling.py": "45860d0adfbefb2818b67fe5705cb8c36d7c344c1c52c44d4ca5abc6765e37ed", "visual/runtime/test/benchmark_pca_cuda.py": "052e300cb9b7aedc04dae3cd20c22614ebcdd2f1d0e0bae482271e325fded84a", "visual/runtime/test/benchmark_pca_streaming.py": "2ad4ddcaa33a03f7922f79312f8d959b9ad92fa2bfa2a03a718f13f866a26fcb", "visual/runtime/test/normal_diagnostics.py": "d3da4f81a2452a9e11c4781ade557af5baeed96a2593876fdda768efb89ffddc", "visual/runtime/test/normal_estimators.py": "3b8d15c3a55fe124956a75601ceb244204579dd0bef64720ca4524ccec24a692", "visual/runtime/test/pca_optimized.py": "3ea4a2c3e80f8dd6b66baf366d8f75214810cc79a79ff9a2bbd2cef2c811c890", "visual/runtime/test/pca_torch.py": "6a27dd01efbc411d88e8bd9a595c29797ce70f4d4308cc6c88b6af543defb482", "visual/runtime/test/pca_triton.py": "699100eee075ee11eb1a4b1b1e94bbd5da92d2e5733c5b99f7df462451e8e692", "visual/runtime/test/run_adaptive_node_budget.py": "3ddfa394bb81e7a82d0a0f8d65e4146caad3243c4fe13359eb4dd4233b2b0cc9", "visual/runtime/test/run_candidate_count_matched.py": "df2b3ea2a6b80262e016a13bc02256965a4524cb18647dadac85018450393738", "visual/runtime/test/run_geometry.py": "cd051a6bbae95593351b8c10d96a413216c768550bac2221d58ce8b55d1727c3", "visual/runtime/test/run_geometry_aware_sampling.py": "6fcfd638a929e793ba920297942f2b85eb6b00b066058dd0133d32a358648276", "visual/runtime/test/run_grounding.py": "86fa4d84acd43a69e31e7e240ea79d19d9e26f33ea9fcc1a64fb8018fcf7d89d", "visual/runtime/test/run_local_structural_sampling.py": "4f65391c281fa8143d4be35bec957f979b11440be3178b7ae903a66fc7bc525f", "visual/runtime/test/run_normal_comparison.py": "b3caa29120144be1affbd8b9329b95ae24750ff3bd7736832cc2e69bc9e1816b", "visual/runtime/test/run_normal_diagnostics.py": "688c07957dd04e3ee7abbcebf962745199a194df317a266e2642c9d8bdae64aa", "visual/runtime/test/run_pca_optimization.py": "4353e5a59377ff8e918df564d215385feb4c8394d378e34f80b1451cbe195b0b", "visual/runtime/test/run_priority_fps_metric_control.py": "c01afcd516f3cf2b1f1d34d5878be2376e849e50dc7c1b809854d8f5231d1ca9", "visual/runtime/test/run_priority_fps_seed_control.py": "e9ecf5d8d4fb140242063c341711cff787d14dada2cb362f50706def372b7a26", "visual/runtime/test/run_priority_fps_trace.py": "f41905efd42b375f74da5baaac770ade914df21f192bda3a6182792edae68f3b", "visual/runtime/test/run_rgbd.py": "374bf129dc2eaf7f9c000a9b19fa2816ce1c0580ec59bc79ca326c7e198a363a", "visual/runtime/test/run_rim_bottleneck.py": "8323bd3048438be9c90b663f1bc03ef6fdfd67d10eb123c1fd4930538428fda3", "visual/runtime/test/run_sampling.py": "dcbcb9a20c71555f836a5b13fc5c0b556d73eda430dbff1ecb119d0776689081", "visual/runtime/test/run_structural_edges.py": "eb123019b2606a37d9c629aac7c4e3f2a77c14b577141485cb7e1a94b117e2fe", "visual/runtime/test/run_tracking.py": "28689bad6afcf0116cd23596e8ec09e5601fcb9b6f35ae093d1972bcc4af10f3", "visual/runtime/test/run_voxel_structural_sampling.py": "e4c7105e5150911a947b857efc81f8f9fa23c7bf5f5f794998425142b2e1ba95", "visual/runtime/test/sampling_evaluation.py": "daebf8834d2c0d4ca7f95e927c87ed3d6c7fc3777909a49504e265443585d60b", "visual/runtime/test/sampling_plots.py": "fca7005f90f5f665c823fc9ae147e1ca1917285367655f6dcb30ed5144a1e223", "visual/runtime/test/structural_edges.py": "bd9db684acff23a64ef5f2fff53cf35cf6eb5b36805c1f43e5e60bd2cd9102f2", "visual/runtime/test/test_adaptive_node_budget.py": "d74c250c7380fc92a0b7983be773743531eb5acd6d6d631ab423fb7cb07d4189", "visual/runtime/test/test_candidate_count_matched.py": "17f5a36e36d53cceefb9860e1e4953c5d6c668701000386417ed15cd46fa913d", "visual/runtime/test/test_geometry.py": "cff95cb959cd0ccdb6370b907c6d50c04fd3cc1770d4111e3459c8d5d2c2924d", "visual/runtime/test/test_geometry_aware_sampling.py": "cf2bd9fd5a1915b6d9fc3194898342745d6c0ba28355a306c303149f0b9eaf5f", "visual/runtime/test/test_geometry_evaluation.py": "27c2bd3c46cb2ddbc67fa58f8899b70b178640aa7b05e90349d5272e7633c866", "visual/runtime/test/test_initialization.py": "8a9928a656f3b02d55a07f3dde798df96053217f7829ef61494cb3dc879f34e0", "visual/runtime/test/test_local_structural_sampling.py": "d6758da4be04c7622a40ed9226503e6d2884de89f08992fc731200c8d21d7994", "visual/runtime/test/test_normal_comparison.py": "cc3e5cfe1dd9322412fc939247c4dd4258e22ca09eec77a07ce2d18d9513ab79", "visual/runtime/test/test_normal_diagnostics.py": "62898a79895a74d9e982d7ccb1996ca44a99af3a9890c18d2776a74a4680e5b4", "visual/runtime/test/test_pca_optimized.py": "a41d5a75b8e38987d17bd697efe538f776a530df753301d8666ded2e82fe8ad1", "visual/runtime/test/test_priority_fps_metric_control.py": "92977784be3da1c7151d2a032acefa1009e1ccf930d8514eec5623086613b565", "visual/runtime/test/test_priority_fps_seed_control.py": "69c8b3a1c420bec843bd8a3d948db009cd78c9ea6c99cb1376e15b60c3f47645", "visual/runtime/test/test_priority_fps_trace.py": "60e7a8a69c538c325cd59cf81527b52b09b19f1fdd4464025e02de39744c8f0a", "visual/runtime/test/test_rgbd.py": "bc2331b428c41276711156781771d820201c8b5da9d2e5e5efb785273e1e66c3", "visual/runtime/test/test_rgbd_evaluation.py": "4e931d5f562f70ca967505c437c7f93fe0be8dcaacfe6169db88171bad229942", "visual/runtime/test/test_sampling.py": "84240df749df06534e961db4e98418928230ef3cdbe920946d7489f2fab9dc60", "visual/runtime/test/test_sampling_evaluation.py": "8ec490314b6e55b3d4c0bc2b05f37036bf07fa3462039fd8b1676227d0a3b0bd", "visual/runtime/test/test_sampling_geometry.py": "a6df427b8510d0018931f637eb3c3357d3ed57211cd592ab07d7b8c8094de031", "visual/runtime/test/test_structural_edges.py": "c270dc3def473fb7730801a73cf2e6eb6cd7287e7883b839b2e18969d33ccf0e", "visual/runtime/test/test_voxel_structural_sampling.py": "88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620", "visual/runtime/tracking.py": "001630b2a71094182d488ba079dc13f6bb7b9cb46f7f9f366aca6a0db3c32522" }, "protected_baseline_sha256": "ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967", "source_run_id": "2551448b0fae4c6bbce3caf48774275f", "baseline_run_id": "7f657cf88baf4f1f89e594252e243e1c", "fixture_run_id": "1f7ad262dd2e4b2fb0ac805a4eda5278", "python": "3.11.13", "numpy": "2.4.6", "platform": "macOS-27.0.1-arm64-arm-64bit", "device": "cpu", "simulator_executed": false, "gpu_executed": false, "baseline_FPS_executed": false, "production_policy_adopted": false}123456789{ "status": " M docs/visual-graph-integration/03_sampling.md\n M visual/runtime/test/sampling_evaluation.py\n M visual/runtime/test/test_sampling_evaluation.py\n?? docs/visual-graph-integration/03ab_adaptive_node_budget.md\n?? docs/visual-graph-integration/03ab_adaptive_node_budget_plan.md\n?? docs/visual-graph-integration/03d_box_rim_bottleneck_phase1.md\n?? docs/visual-graph-integration/03d_priority_fps_seed_control_phase3.md\n?? docs/visual-graph-integration/03d_priority_fps_seed_control_phase3_plan.md\n?? docs/visual-graph-integration/03d_priority_fps_trace_phase2.md\n?? docs/visual-graph-integration/03d_priority_fps_trace_phase2_plan.md\n?? docs/visual-graph-integration/03e_priority_fps_metric_control.md\n?? docs/visual-graph-integration/03e_priority_fps_metric_control_plan.md\n?? docs/visual-graph-integration/03f_local_structural_sampling.md\n?? docs/visual-graph-integration/03f_local_structural_sampling_plan.md\n?? docs/visual-graph-integration/03g_geometry_aware_sampling.md\n?? docs/visual-graph-integration/03g_geometry_aware_sampling_plan.md\n?? docs/visual-graph-integration/03h_candidate_count_matched.md\n?? docs/visual-graph-integration/03h_candidate_count_matched_plan.md\n?? docs/visual-graph-integration/03i_voxel_structural_sampling.md\n?? docs/visual-graph-integration/03i_voxel_structural_sampling_plan.md\n?? visual/runtime/test/run_adaptive_node_budget.py\n?? visual/runtime/test/run_candidate_count_matched.py\n?? visual/runtime/test/run_geometry_aware_sampling.py\n?? visual/runtime/test/run_local_structural_sampling.py\n?? visual/runtime/test/run_priority_fps_metric_control.py\n?? visual/runtime/test/run_priority_fps_seed_control.py\n?? visual/runtime/test/run_priority_fps_trace.py\n?? visual/runtime/test/run_rim_bottleneck.py\n?? visual/runtime/test/run_voxel_structural_sampling.py\n?? visual/runtime/test/test_adaptive_node_budget.py\n?? visual/runtime/test/test_candidate_count_matched.py\n?? visual/runtime/test/test_geometry_aware_sampling.py\n?? visual/runtime/test/test_local_structural_sampling.py\n?? visual/runtime/test/test_priority_fps_metric_control.py\n?? visual/runtime/test/test_priority_fps_seed_control.py\n?? visual/runtime/test/test_priority_fps_trace.py\n?? visual/runtime/test/test_voxel_structural_sampling.py\n", "preservation": { "status": "PASS", "protected_file_count": 3092, "all_sha256_unchanged": true, "HEAD_unchanged": true }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293test_GT_stage_unique_node_reference_same_pair_and_subset_losses (visual.runtime.test.test_voxel_structural_sampling.EvaluationContracts.test_GT_stage_unique_node_reference_same_pair_and_subset_losses) ... oktest_available_feature_exact_gather_variable_priority (visual.runtime.test.test_voxel_structural_sampling.EvaluationContracts.test_available_feature_exact_gather_variable_priority) ... oktest_protected_hash_failure_is_not_ignored (visual.runtime.test.test_voxel_structural_sampling.EvaluationContracts.test_protected_hash_failure_is_not_ignored) ... oktest_selection_signature_has_no_annotations_and_freeze_before_GT (visual.runtime.test.test_voxel_structural_sampling.EvaluationContracts.test_selection_signature_has_no_annotations_and_freeze_before_GT) ... oktest_variable_P_adapter_and_separate_reference_losses (visual.runtime.test.test_voxel_structural_sampling.EvaluationContracts.test_variable_P_adapter_and_separate_reference_losses) ... oktest_coincident_xyz_sources_collapse_without_duplicate (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_coincident_xyz_sources_collapse_without_duplicate) ... oktest_determinism_input_unchanged_and_bound (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_determinism_input_unchanged_and_bound) ... oktest_dyadic_parent_nesting_first_count_and_nonexact32 (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_dyadic_parent_nesting_first_count_and_nonexact32) ... oktest_dyadic_signed_int64_extremes_terminate (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_dyadic_signed_int64_extremes_terminate) ... oktest_fixed_origin_negative_floor_and_boundaries (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_fixed_origin_negative_floor_and_boundaries) ... oktest_invalid_grid_and_source_inputs_fail_closed (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_invalid_grid_and_source_inputs_fail_closed) ... oktest_representative_centroid_is_not_output_and_tie_source (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_representative_centroid_is_not_output_and_tie_source) ... oktest_scale_median_robust_to_extreme_max_and_uses_only_X (visual.runtime.test.test_voxel_structural_sampling.GridTests.test_scale_median_robust_to_extreme_max_and_uses_only_X) ... oktest_anchor_maps_to_representative_records_distance_pixels (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_anchor_maps_to_representative_records_distance_pixels) ... oktest_cap_reuses_existing_3d_fps_and_exact_source (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_cap_reuses_existing_3d_fps_and_exact_source) ... oktest_decomposition_nn_extra_and_ties (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_decomposition_nn_extra_and_ties) ... oktest_empty_P_distance_is_missing_not_zero (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_empty_P_distance_is_missing_not_zero) ... oktest_invalid_membership_coordinates_anchor_target (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_invalid_membership_coordinates_anchor_target) ... oktest_more_equal_fewer_occupied_and_zero_cap (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_more_equal_fewer_occupied_and_zero_cap) ... oktest_underfill_surface_empty_candidate_small_support_and_empty (visual.runtime.test.test_voxel_structural_sampling.SelectionTests.test_underfill_surface_empty_candidate_small_support_and_empty) ... 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/tmpgqyk6aef/out/f6f2483ed9d3492691e7ff68edb2ea33Frames 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_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) ... oktest_annotation_not_shared_or_required_by_priority (visual.runtime.test.test_local_structural_sampling.FixtureContracts.test_annotation_not_shared_or_required_by_priority) ... oktest_density_noise_camera_and_occlusion_are_input_changes_only (visual.runtime.test.test_local_structural_sampling.FixtureContracts.test_density_noise_camera_and_occlusion_are_input_changes_only) ... oktest_exact_seven_constants_and_reproducible_source_correspondence (visual.runtime.test.test_local_structural_sampling.FixtureContracts.test_exact_seven_constants_and_reproducible_source_correspondence) ... oktest_no_baseline_replay_or_production_control_entrypoints (visual.runtime.test.test_local_structural_sampling.FixtureContracts.test_no_baseline_replay_or_production_control_entrypoints) ... oktest_axis_and_balanced_cut_ties (visual.runtime.test.test_local_structural_sampling.GroupTests.test_axis_and_balanced_cut_ties) ... oktest_disjoint_exhaustive_partition_capacity_and_order (visual.runtime.test.test_local_structural_sampling.GroupTests.test_disjoint_exhaustive_partition_capacity_and_order) ... oktest_invalid_longer_axis_uses_valid_shorter_axis (visual.runtime.test.test_local_structural_sampling.GroupTests.test_invalid_longer_axis_uses_valid_shorter_axis) ... oktest_invalid_sources_fail_closed (visual.runtime.test.test_local_structural_sampling.GroupTests.test_invalid_sources_fail_closed) ... oktest_leaf_tie_and_equal_coordinate_not_divided (visual.runtime.test.test_local_structural_sampling.GroupTests.test_leaf_tie_and_equal_coordinate_not_divided) ... oktest_quota_capacity_round_robin_and_zero (visual.runtime.test.test_local_structural_sampling.GroupTests.test_quota_capacity_round_robin_and_zero) ... oktest_anchor_and_nonanchor_group_rng_and_order (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_anchor_and_nonanchor_group_rng_and_order) ... oktest_annotation_change_delete_does_not_affect_selection (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_annotation_change_delete_does_not_affect_selection) ... oktest_budgets_alignment_uniqueness_original_geometry_and_calls (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_budgets_alignment_uniqueness_original_geometry_and_calls) ... oktest_empty_candidates_shortfall_and_no_padding (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_empty_candidates_shortfall_and_no_padding) ... oktest_feature_unavailable_exact_compact_only (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_feature_unavailable_exact_compact_only) ... oktest_single_group_matches_global_priority_and_final_exact (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_single_group_matches_global_priority_and_final_exact) ... oktest_small_budget_zero_anchor_quota_does_not_force_selection (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_small_budget_zero_anchor_quota_does_not_force_selection) ... oktest_support_mapping_mismatch_and_bad_anchor_fail (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_support_mapping_mismatch_and_bad_anchor_fail) ... oktest_xy_ties_depth_invariance_and_same_xyz_distinct_sources (visual.runtime.test.test_local_structural_sampling.SelectionTests.test_xy_ties_depth_invariance_and_same_xyz_distinct_sources) ... oktest_empty_and_zero_bbox_na (visual.runtime.test.test_local_structural_sampling.SpatialEvaluationTests.test_empty_and_zero_bbox_na) ... oktest_grid_boundary_max_endpoint_zero_span_and_same_definition (visual.runtime.test.test_local_structural_sampling.SpatialEvaluationTests.test_grid_boundary_max_endpoint_zero_span_and_same_definition) ... oktest_known_distances_raw_normalized_and_worst_source (visual.runtime.test.test_local_structural_sampling.SpatialEvaluationTests.test_known_distances_raw_normalized_and_worst_source) ... oktest_region_equal_weight_differs_from_candidate_weight_and_no_group_input (visual.runtime.test.test_local_structural_sampling.SpatialEvaluationTests.test_region_equal_weight_differs_from_candidate_weight_and_no_group_input) ... ok
----------------------------------------------------------------------Ran 86 tests in 0.677s
OK123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210{ "artifacts": [ { "kind": "metrics", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/ae4815498798f8b910b5c66375231bb8ba39b021acf95805ddb82d426d603dce/metrics.json", "sha256": "ae4815498798f8b910b5c66375231bb8ba39b021acf95805ddb82d426d603dce", "size": 5716 }, { "kind": "metrics", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/1cf28febe8f33b4f62654dd50886c3196dfdb34920a46ef25c1836089debe1c8/voxel_structural_sampling.json", "sha256": "1cf28febe8f33b4f62654dd50886c3196dfdb34920a46ef25c1836089debe1c8", "size": 2154854 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4ad29586893b1e4621423ef0e284da0ed5c30d46a34d6601fd2f014ebe595da0/git_start.json", "sha256": "4ad29586893b1e4621423ef0e284da0ed5c30d46a34d6601fd2f014ebe595da0", "size": 2158 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diff", "sha256": "2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5", "size": 15981 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967/protected_baseline.json", "sha256": "ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967", "size": 714086 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b5c251c7ad9d7cbc9d7c49cae3ffa0faa3505e5de918e705b2d2fb80bb36ae99/preregistered_config.json", "sha256": "b5c251c7ad9d7cbc9d7c49cae3ffa0faa3505e5de918e705b2d2fb80bb36ae99", "size": 9335 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ded04031d9104676536b76c89e15214251faa884c44b3fcb95f21c978f76ae63/tests.log", "sha256": "ded04031d9104676536b76c89e15214251faa884c44b3fcb95f21c978f76ae63", "size": 15831 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426/selection_before_gt.npz", "sha256": "9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426", "size": 199889 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06bb251620fc682e8f916d24eb06f38e4b82cd3cb9f0caa3f59f3bcb5b421caf/selection_before_gt.json", "sha256": "06bb251620fc682e8f916d24eb06f38e4b82cd3cb9f0caa3f59f3bcb5b421caf", "size": 7646 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88de6d8684943b17e29f1fbf7abe3ad2e44531fe153f69c73e5245b0b1dd419d/voxel_structural_sampling.npz", "sha256": "88de6d8684943b17e29f1fbf7abe3ad2e44531fe153f69c73e5245b0b1dd419d", "size": 1467363 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ca95318cabf4f2551a3a31ee4d2b4aa278f0668bd375658d252ddbd916b4644d/primary_selection.png", "sha256": "ca95318cabf4f2551a3a31ee4d2b4aa278f0668bd375658d252ddbd916b4644d", "size": 575329 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/6a8d4489a3e71e5405c1d4a7a2f63f1d052d2480b0376d730c925a48b77cb7d7/resolution_budget.png", "sha256": "6a8d4489a3e71e5405c1d4a7a2f63f1d052d2480b0376d730c925a48b77cb7d7", "size": 130909 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/615e7b4d53d04455bc80bcbc86275ca7c5262f84a41100e2bd3ac68e93d4b3f2/primary_distances.png", "sha256": "615e7b4d53d04455bc80bcbc86275ca7c5262f84a41100e2bd3ac68e93d4b3f2", "size": 189259 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/79d9f4d7ff3eaa50772a08d7baaac1a5506853c823febd73846297fe8351d477/peg_gt.png", "sha256": "79d9f4d7ff3eaa50772a08d7baaac1a5506853c823febd73846297fe8351d477", "size": 1034304 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9868720e0b2cb973a7d70ee51777da533a27d2aa3b62cd1b6815f75a6650245c/box_gt.png", "sha256": "9868720e0b2cb973a7d70ee51777da533a27d2aa3b62cd1b6815f75a6650245c", "size": 289671 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/adadc5ff7b636910f0149a2f7346f182a95f2eadb8dd4eb61085952dbd3bd488/depth_roi_surface.png", "sha256": "adadc5ff7b636910f0149a2f7346f182a95f2eadb8dd4eb61085952dbd3bd488", "size": 167579 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/5c65ce227b78f697e97e1c8251ac8ed79c5754df3513bcf67e167dc8d8f4fe64/synthetic.png", "sha256": "5c65ce227b78f697e97e1c8251ac8ed79c5754df3513bcf67e167dc8d8f4fe64", "size": 548072 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ccf39663ec5c351432aa136e6eb32414a52288eb917787238e1a81981683acab/source_hashes.json", "sha256": "ccf39663ec5c351432aa136e6eb32414a52288eb917787238e1a81981683acab", "size": 1407244 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4220b00d3b0e384039f365d9aab2c26711f17f873fed8fb76b8fc9a5832995fe/implementation.patch", "sha256": "4220b00d3b0e384039f365d9aab2c26711f17f873fed8fb76b8fc9a5832995fe", "size": 79901 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b341724f3bff4db8f719eab6451b83d72c7155e6a172a5fe403f534884cdb42d/verification.json", "sha256": "b341724f3bff4db8f719eab6451b83d72c7155e6a172a5fe403f534884cdb42d", "size": 2551 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06606a548e8ee7cd492b4fc07d578135516b2c89a6396ed4833175fa500d0b15/voxel_structural_sampling.html", "sha256": "06606a548e8ee7cd492b4fc07d578135516b2c89a6396ed4833175fa500d0b15", "size": 22137 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/38e82d8bed4891a13ab38a98e9d1192a0a147a80eaa00c6627e778c36ec43b8a/03i_voxel_structural_sampling.md", "sha256": "38e82d8bed4891a13ab38a98e9d1192a0a147a80eaa00c6627e778c36ec43b8a", "size": 17470 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/cf6b9dcb33fc2d08f3a82b4d69326d456ab8035228542f6aea3ad688333aa94a/git_end.json", "sha256": "cf6b9dcb33fc2d08f3a82b4d69326d456ab8035228542f6aea3ad688333aa94a", "size": 2428 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/7282fefc9a1e253d6888bff797ed059d348946ac5c31b87e492ecdab778fcea9/report_refinement.patch", "sha256": "7282fefc9a1e253d6888bff797ed059d348946ac5c31b87e492ecdab778fcea9", "size": 8913 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/990c0de604aa9594cbe36b1987b7e55b44386b8814a34a3c83b7e9f954bee913/run_voxel_structural_sampling.py", "sha256": "990c0de604aa9594cbe36b1987b7e55b44386b8814a34a3c83b7e9f954bee913", "size": 70115 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620/test_voxel_structural_sampling.py", "sha256": "88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620", "size": 13230 }, { "kind": "reports", "path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e/report-29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e.zip", "sha256": "29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e", "size": 5164482 } ], "config_path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/config/d75156eeebf36319b7ac3dead743f759f0b4240e2bf2fa37a6b010e62099b824/config.yaml", "environment": null, "episode_metadata_paths": [], "git_commit": "2e10a51736826aa980f2fe79a801eb6c9da8e288", "git_dirty": true, "metrics_path": "visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/ae4815498798f8b910b5c66375231bb8ba39b021acf95805ddb82d426d603dce/metrics.json", "model_name": "task03i_voxel_precompression_3d_fps_cap", "random_seed": 0, "report_paths": [ "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4ad29586893b1e4621423ef0e284da0ed5c30d46a34d6601fd2f014ebe595da0/git_start.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diff", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967/protected_baseline.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b5c251c7ad9d7cbc9d7c49cae3ffa0faa3505e5de918e705b2d2fb80bb36ae99/preregistered_config.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ded04031d9104676536b76c89e15214251faa884c44b3fcb95f21c978f76ae63/tests.log", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426/selection_before_gt.npz", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06bb251620fc682e8f916d24eb06f38e4b82cd3cb9f0caa3f59f3bcb5b421caf/selection_before_gt.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88de6d8684943b17e29f1fbf7abe3ad2e44531fe153f69c73e5245b0b1dd419d/voxel_structural_sampling.npz", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ca95318cabf4f2551a3a31ee4d2b4aa278f0668bd375658d252ddbd916b4644d/primary_selection.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/6a8d4489a3e71e5405c1d4a7a2f63f1d052d2480b0376d730c925a48b77cb7d7/resolution_budget.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/615e7b4d53d04455bc80bcbc86275ca7c5262f84a41100e2bd3ac68e93d4b3f2/primary_distances.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/79d9f4d7ff3eaa50772a08d7baaac1a5506853c823febd73846297fe8351d477/peg_gt.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9868720e0b2cb973a7d70ee51777da533a27d2aa3b62cd1b6815f75a6650245c/box_gt.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/adadc5ff7b636910f0149a2f7346f182a95f2eadb8dd4eb61085952dbd3bd488/depth_roi_surface.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/5c65ce227b78f697e97e1c8251ac8ed79c5754df3513bcf67e167dc8d8f4fe64/synthetic.png", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ccf39663ec5c351432aa136e6eb32414a52288eb917787238e1a81981683acab/source_hashes.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4220b00d3b0e384039f365d9aab2c26711f17f873fed8fb76b8fc9a5832995fe/implementation.patch", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b341724f3bff4db8f719eab6451b83d72c7155e6a172a5fe403f534884cdb42d/verification.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06606a548e8ee7cd492b4fc07d578135516b2c89a6396ed4833175fa500d0b15/voxel_structural_sampling.html", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/38e82d8bed4891a13ab38a98e9d1192a0a147a80eaa00c6627e778c36ec43b8a/03i_voxel_structural_sampling.md", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/cf6b9dcb33fc2d08f3a82b4d69326d456ab8035228542f6aea3ad688333aa94a/git_end.json", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/7282fefc9a1e253d6888bff797ed059d348946ac5c31b87e492ecdab778fcea9/report_refinement.patch", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/990c0de604aa9594cbe36b1987b7e55b44386b8814a34a3c83b7e9f954bee913/run_voxel_structural_sampling.py", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620/test_voxel_structural_sampling.py", "visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e/report-29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e.zip" ], "run_id": "92f29716e76f4b998fe924f08e80357d", "schema_version": 1, "selection": [ "metrics", "reports" ], "task": null, "team": "visual", "wandb_run_id": "92f29716e76f4b998fe924f08e80357d"}visual/92f29716e76f4b998fe924f08e80357d/artifacts/config/d75156eeebf36319b7ac3dead743f759f0b4240e2bf2fa37a6b010e62099b824/config.yamlAdded+124
visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/1cf28febe8f33b4f62654dd50886c3196dfdb34920a46ef25c1836089debe1c8/voxel_structural_sampling.jsonAdded
visual/92f29716e76f4b998fe924f08e80357d/artifacts/metrics/ae4815498798f8b910b5c66375231bb8ba39b021acf95805ddb82d426d603dce/metrics.jsonAdded+102
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06606a548e8ee7cd492b4fc07d578135516b2c89a6396ed4833175fa500d0b15/voxel_structural_sampling.htmlAdded+52
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/06bb251620fc682e8f916d24eb06f38e4b82cd3cb9f0caa3f59f3bcb5b421caf/selection_before_gt.jsonAdded+313
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e/report-29bfbc780e42f60fe6b4ce26dcc9e6340375008899b56869ee8b2b341d9a7c0e.zipAdded+3
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/2a85e21142786e54bff67b4ce38cac8234f97f2581fe5fffcc8c13ae1e8331c5/git_start.diffAdded+259
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/38e82d8bed4891a13ab38a98e9d1192a0a147a80eaa00c6627e778c36ec43b8a/03i_voxel_structural_sampling.mdAdded+168
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4220b00d3b0e384039f365d9aab2c26711f17f873fed8fb76b8fc9a5832995fe/implementation.patchAdded+1074
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/4ad29586893b1e4621423ef0e284da0ed5c30d46a34d6601fd2f014ebe595da0/git_start.jsonAdded+4
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/5c65ce227b78f697e97e1c8251ac8ed79c5754df3513bcf67e167dc8d8f4fe64/synthetic.pngAdded

Large File Pointer Details
- SHA256: 5c65ce227b78f697e97e1c8251ac8ed79c5754df3513bcf67e167dc8d8f4fe64
- Pointer size: 131 Bytes
- Size of remote file: 548 kB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/615e7b4d53d04455bc80bcbc86275ca7c5262f84a41100e2bd3ac68e93d4b3f2/primary_distances.pngAdded

Large File Pointer Details
- SHA256: 615e7b4d53d04455bc80bcbc86275ca7c5262f84a41100e2bd3ac68e93d4b3f2
- Pointer size: 131 Bytes
- Size of remote file: 189 kB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/6a8d4489a3e71e5405c1d4a7a2f63f1d052d2480b0376d730c925a48b77cb7d7/resolution_budget.pngAdded

Large File Pointer Details
- SHA256: 6a8d4489a3e71e5405c1d4a7a2f63f1d052d2480b0376d730c925a48b77cb7d7
- Pointer size: 131 Bytes
- Size of remote file: 131 kB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/7282fefc9a1e253d6888bff797ed059d348946ac5c31b87e492ecdab778fcea9/report_refinement.patchAdded+95
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/79d9f4d7ff3eaa50772a08d7baaac1a5506853c823febd73846297fe8351d477/peg_gt.pngAdded

Large File Pointer Details
- SHA256: 79d9f4d7ff3eaa50772a08d7baaac1a5506853c823febd73846297fe8351d477
- Pointer size: 132 Bytes
- Size of remote file: 1.03 MB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88c39e5c3e853d29f219a0f573c0d14b350a5228ec6f806667641ca101119620/test_voxel_structural_sampling.pyAdded+214
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/88de6d8684943b17e29f1fbf7abe3ad2e44531fe153f69c73e5245b0b1dd419d/voxel_structural_sampling.npzAdded+3
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9868720e0b2cb973a7d70ee51777da533a27d2aa3b62cd1b6815f75a6650245c/box_gt.pngAdded

Large File Pointer Details
- SHA256: 9868720e0b2cb973a7d70ee51777da533a27d2aa3b62cd1b6815f75a6650245c
- Pointer size: 131 Bytes
- Size of remote file: 290 kB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/990c0de604aa9594cbe36b1987b7e55b44386b8814a34a3c83b7e9f954bee913/run_voxel_structural_sampling.pyAdded+907
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/9ca4c0adcea037cf37022845348c0d13a949e5a1a2bbb5fbfa5a93259a52f426/selection_before_gt.npzAdded+3
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/adadc5ff7b636910f0149a2f7346f182a95f2eadb8dd4eb61085952dbd3bd488/depth_roi_surface.pngAdded

Large File Pointer Details
- SHA256: adadc5ff7b636910f0149a2f7346f182a95f2eadb8dd4eb61085952dbd3bd488
- Pointer size: 131 Bytes
- Size of remote file: 168 kB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b341724f3bff4db8f719eab6451b83d72c7155e6a172a5fe403f534884cdb42d/verification.jsonAdded+95
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/b5c251c7ad9d7cbc9d7c49cae3ffa0faa3505e5de918e705b2d2fb80bb36ae99/preregistered_config.jsonAdded+124
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ca95318cabf4f2551a3a31ee4d2b4aa278f0668bd375658d252ddbd916b4644d/primary_selection.pngAdded

Large File Pointer Details
- SHA256: ca95318cabf4f2551a3a31ee4d2b4aa278f0668bd375658d252ddbd916b4644d
- Pointer size: 131 Bytes
- Size of remote file: 575 kB
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ccf39663ec5c351432aa136e6eb32414a52288eb917787238e1a81981683acab/source_hashes.jsonAdded
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/cf6b9dcb33fc2d08f3a82b4d69326d456ab8035228542f6aea3ad688333aa94a/git_end.jsonAdded+9
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ded04031d9104676536b76c89e15214251faa884c44b3fcb95f21c978f76ae63/tests.logAdded+93
visual/92f29716e76f4b998fe924f08e80357d/artifacts/reports/ec7972e4917401c4c436fce3bb60f15f714459a8b26c9bddd579a19057a32967/protected_baseline.jsonAdded
visual/92f29716e76f4b998fe924f08e80357d/manifests/72cb909c95433269381af39bb41161808a3797cef92988886b35d18fd038a7fd/manifest.jsonAdded+210