From 69dc566665884ae89e428edbe4f6d4dc37bcc783 Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 29 Oct 2026 09:10:00 +0300 Subject: [PATCH] feat(research): preserve urban geometry pipelines and qualification suites Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation. --- simulation/urban-mapping/README.md | 85 + simulation/urban-mapping/atlas.py | 2 + simulation/urban-mapping/mapping.py | 73 +- .../urban-mapping/vector/contour_evidence.py | 67 + .../urban-mapping/vector/contour_geometry.py | 83 + .../urban-mapping/vector/infer_vectors.py | 26 +- .../urban-mapping/vector/refine_contours.py | 188 + .../urban-mapping/vector/whole_vectors.py | 75 + simulation/urban-mapping/whole_scene.py | 92 + simulation/urban-mapping/worker-profile.json | 10 + simulation/urban-plan-research/README.rst | 534 ++ .../assembly_pass/README.rst | 66 + .../assembly_pass/assembly_evidence.py | 45 + .../assembly_pass/assembly_rules.py | 17 + .../assembly_pass/assembly_templates.py | 52 + .../assembly_pass/assembly_zigzag.py | 18 + .../assembly_pass/audit_assembly.py | 42 + .../assembly_pass/audit_assembly_joins.py | 33 + .../assembly_pass/bundle.json | 230 + .../assembly_pass/diagnose_assembly.py | 29 + .../assembly_pass/extract_assembly.py | 54 + .../assembly_pass/join_assembly.py | 62 + .../assembly_pass/refine_assembly.py | 97 + .../assembly_pass/render_assembly.py | 33 + .../assembly_pass/test_assembly.py | 38 + .../urban-plan-research/audit_refinement.py | 54 + .../urban-plan-research/beta_pass/README.rst | 81 + .../beta_pass/audit_beta.py | 45 + .../beta_pass/beta_profiles.py | 181 + .../urban-plan-research/beta_pass/bundle.json | 96 + .../beta_pass/refine_beta.py | 118 + .../beta_pass/render_beta.py | 41 + .../beta_pass/test_beta.py | 67 + .../urban-plan-research/boundary_anchors.py | 241 + .../boundary_competition.py | 77 + .../catalog_pass/README.rst | 80 + .../catalog_pass/audit_catalog.py | 34 + .../catalog_pass/bicycle_artwork.py | 7 + .../catalog_pass/bundle.json | 206 + .../catalog_pass/catalog_context.py | 17 + .../catalog_pass/catalog_dependencies.py | 12 + .../catalog_pass/catalog_dependency_pins.py | 1 + .../catalog_pass/catalog_evidence.py | 36 + .../catalog_pass/catalog_rules.py | 37 + .../catalog_pass/catalog_templates.py | 79 + .../catalog_pass/catalog_zigzag.py | 54 + .../catalog_pass/children_warning.svg | 15 + .../catalog_pass/extract_catalog.py | 54 + .../catalog_pass/inspect_bicycles.py | 24 + .../catalog_pass/inspect_catalog.py | 27 + .../catalog_pass/refine_catalog.py | 107 + .../catalog_pass/render_catalog.py | 33 + .../catalog_pass/render_plan.py | 109 + .../catalog_pass/test_catalog.py | 69 + .../completion_pass/README.rst | 85 + .../completion_pass/audit_completion.py | 68 + .../completion_pass/bundle.json | 126 + .../completion_pass/completion_profiles.py | 142 + .../completion_pass/refine_completion.py | 205 + .../completion_pass/render_completion.py | 41 + .../completion_pass/test_completion.py | 48 + .../component_pass/README.md | 83 + .../component_pass/audit_components.py | 34 + .../component_pass/bundle.json | 422 ++ .../component_pass/component_arrows.py | 41 + .../component_pass/component_bicycle.py | 52 + .../component_pass/component_conflicts.py | 30 + .../component_pass/component_evidence.py | 61 + .../component_pass/component_mosaics.py | 40 + .../component_pass/component_rules.py | 29 + .../component_pass/component_surface.py | 22 + .../component_pass/component_targets.py | 55 + .../component_pass/component_zigzag_rules.py | 16 + .../component_pass/diagnose_components.py | 26 + .../component_pass/paint_channels.py | 16 + .../component_pass/refine_components.py | 57 + .../component_pass/refine_zigzags.py | 55 + .../component_pass/render_components.py | 33 + .../component_pass/render_hypotheses.py | 43 + .../component_pass/test_components.py | 77 + .../component_pass/zigzag_evidence.py | 33 + .../component_pass/zigzag_mosaics.py | 46 + .../consensus_pass/README.rst | 80 + .../consensus_pass/audit_consensus.py | 30 + .../consensus_pass/bundle.json | 64 + .../consensus_pass/consensus_profiles.py | 97 + .../consensus_pass/refine_consensus.py | 70 + .../consensus_pass/render_consensus.py | 41 + .../consensus_pass/test_consensus.py | 54 + .../continuation_pass/README.rst | 108 + .../continuation_pass/assemble_plan.py | 157 + .../continuation_pass/audit_scene.py | 49 + .../continuation_pass/bundle.json | 57 + .../continuation_pass/continuations.py | 187 + .../continuation_pass/evidence_fields.py | 39 + .../continuation_pass/frontage_chains.py | 41 + .../continuation_pass/object_solver.py | 149 + .../continuation_pass/paint_dedup.py | 15 + .../continuation_pass/paint_families.py | 63 + .../continuation_pass/paint_templates.py | 85 + .../continuation_pass/reanchor.py | 83 + .../continuation_pass/recover_interfaces.py | 63 + .../continuation_pass/refine_scene.py | 128 + .../continuation_pass/render_plan.py | 105 + .../continuation_pass/render_scene.py | 58 + .../continuation_pass/road_glyph_presets.py | 42 + .../continuation_pass/test_refine.py | 81 + .../corridor_pass/README.rst | 67 + .../corridor_pass/audit_corridor.py | 33 + .../corridor_pass/bundle.json | 154 + .../corridor_pass/corridor_profiles.py | 81 + .../corridor_pass/coverage_evidence.py | 16 + .../corridor_pass/coverage_plan.py | 13 + .../corridor_pass/diagnose_corridor.py | 28 + .../corridor_pass/diagnose_coverage.py | 28 + .../corridor_pass/mapping.py | 216 + .../corridor_pass/refine_corridor.py | 116 + .../corridor_pass/render_corridor.py | 41 + .../corridor_pass/render_coverage.py | 43 + .../corridor_pass/row_evidence.py | 57 + .../corridor_pass/test_corridor.py | 42 + .../corridor_pass/validation.py | 75 + .../coverage_pass/README.md | 34 + .../coverage_pass/audit_coverage.py | 24 + .../coverage_pass/audit_scene.py | 64 + .../coverage_pass/bundle.json | 149 + .../coverage_pass/coverage_crossings.py | 11 + .../coverage_pass/coverage_evidence.py | 50 + .../coverage_pass/coverage_patterns.py | 11 + .../coverage_pass/coverage_rules.py | 15 + .../coverage_pass/refine_coverage.py | 36 + .../coverage_pass/refine_crossings.py | 42 + .../coverage_pass/refine_patterns.py | 83 + .../coverage_pass/render_coverage_changes.py | 41 + .../coverage_pass/test_coverage.py | 48 + .../coverage_pass/zigzag_segments.py | 54 + .../discovery_pass/README.rst | 64 + .../discovery_pass/audit_discovery.py | 32 + .../discovery_pass/bundle.json | 116 + .../discovery_pass/discovery_evidence.py | 29 + .../discovery_pass/discovery_rules.py | 69 + .../discovery_pass/extract_discovery.py | 64 + .../discovery_pass/fragment_templates.py | 97 + .../discovery_pass/refine_discovery.py | 97 + .../discovery_pass/render_discovery.py | 31 + .../discovery_pass/test_discovery.py | 54 + .../driveway_refinement.py | 55 + .../urban-plan-research/evaluation/README.md | 40 + .../evaluation/ablation.py | 71 + .../evaluation/analyze_execution_profile.py | 65 + .../evaluation/benchmark_array_io.py | 107 + .../evaluation/compare_frozen_runs.py | 157 + .../evaluation/compare_pipeline_maps.py | 59 + .../evaluation/contract_preflight.py | 112 + .../evaluation/execution_profile.py | 139 + .../evaluation/explain_run_metadata.py | 163 + .../evaluation/geometry_metrics.py | 52 + .../evaluation/probe_background_cause.py | 248 + .../evaluation/profile_frozen_assembly.py | 63 + .../evaluation/qualify_control_tail.py | 50 + .../evaluation/qualify_execution_reuse.py | 58 + .../evaluation/qualify_shared_survey.py | 116 + .../evaluation/qualify_stroke_execution.py | 31 + .../evaluation/qualify_systematic.py | 54 + .../evaluation/qualify_topdown.py | 127 + .../evaluation/queue_worker_canary.py | 166 + .../evaluation/render_spatial_control.py | 106 + .../evaluation/retire_mapper_builds.py | 48 + .../evaluation/run_control_tail.py | 137 + .../evaluation/run_frozen_tail.py | 92 + .../evaluation/run_shared_survey_worker.py | 243 + .../evaluation/run_systematic_worker.py | 170 + .../evaluation/run_topdown_worker.py | 234 + .../evaluation/test_array_serialization.py | 38 + .../evaluation/test_execution_profile.py | 43 + .../evaluation/test_metadata_equivalence.py | 45 + .../evaluation/test_run_equivalence.py | 41 + .../families_pass/README.rst | 107 + .../families_pass/audit_families.py | 18 + .../families_pass/bundle.json | 36 + .../families_pass/crossing_completion.py | 106 + .../families_pass/line_family_completion.py | 60 + .../families_pass/refine_paint.py | 44 + .../families_pass/render_families.py | 37 + .../families_pass/test_families.py | 38 + .../urban-plan-research/frontage_chains.py | 37 + .../urban-plan-research/full_plan/README.rst | 54 + .../full_plan/assemble_layers.py | 150 + .../full_plan/audit_layers.py | 22 + .../urban-plan-research/full_plan/bundle.json | 27 + .../full_plan/crosswalk_family.py | 38 + .../full_plan/fit_scene.py | 15 + .../full_plan/layer_common.py | 13 + .../full_plan/render_layers.py | 64 + .../full_plan/semantic_layers.py | 40 + .../full_plan/source_facade_planes.py | 88 + .../full_plan/test_layers.py | 6 + .../urban-plan-research/gap_evidence.py | 75 + .../urban-plan-research/gap_observations.py | 55 + .../urban-plan-research/glyph_pass/README.md | 17 + .../glyph_pass/audit_glyph.py | 38 + .../glyph_pass/bundle.json | 171 + .../glyph_pass/diagnose_glyph.py | 29 + .../glyph_pass/diagnose_projection.py | 20 + .../glyph_pass/glyph_identity.py | 16 + .../glyph_pass/glyph_mosaics.py | 43 + .../glyph_pass/glyph_mosaics_inspect.py | 49 + .../glyph_pass/glyph_registration.py | 32 + .../glyph_pass/glyph_rules.py | 37 + .../glyph_pass/glyph_targets.py | 12 + .../glyph_pass/glyph_templates.py | 20 + .../glyph_pass/refine_glyph.py | 64 + .../glyph_pass/render_glyph.py | 33 + .../glyph_pass/test_glyph.py | 38 + .../intervals_pass/README.rst | 69 + .../intervals_pass/audit_intervals.py | 18 + .../intervals_pass/bundle.json | 38 + .../intervals_pass/interval_profiles.py | 151 + .../intervals_pass/line_reconstruction.py | 160 + .../intervals_pass/refine_intervals.py | 110 + .../intervals_pass/render_intervals.py | 41 + .../intervals_pass/test_intervals.py | 51 + .../urban-plan-research/joint_pass/README.md | 9 + .../joint_pass/audit_registration.py | 27 + .../joint_pass/bundle.json | 180 + .../joint_pass/inspect_recall.py | 22 + .../joint_pass/probe_bicycles.py | 68 + .../joint_pass/refine_registration.py | 35 + .../joint_pass/registered_template.py | 72 + .../joint_pass/registration.py | 132 + .../joint_pass/render_registration.py | 33 + .../joint_pass/small_bicycle.py | 52 + .../joint_pass/test_registration.py | 34 + .../urban-plan-research/lines_pass/README.rst | 101 + .../lines_pass/audit_lines.py | 19 + .../lines_pass/bundle.json | 34 + .../lines_pass/image_profiles.py | 69 + .../lines_pass/line_reconstruction.py | 160 + .../lines_pass/reconstruct_lines.py | 110 + .../lines_pass/render_lines.py | 41 + .../lines_pass/test_lines.py | 42 + .../long_edge_refinement.py | 50 + .../marking_pass/README.md | 9 + .../marking_pass/audit_markings.py | 33 + .../marking_pass/beta_profiles.py | 181 + .../marking_pass/bundle.json | 25 + .../marking_pass/diagnose_markings.py | 28 + .../marking_pass/discovery_evidence.py | 29 + .../marking_pass/discovery_rules.py | 69 + .../marking_pass/fit_scene.py | 15 + .../marking_pass/gost_catalog.py | 66 + .../marking_pass/interval_profiles.py | 151 + .../marking_pass/layer_common.py | 13 + .../marking_pass/line_reconstruction.py | 160 + .../marking_pass/marking_profiles.py | 40 + .../marking_pass/marking_rules.py | 81 + .../marking_pass/refine_markings.py | 112 + .../marking_pass/render_markings.py | 33 + .../marking_pass/render_plan.py | 77 + .../marking_pass/row_evidence.py | 57 + .../marking_pass/row_profiles.py | 85 + .../marking_pass/search_views.py | 42 + .../marking_pass/test_markings.py | 47 + .../urban-plan-research/material_regions.py | 71 + .../urban-plan-research/multiview/README.rst | 65 + .../urban-plan-research/multiview/method.json | 22 + .../multiview/model-profiles.json | 20 + .../multiview/mv_camera_audit.py | 30 + .../urban-plan-research/multiview/mv_fuse.py | 179 + .../urban-plan-research/multiview/mv_infer.py | 73 + .../urban-plan-research/multiview/mv_io.py | 42 + .../urban-plan-research/multiview/mv_math.py | 110 + .../urban-plan-research/multiview/mv_plan.py | 32 + .../multiview/mv_render.py | 77 + .../multiview/test_multiview.py | 69 + .../urban-plan-research/norms_pass/README.rst | 73 + .../norms_pass/audit_norms.py | 15 + .../norms_pass/bundle.json | 44 + .../norms_pass/gost_catalog.py | 66 + .../norms_pass/norm_profiles.py | 125 + .../norms_pass/refine_norms.py | 94 + .../norms_pass/render_norms.py | 41 + .../norms_pass/test_norms.py | 42 + .../urban-plan-research/orthophoto/README.rst | 88 + .../orthophoto/coordinate_cache.py | 22 + .../orthophoto/method.json | 22 + .../orthophoto/ortho_classes.py | 12 + .../orthophoto/ortho_render.py | 49 + .../orthophoto/ortho_segment.py | 58 + .../orthophoto/ortho_terrain.py | 64 + .../orthophoto/ortho_windows.py | 15 + .../orthophoto/test_ortho_pass.py | 42 + .../urban-plan-research/paint_templates.py | 55 + .../urban-plan-research/pipeline/README.md | 108 + .../pipeline/base/boundary_anchors.py | 204 + .../pipeline/base/curb_regularize.py | 12 + .../pipeline/base/geometry.py | 57 + .../pipeline/base/height_observations.py | 48 + .../pipeline/base/height_reference.py | 31 + .../pipeline/base/observed_boundaries.py | 106 + .../pipeline/base/qualify_junctions.py | 322 + .../pipeline/config-mv.json | 47 + .../pipeline/config-ortho.json | 25 + .../pipeline/definition.json | 5982 +++++++++++++++++ .../strip_validation/revalidate_strips.py | 48 + .../strip_validation/strip_validation.py | 15 + .../strip_validation/test_strip_validation.py | 27 + .../pipeline/timing-profile.json | 541 ++ .../pipeline/worker-profile.json | 13 + .../urban-plan-research/plan_acceptance.py | 42 + .../urban-plan-research/plan_boundaries.py | 43 + .../urban-plan-research/plan_continuity.py | 296 + .../urban-plan-research/plan_coverage.py | 81 + .../urban-plan-research/plan_junctions.py | 102 + .../urban-plan-research/plan_primitives.py | 106 + .../urban-plan-research/plan_refinement.py | 78 + simulation/urban-plan-research/plan_scene.py | 202 + simulation/urban-plan-research/plan_shapes.py | 117 + .../urban-plan-research/qualify_continuity.py | 82 + .../urban-plan-research/qualify_junctions.py | 343 + .../urban-plan-research/qualify_refinement.py | 96 + .../qualify_scene_assembly.py | 177 + .../qualify_scene_invariants.py | 49 + .../qualify_scene_junctions.py | 57 + .../urban-plan-research/recall_pass/README.md | 48 + .../recall_pass/audit_recall.py | 38 + .../recall_pass/bundle.json | 158 + .../recall_pass/diagnose_recall.py | 26 + .../recall_pass/recall_extent.py | 8 + .../recall_pass/recall_rules.py | 10 + .../recall_pass/recall_targets.py | 28 + .../recall_pass/recall_templates.py | 17 + .../recall_pass/refine_recall.py | 63 + .../recall_pass/render_recall.py | 33 + .../recall_pass/test_recall.py | 60 + .../refinement_evidence.py | 31 + .../registration_pass/README.md | 7 + .../registration_pass/audit_registration.py | 27 + .../registration_pass/bundle.json | 177 + .../registration_pass/refine_registration.py | 34 + .../registration_pass/registered_template.py | 51 + .../registration_pass/registration.py | 130 + .../registration_pass/render_registration.py | 33 + .../registration_pass/test_registration.py | 21 + .../replay/COMPACT_SYMBOLS.md | 34 + .../replay/LINEAR_WINDOWS.md | 52 + .../urban-plan-research/replay/README.rst | 160 + .../replay/arrow_admission.py | 49 + .../replay/arrow_admission_bundle.json | 401 ++ .../replay/arrow_evidence.py | 57 + .../replay/arrow_frames.py | 14 + .../replay/arrow_mosaics.py | 47 + .../replay/arrow_tip_registration.py | 37 + .../replay/audit_arrow_admission.py | 35 + .../replay/audit_arrow_sources.py | 37 + .../replay/audit_compact_symbols.py | 46 + .../replay/audit_completed_zigzags.py | 24 + .../replay/audit_linear_support.py | 87 + .../replay/audit_linear_windows.py | 88 + .../replay/audit_uniform_sources.py | 34 + .../replay/audit_zigzag_coverage.py | 24 + .../replay/compact_bicycle.py | 54 + .../replay/compact_evidence.py | 61 + .../replay/compact_mosaics.py | 44 + .../replay/compact_symbols_bundle.json | 398 ++ .../replay/compact_targets.py | 33 + .../replay/crossing_discovery.py | 108 + .../replay/diagnose_arrow_gates.py | 48 + .../replay/diagnose_marking_surfaces.py | 158 + .../replay/diagnose_remaining_patterns.py | 69 + .../replay/discover_crossings.py | 61 + .../replay/discover_uniform_arrows.py | 51 + .../replay/final_symbol_admission.py | 97 + .../replay/fit_standard_arrows.py | 45 + .../replay/fixed_arrow_bundle.json | 409 ++ .../replay/inspect_zigzag_gaps.py | 71 + .../replay/linear_coverage_views.py | 43 + .../replay/linear_window_support.py | 79 + .../replay/linear_windows_bundle.json | 35 + .../replay/merge_arrow_artwork.json | 119 + .../replay/paved_registration.py | 142 + .../replay/plan_linear_coverage.py | 25 + .../urban-plan-research/replay/pose_survey.py | 83 + .../replay/prefilter_compact_shape.py | 73 + .../replay/prefilter_compact_symbols.py | 33 + .../replay/prepare_compact_symbols.py | 132 + .../replay/prepare_uniform_symbols.py | 44 + .../replay/probe_compact_symbols.py | 72 + .../replay/refine_arrow_admission.py | 118 + .../replay/refine_standard_arrows.py | 78 + .../replay/refine_uniform_arrows.py | 66 + .../replay/refine_zigzag_extensions.py | 47 + .../replay/refine_zigzag_terminals.py | 45 + .../replay/render_arrow_admission.py | 44 + .../replay/render_compact_symbols.py | 44 + .../replay/render_linear_changes.py | 69 + .../replay/render_marking_overview.py | 46 + .../replay/render_standard_proposals.py | 44 + .../replay/semantic_compact_symbols.py | 49 + .../replay/standard_arrow_evidence.py | 32 + .../replay/standard_arrow_regions.py | 35 + .../replay/standard_arrow_templates.py | 73 + .../urban-plan-research/replay/survey_grid.py | 17 + .../replay/test_arrow_admission.py | 69 + .../replay/test_compact_symbols.py | 49 + .../replay/test_crossing_discovery.py | 36 + .../replay/test_standard_arrows.py | 49 + .../replay/test_zigzag_extensions.py | 31 + .../replay/test_zigzag_terminal_views.py | 19 + .../replay/verify_arrow_observations.py | 45 + .../replay/verify_discovered_crossings.py | 31 + .../replay/verify_standard_arrows.py | 47 + .../replay/verify_uniform_arrows.py | 49 + .../replay/verify_zigzag_extensions.py | 29 + .../replay/verify_zigzag_terminals.py | 30 + .../replay/zigzag_extension.py | 64 + .../replay/zigzag_extension_bundle.json | 419 ++ .../replay/zigzag_terminal.py | 71 + .../urban-plan-research/rows_pass/README.rst | 84 + .../rows_pass/audit_rows.py | 33 + .../urban-plan-research/rows_pass/bundle.json | 86 + .../rows_pass/refine_rows.py | 54 + .../rows_pass/render_rows.py | 41 + .../rows_pass/row_evidence.py | 56 + .../rows_pass/row_profiles.py | 85 + .../rows_pass/test_rows.py | 65 + .../search_pass/README.rst | 71 + .../search_pass/audit_search.py | 36 + .../search_pass/bundle.json | 168 + .../search_pass/corridor_profiles.py | 82 + .../search_pass/extract_search.py | 66 + .../search_pass/refine_search.py | 106 + .../search_pass/render_plan.py | 107 + .../search_pass/render_search.py | 33 + .../search_pass/search_rules.py | 7 + .../search_pass/search_views.py | 42 + .../search_pass/test_search.py | 28 + .../sections_pass/README.rst | 77 + .../sections_pass/audit_sections.py | 33 + .../sections_pass/bundle.json | 74 + .../sections_pass/refine_sections.py | 102 + .../sections_pass/render_sections.py | 41 + .../sections_pass/section_profiles.py | 82 + .../sections_pass/test_sections.py | 67 + .../shared_survey/README.md | 55 + .../shared_survey/compare_semantic_survey.py | 80 + .../shared_survey/semantic_consumers.py | 115 + .../shared_survey/semantic_survey.py | 153 + .../shared_survey/semantic_survey_stage.py | 190 + .../shared_survey/test_semantic_survey.py | 141 + .../surface_pass/audit_surface.py | 24 + .../surface_pass/bundle.json | 10 + .../surface_pass/diagnose_surface.py | 15 + .../surface_pass/refine_surface.py | 17 + .../surface_pass/surface_height.py | 34 + .../surface_pass/test_surface.py | 18 + .../urban-plan-research/survey_index.py | 23 + .../symbol_pass/README.rst | 34 + .../symbol_pass/audit_symbols.py | 25 + .../symbol_pass/bundle.json | 241 + .../symbol_pass/catalog_evidence.py | 36 + .../symbol_pass/prepare_symbols.py | 43 + .../symbol_pass/refine_symbols.py | 75 + .../symbol_pass/render_symbols.py | 33 + .../symbol_pass/review_symbols.py | 17 + .../symbol_pass/semantic_symbols.py | 33 + .../symbol_pass/symbol_evidence.py | 18 + .../symbol_pass/symbol_rules.py | 19 + .../symbol_pass/test_symbols.py | 36 + .../systematic/CONNECTED_PAINT.md | 25 + .../systematic/INITIAL_VIEWS.md | 33 + .../systematic/JOINT_ASSEMBLY.md | 43 + .../systematic/admit_marking_contracts.py | 37 + .../systematic/admit_primary_arrows.py | 45 + .../systematic/array_archive.py | 13 + .../systematic/arrow-contract-lock.json | 51 + .../systematic/assemble_paint.py | 92 + .../systematic/assemble_surfaces.py | 81 + .../systematic/batched_concepts.py | 37 + .../systematic/batched_row_evidence.py | 77 + .../systematic/body_profiles.py | 43 + .../systematic/cached_text_processor.py | 30 + .../systematic/catalog_observations.py | 40 + .../systematic/compact_observations.py | 43 + .../systematic/component_axis.py | 37 + .../systematic/conditional_replacements.py | 45 + .../systematic/connected_configurations.py | 80 + .../systematic/connected_ridges.py | 52 + .../systematic/coverage_semantics.py | 44 + .../systematic/crossing_fit.py | 59 + .../systematic/definition.json | 1891 ++++++ .../systematic/discover_primary_arrows.py | 49 + .../systematic/extract_observations.py | 55 + .../systematic/family_ownership.py | 39 + .../systematic/finite_strokes.py | 24 + .../systematic/fixed_observation_grid.py | 80 + .../systematic/initial_views.py | 130 + .../systematic/join_surfaces.py | 53 + .../systematic/joint_assembly.py | 106 + .../systematic/joint_choice.py | 120 + .../systematic/marking_rules.py | 99 + .../systematic/measured_row_graph.py | 102 + .../systematic/measured_rows.py | 51 + .../systematic/measurement_reads.py | 77 + .../systematic/object_context.py | 154 + .../systematic/object_evidence.py | 115 + .../systematic/observation_cache.py | 25 + .../systematic/observation_coverage.py | 61 + .../systematic/observation_tiles.py | 78 + .../systematic/observed_geometry.py | 21 + .../systematic/ortho_render.py | 113 + .../systematic/paint_conservation.py | 36 + .../systematic/paint_observations.py | 50 + .../systematic/paint_templates.py | 86 + .../systematic/paired_markings.py | 56 + .../systematic/prepare_primary_symbols.py | 88 + .../systematic/primary_components.py | 39 + .../systematic/primary_evidence.py | 14 + .../systematic/primary_line_observations.py | 37 + .../systematic/qualify_camera_ownership.py | 32 + .../qualify_component_axis_contract.py | 28 + .../systematic/qualify_concept_decoding.py | 54 + .../systematic/qualify_crossing_fit.py | 41 + .../systematic/qualify_family_ownership.py | 22 + .../qualify_initial_observations.py | 47 + .../systematic/qualify_primary_plan.py | 22 + .../systematic/qualify_row_graph_contract.py | 33 + .../systematic/qualify_strokes.py | 113 + .../systematic/reconstruct_primary_arrows.py | 13 + .../systematic/refine_markings.py | 248 + .../systematic/row_discovery.py | 75 + .../systematic/search_views.py | 47 + .../systematic/semantic_primary_symbols.py | 34 + .../systematic/semantic_survey.py | 150 + .../systematic/semantic_survey_stage.py | 195 + .../systematic/shared_surface_edges.py | 255 + .../systematic/solve_catalog.py | 107 + .../systematic/solve_crossings.py | 54 + .../systematic/stroke_axis.py | 46 + .../systematic/stroke_inventory.py | 19 + .../systematic/stroke_observations.py | 109 + .../systematic/stroke_seeds.py | 20 + .../test_conditional_replacements.py | 93 + .../test_connected_configurations.py | 53 + .../systematic/test_connected_ridges.py | 28 + .../systematic/test_initial_views.py | 69 + .../systematic/test_joint_choice.py | 86 + .../systematic/test_object_context.py | 81 + .../systematic/test_object_evidence.py | 86 + .../systematic/test_observed_geometry.py | 34 + .../systematic/test_shared_surface_edges.py | 130 + .../test_boundary_anchors.py | 166 + .../test_boundary_competition.py | 45 + .../urban-plan-research/test_gap_evidence.py | 60 + .../test_material_regions.py | 57 + .../urban-plan-research/test_observed_plan.py | 39 + .../test_plan_continuity.py | 153 + .../urban-plan-research/test_plan_geometry.py | 101 + .../test_plan_junctions.py | 67 + .../test_plan_refinement.py | 53 + .../urban-plan-research/test_plan_scene.py | 82 + .../urban-plan-research/test_plan_shapes.py | 36 + .../urban-plan-research/test_survey_index.py | 32 + .../test_transfer_contract.py | 27 + .../urban-plan-research/topdown/README.md | 179 + .../topdown/admission_contract.py | 84 + .../topdown/assemble_reviewed_state.py | 18 + .../topdown/audit_contract.py | 59 + .../topdown/audit_topdown.py | 95 + .../topdown/candidate_registry.py | 101 + .../topdown/conditional_contract_audit.py | 45 + .../topdown/depth_audit.py | 79 + .../topdown/direct_fixed.py | 229 + .../topdown/endpoint_cause_audit.py | 99 + .../topdown/feasibility_audit.py | 54 + .../topdown/ground_observations.py | 346 + .../topdown/head_observation.py | 36 + .../topdown/object_evidence.py | 30 + .../topdown/observation_checks.py | 145 + .../topdown/observation_evaluator.py | 78 + .../topdown/observed_fixed.py | 82 + .../topdown/orthographic_colour.py | 16 + .../topdown/orthographic_depth.py | 37 + .../topdown/paint_channels_fast.py | 54 + .../topdown/pixel_geometry.py | 31 + .../topdown/plan_marking_policy.py | 33 + .../topdown/plan_registration.py | 28 + .../topdown/pose_domain_audit.py | 65 + .../topdown/prepare_topdown.py | 75 + .../topdown/preservation.py | 32 + .../topdown/reconcile_objects.py | 86 + .../topdown/reconstruct_topdown.py | 127 + .../topdown/registration_evaluator.py | 66 + .../topdown/render_native_geometry.py | 129 + .../topdown/spatial_index.py | 25 + .../topdown/surface_audit.py | 38 + .../topdown/test_orthographic_colour.py | 44 + .../topdown/test_topdown.py | 647 ++ .../topdown/verify_topdown.py | 199 + .../transitions_pass/README.rst | 73 + .../transitions_pass/audit_transitions.py | 26 + .../transitions_pass/bundle.json | 54 + .../transitions_pass/refine_transitions.py | 77 + .../transitions_pass/render_transitions.py | 41 + .../transitions_pass/test_transitions.py | 30 + .../transitions_pass/transition_profiles.py | 92 + tests/test_contour_refinement.py | 102 + tests/test_systematic_pipeline.py | 162 + tests/test_urban_ablation.py | 49 + tests/test_urban_final_symbol_admission.py | 68 + tests/test_urban_linear_windows.py | 68 + 611 files changed, 52016 insertions(+), 28 deletions(-) create mode 100644 simulation/urban-mapping/vector/contour_evidence.py create mode 100644 simulation/urban-mapping/vector/contour_geometry.py create mode 100644 simulation/urban-mapping/vector/refine_contours.py create mode 100644 simulation/urban-mapping/vector/whole_vectors.py create mode 100644 simulation/urban-mapping/whole_scene.py create mode 100644 simulation/urban-mapping/worker-profile.json create mode 100644 simulation/urban-plan-research/README.rst create mode 100644 simulation/urban-plan-research/assembly_pass/README.rst create mode 100644 simulation/urban-plan-research/assembly_pass/assembly_evidence.py create mode 100644 simulation/urban-plan-research/assembly_pass/assembly_rules.py create mode 100644 simulation/urban-plan-research/assembly_pass/assembly_templates.py create mode 100644 simulation/urban-plan-research/assembly_pass/assembly_zigzag.py create mode 100644 simulation/urban-plan-research/assembly_pass/audit_assembly.py create mode 100644 simulation/urban-plan-research/assembly_pass/audit_assembly_joins.py create mode 100644 simulation/urban-plan-research/assembly_pass/bundle.json create mode 100644 simulation/urban-plan-research/assembly_pass/diagnose_assembly.py create mode 100644 simulation/urban-plan-research/assembly_pass/extract_assembly.py create mode 100644 simulation/urban-plan-research/assembly_pass/join_assembly.py create mode 100644 simulation/urban-plan-research/assembly_pass/refine_assembly.py create mode 100644 simulation/urban-plan-research/assembly_pass/render_assembly.py create mode 100644 simulation/urban-plan-research/assembly_pass/test_assembly.py create mode 100644 simulation/urban-plan-research/audit_refinement.py create mode 100644 simulation/urban-plan-research/beta_pass/README.rst create mode 100644 simulation/urban-plan-research/beta_pass/audit_beta.py create mode 100644 simulation/urban-plan-research/beta_pass/beta_profiles.py create mode 100644 simulation/urban-plan-research/beta_pass/bundle.json create mode 100644 simulation/urban-plan-research/beta_pass/refine_beta.py create mode 100644 simulation/urban-plan-research/beta_pass/render_beta.py create mode 100644 simulation/urban-plan-research/beta_pass/test_beta.py create mode 100644 simulation/urban-plan-research/boundary_anchors.py create mode 100644 simulation/urban-plan-research/boundary_competition.py create mode 100644 simulation/urban-plan-research/catalog_pass/README.rst create mode 100644 simulation/urban-plan-research/catalog_pass/audit_catalog.py create mode 100644 simulation/urban-plan-research/catalog_pass/bicycle_artwork.py create mode 100644 simulation/urban-plan-research/catalog_pass/bundle.json create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_context.py create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_dependencies.py create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_dependency_pins.py create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_evidence.py create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_rules.py create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_templates.py create mode 100644 simulation/urban-plan-research/catalog_pass/catalog_zigzag.py create mode 100644 simulation/urban-plan-research/catalog_pass/children_warning.svg create mode 100644 simulation/urban-plan-research/catalog_pass/extract_catalog.py create mode 100644 simulation/urban-plan-research/catalog_pass/inspect_bicycles.py create mode 100644 simulation/urban-plan-research/catalog_pass/inspect_catalog.py create mode 100644 simulation/urban-plan-research/catalog_pass/refine_catalog.py create mode 100644 simulation/urban-plan-research/catalog_pass/render_catalog.py create mode 100644 simulation/urban-plan-research/catalog_pass/render_plan.py create mode 100644 simulation/urban-plan-research/catalog_pass/test_catalog.py create mode 100644 simulation/urban-plan-research/completion_pass/README.rst create mode 100644 simulation/urban-plan-research/completion_pass/audit_completion.py create mode 100644 simulation/urban-plan-research/completion_pass/bundle.json create mode 100644 simulation/urban-plan-research/completion_pass/completion_profiles.py create mode 100644 simulation/urban-plan-research/completion_pass/refine_completion.py create mode 100644 simulation/urban-plan-research/completion_pass/render_completion.py create mode 100644 simulation/urban-plan-research/completion_pass/test_completion.py create mode 100644 simulation/urban-plan-research/component_pass/README.md create mode 100644 simulation/urban-plan-research/component_pass/audit_components.py create mode 100644 simulation/urban-plan-research/component_pass/bundle.json create mode 100644 simulation/urban-plan-research/component_pass/component_arrows.py create mode 100644 simulation/urban-plan-research/component_pass/component_bicycle.py create mode 100644 simulation/urban-plan-research/component_pass/component_conflicts.py create mode 100644 simulation/urban-plan-research/component_pass/component_evidence.py create mode 100644 simulation/urban-plan-research/component_pass/component_mosaics.py create mode 100644 simulation/urban-plan-research/component_pass/component_rules.py create mode 100644 simulation/urban-plan-research/component_pass/component_surface.py create mode 100644 simulation/urban-plan-research/component_pass/component_targets.py create mode 100644 simulation/urban-plan-research/component_pass/component_zigzag_rules.py create mode 100644 simulation/urban-plan-research/component_pass/diagnose_components.py create mode 100644 simulation/urban-plan-research/component_pass/paint_channels.py create mode 100644 simulation/urban-plan-research/component_pass/refine_components.py create mode 100644 simulation/urban-plan-research/component_pass/refine_zigzags.py create mode 100644 simulation/urban-plan-research/component_pass/render_components.py create mode 100644 simulation/urban-plan-research/component_pass/render_hypotheses.py create mode 100644 simulation/urban-plan-research/component_pass/test_components.py create mode 100644 simulation/urban-plan-research/component_pass/zigzag_evidence.py create mode 100644 simulation/urban-plan-research/component_pass/zigzag_mosaics.py create mode 100644 simulation/urban-plan-research/consensus_pass/README.rst create mode 100644 simulation/urban-plan-research/consensus_pass/audit_consensus.py create mode 100644 simulation/urban-plan-research/consensus_pass/bundle.json create mode 100644 simulation/urban-plan-research/consensus_pass/consensus_profiles.py create mode 100644 simulation/urban-plan-research/consensus_pass/refine_consensus.py create mode 100644 simulation/urban-plan-research/consensus_pass/render_consensus.py create mode 100644 simulation/urban-plan-research/consensus_pass/test_consensus.py create mode 100644 simulation/urban-plan-research/continuation_pass/README.rst create mode 100644 simulation/urban-plan-research/continuation_pass/assemble_plan.py create mode 100644 simulation/urban-plan-research/continuation_pass/audit_scene.py create mode 100644 simulation/urban-plan-research/continuation_pass/bundle.json create mode 100644 simulation/urban-plan-research/continuation_pass/continuations.py create mode 100644 simulation/urban-plan-research/continuation_pass/evidence_fields.py create mode 100644 simulation/urban-plan-research/continuation_pass/frontage_chains.py create mode 100644 simulation/urban-plan-research/continuation_pass/object_solver.py create mode 100644 simulation/urban-plan-research/continuation_pass/paint_dedup.py create mode 100644 simulation/urban-plan-research/continuation_pass/paint_families.py create mode 100644 simulation/urban-plan-research/continuation_pass/paint_templates.py create mode 100644 simulation/urban-plan-research/continuation_pass/reanchor.py create mode 100644 simulation/urban-plan-research/continuation_pass/recover_interfaces.py create mode 100644 simulation/urban-plan-research/continuation_pass/refine_scene.py create mode 100644 simulation/urban-plan-research/continuation_pass/render_plan.py create mode 100644 simulation/urban-plan-research/continuation_pass/render_scene.py create mode 100644 simulation/urban-plan-research/continuation_pass/road_glyph_presets.py create mode 100644 simulation/urban-plan-research/continuation_pass/test_refine.py create mode 100644 simulation/urban-plan-research/corridor_pass/README.rst create mode 100644 simulation/urban-plan-research/corridor_pass/audit_corridor.py create mode 100644 simulation/urban-plan-research/corridor_pass/bundle.json create mode 100644 simulation/urban-plan-research/corridor_pass/corridor_profiles.py create mode 100644 simulation/urban-plan-research/corridor_pass/coverage_evidence.py create mode 100644 simulation/urban-plan-research/corridor_pass/coverage_plan.py create mode 100644 simulation/urban-plan-research/corridor_pass/diagnose_corridor.py create mode 100644 simulation/urban-plan-research/corridor_pass/diagnose_coverage.py create mode 100644 simulation/urban-plan-research/corridor_pass/mapping.py create mode 100644 simulation/urban-plan-research/corridor_pass/refine_corridor.py create mode 100644 simulation/urban-plan-research/corridor_pass/render_corridor.py create mode 100644 simulation/urban-plan-research/corridor_pass/render_coverage.py create mode 100644 simulation/urban-plan-research/corridor_pass/row_evidence.py create mode 100644 simulation/urban-plan-research/corridor_pass/test_corridor.py create mode 100644 simulation/urban-plan-research/corridor_pass/validation.py create mode 100644 simulation/urban-plan-research/coverage_pass/README.md create mode 100644 simulation/urban-plan-research/coverage_pass/audit_coverage.py create mode 100644 simulation/urban-plan-research/coverage_pass/audit_scene.py create mode 100644 simulation/urban-plan-research/coverage_pass/bundle.json create mode 100644 simulation/urban-plan-research/coverage_pass/coverage_crossings.py create mode 100644 simulation/urban-plan-research/coverage_pass/coverage_evidence.py create mode 100644 simulation/urban-plan-research/coverage_pass/coverage_patterns.py create mode 100644 simulation/urban-plan-research/coverage_pass/coverage_rules.py create mode 100644 simulation/urban-plan-research/coverage_pass/refine_coverage.py create mode 100644 simulation/urban-plan-research/coverage_pass/refine_crossings.py create mode 100644 simulation/urban-plan-research/coverage_pass/refine_patterns.py create mode 100644 simulation/urban-plan-research/coverage_pass/render_coverage_changes.py create mode 100644 simulation/urban-plan-research/coverage_pass/test_coverage.py create mode 100644 simulation/urban-plan-research/coverage_pass/zigzag_segments.py create mode 100644 simulation/urban-plan-research/discovery_pass/README.rst create mode 100644 simulation/urban-plan-research/discovery_pass/audit_discovery.py create mode 100644 simulation/urban-plan-research/discovery_pass/bundle.json create mode 100644 simulation/urban-plan-research/discovery_pass/discovery_evidence.py create mode 100644 simulation/urban-plan-research/discovery_pass/discovery_rules.py create mode 100644 simulation/urban-plan-research/discovery_pass/extract_discovery.py create mode 100644 simulation/urban-plan-research/discovery_pass/fragment_templates.py create mode 100644 simulation/urban-plan-research/discovery_pass/refine_discovery.py create mode 100644 simulation/urban-plan-research/discovery_pass/render_discovery.py create mode 100644 simulation/urban-plan-research/discovery_pass/test_discovery.py create mode 100644 simulation/urban-plan-research/driveway_refinement.py create mode 100644 simulation/urban-plan-research/evaluation/README.md create mode 100644 simulation/urban-plan-research/evaluation/ablation.py create mode 100644 simulation/urban-plan-research/evaluation/analyze_execution_profile.py create mode 100644 simulation/urban-plan-research/evaluation/benchmark_array_io.py create mode 100644 simulation/urban-plan-research/evaluation/compare_frozen_runs.py create mode 100644 simulation/urban-plan-research/evaluation/compare_pipeline_maps.py create mode 100644 simulation/urban-plan-research/evaluation/contract_preflight.py create mode 100644 simulation/urban-plan-research/evaluation/execution_profile.py create mode 100644 simulation/urban-plan-research/evaluation/explain_run_metadata.py create mode 100644 simulation/urban-plan-research/evaluation/geometry_metrics.py create mode 100644 simulation/urban-plan-research/evaluation/probe_background_cause.py create mode 100644 simulation/urban-plan-research/evaluation/profile_frozen_assembly.py create mode 100644 simulation/urban-plan-research/evaluation/qualify_control_tail.py create mode 100644 simulation/urban-plan-research/evaluation/qualify_execution_reuse.py create mode 100644 simulation/urban-plan-research/evaluation/qualify_shared_survey.py create mode 100644 simulation/urban-plan-research/evaluation/qualify_stroke_execution.py create mode 100644 simulation/urban-plan-research/evaluation/qualify_systematic.py create mode 100644 simulation/urban-plan-research/evaluation/qualify_topdown.py create mode 100644 simulation/urban-plan-research/evaluation/queue_worker_canary.py create mode 100644 simulation/urban-plan-research/evaluation/render_spatial_control.py create mode 100644 simulation/urban-plan-research/evaluation/retire_mapper_builds.py create mode 100644 simulation/urban-plan-research/evaluation/run_control_tail.py create mode 100644 simulation/urban-plan-research/evaluation/run_frozen_tail.py create mode 100644 simulation/urban-plan-research/evaluation/run_shared_survey_worker.py create mode 100644 simulation/urban-plan-research/evaluation/run_systematic_worker.py create mode 100644 simulation/urban-plan-research/evaluation/run_topdown_worker.py create mode 100644 simulation/urban-plan-research/evaluation/test_array_serialization.py create mode 100644 simulation/urban-plan-research/evaluation/test_execution_profile.py create mode 100644 simulation/urban-plan-research/evaluation/test_metadata_equivalence.py create mode 100644 simulation/urban-plan-research/evaluation/test_run_equivalence.py create mode 100644 simulation/urban-plan-research/families_pass/README.rst create mode 100644 simulation/urban-plan-research/families_pass/audit_families.py create mode 100644 simulation/urban-plan-research/families_pass/bundle.json create mode 100644 simulation/urban-plan-research/families_pass/crossing_completion.py create mode 100644 simulation/urban-plan-research/families_pass/line_family_completion.py create mode 100644 simulation/urban-plan-research/families_pass/refine_paint.py create mode 100644 simulation/urban-plan-research/families_pass/render_families.py create mode 100644 simulation/urban-plan-research/families_pass/test_families.py create mode 100644 simulation/urban-plan-research/frontage_chains.py create mode 100644 simulation/urban-plan-research/full_plan/README.rst create mode 100644 simulation/urban-plan-research/full_plan/assemble_layers.py create mode 100644 simulation/urban-plan-research/full_plan/audit_layers.py create mode 100644 simulation/urban-plan-research/full_plan/bundle.json create mode 100644 simulation/urban-plan-research/full_plan/crosswalk_family.py create mode 100644 simulation/urban-plan-research/full_plan/fit_scene.py create mode 100644 simulation/urban-plan-research/full_plan/layer_common.py create mode 100644 simulation/urban-plan-research/full_plan/render_layers.py create mode 100644 simulation/urban-plan-research/full_plan/semantic_layers.py create mode 100644 simulation/urban-plan-research/full_plan/source_facade_planes.py create mode 100644 simulation/urban-plan-research/full_plan/test_layers.py create mode 100644 simulation/urban-plan-research/gap_evidence.py create mode 100644 simulation/urban-plan-research/gap_observations.py create mode 100644 simulation/urban-plan-research/glyph_pass/README.md create mode 100644 simulation/urban-plan-research/glyph_pass/audit_glyph.py create mode 100644 simulation/urban-plan-research/glyph_pass/bundle.json create mode 100644 simulation/urban-plan-research/glyph_pass/diagnose_glyph.py create mode 100644 simulation/urban-plan-research/glyph_pass/diagnose_projection.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_identity.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_mosaics.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_mosaics_inspect.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_registration.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_rules.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_targets.py create mode 100644 simulation/urban-plan-research/glyph_pass/glyph_templates.py create mode 100644 simulation/urban-plan-research/glyph_pass/refine_glyph.py create mode 100644 simulation/urban-plan-research/glyph_pass/render_glyph.py create mode 100644 simulation/urban-plan-research/glyph_pass/test_glyph.py create mode 100644 simulation/urban-plan-research/intervals_pass/README.rst create mode 100644 simulation/urban-plan-research/intervals_pass/audit_intervals.py create mode 100644 simulation/urban-plan-research/intervals_pass/bundle.json create mode 100644 simulation/urban-plan-research/intervals_pass/interval_profiles.py create mode 100644 simulation/urban-plan-research/intervals_pass/line_reconstruction.py create mode 100644 simulation/urban-plan-research/intervals_pass/refine_intervals.py create mode 100644 simulation/urban-plan-research/intervals_pass/render_intervals.py create mode 100644 simulation/urban-plan-research/intervals_pass/test_intervals.py create mode 100644 simulation/urban-plan-research/joint_pass/README.md create mode 100644 simulation/urban-plan-research/joint_pass/audit_registration.py create mode 100644 simulation/urban-plan-research/joint_pass/bundle.json create mode 100644 simulation/urban-plan-research/joint_pass/inspect_recall.py create mode 100644 simulation/urban-plan-research/joint_pass/probe_bicycles.py create mode 100644 simulation/urban-plan-research/joint_pass/refine_registration.py create mode 100644 simulation/urban-plan-research/joint_pass/registered_template.py create mode 100644 simulation/urban-plan-research/joint_pass/registration.py create mode 100644 simulation/urban-plan-research/joint_pass/render_registration.py create mode 100644 simulation/urban-plan-research/joint_pass/small_bicycle.py create mode 100644 simulation/urban-plan-research/joint_pass/test_registration.py create mode 100644 simulation/urban-plan-research/lines_pass/README.rst create mode 100644 simulation/urban-plan-research/lines_pass/audit_lines.py create mode 100644 simulation/urban-plan-research/lines_pass/bundle.json create mode 100644 simulation/urban-plan-research/lines_pass/image_profiles.py create mode 100644 simulation/urban-plan-research/lines_pass/line_reconstruction.py create mode 100644 simulation/urban-plan-research/lines_pass/reconstruct_lines.py create mode 100644 simulation/urban-plan-research/lines_pass/render_lines.py create mode 100644 simulation/urban-plan-research/lines_pass/test_lines.py create mode 100644 simulation/urban-plan-research/long_edge_refinement.py create mode 100644 simulation/urban-plan-research/marking_pass/README.md create mode 100644 simulation/urban-plan-research/marking_pass/audit_markings.py create mode 100644 simulation/urban-plan-research/marking_pass/beta_profiles.py create mode 100644 simulation/urban-plan-research/marking_pass/bundle.json create mode 100644 simulation/urban-plan-research/marking_pass/diagnose_markings.py create mode 100644 simulation/urban-plan-research/marking_pass/discovery_evidence.py create mode 100644 simulation/urban-plan-research/marking_pass/discovery_rules.py create mode 100644 simulation/urban-plan-research/marking_pass/fit_scene.py create mode 100644 simulation/urban-plan-research/marking_pass/gost_catalog.py create mode 100644 simulation/urban-plan-research/marking_pass/interval_profiles.py create mode 100644 simulation/urban-plan-research/marking_pass/layer_common.py create mode 100644 simulation/urban-plan-research/marking_pass/line_reconstruction.py create mode 100644 simulation/urban-plan-research/marking_pass/marking_profiles.py create mode 100644 simulation/urban-plan-research/marking_pass/marking_rules.py create mode 100644 simulation/urban-plan-research/marking_pass/refine_markings.py create mode 100644 simulation/urban-plan-research/marking_pass/render_markings.py create mode 100644 simulation/urban-plan-research/marking_pass/render_plan.py create mode 100644 simulation/urban-plan-research/marking_pass/row_evidence.py create mode 100644 simulation/urban-plan-research/marking_pass/row_profiles.py create mode 100644 simulation/urban-plan-research/marking_pass/search_views.py create mode 100644 simulation/urban-plan-research/marking_pass/test_markings.py create mode 100644 simulation/urban-plan-research/material_regions.py create mode 100644 simulation/urban-plan-research/multiview/README.rst create mode 100644 simulation/urban-plan-research/multiview/method.json create mode 100644 simulation/urban-plan-research/multiview/model-profiles.json create mode 100644 simulation/urban-plan-research/multiview/mv_camera_audit.py create mode 100644 simulation/urban-plan-research/multiview/mv_fuse.py create mode 100644 simulation/urban-plan-research/multiview/mv_infer.py create mode 100644 simulation/urban-plan-research/multiview/mv_io.py create mode 100644 simulation/urban-plan-research/multiview/mv_math.py create mode 100644 simulation/urban-plan-research/multiview/mv_plan.py create mode 100644 simulation/urban-plan-research/multiview/mv_render.py create mode 100644 simulation/urban-plan-research/multiview/test_multiview.py create mode 100644 simulation/urban-plan-research/norms_pass/README.rst create mode 100644 simulation/urban-plan-research/norms_pass/audit_norms.py create mode 100644 simulation/urban-plan-research/norms_pass/bundle.json create mode 100644 simulation/urban-plan-research/norms_pass/gost_catalog.py create mode 100644 simulation/urban-plan-research/norms_pass/norm_profiles.py create mode 100644 simulation/urban-plan-research/norms_pass/refine_norms.py create mode 100644 simulation/urban-plan-research/norms_pass/render_norms.py create mode 100644 simulation/urban-plan-research/norms_pass/test_norms.py create mode 100644 simulation/urban-plan-research/orthophoto/README.rst create mode 100644 simulation/urban-plan-research/orthophoto/coordinate_cache.py create mode 100644 simulation/urban-plan-research/orthophoto/method.json create mode 100644 simulation/urban-plan-research/orthophoto/ortho_classes.py create mode 100644 simulation/urban-plan-research/orthophoto/ortho_render.py create mode 100644 simulation/urban-plan-research/orthophoto/ortho_segment.py create mode 100644 simulation/urban-plan-research/orthophoto/ortho_terrain.py create mode 100644 simulation/urban-plan-research/orthophoto/ortho_windows.py create mode 100644 simulation/urban-plan-research/orthophoto/test_ortho_pass.py create mode 100644 simulation/urban-plan-research/paint_templates.py create mode 100644 simulation/urban-plan-research/pipeline/README.md create mode 100644 simulation/urban-plan-research/pipeline/base/boundary_anchors.py create mode 100644 simulation/urban-plan-research/pipeline/base/curb_regularize.py create mode 100644 simulation/urban-plan-research/pipeline/base/geometry.py create mode 100644 simulation/urban-plan-research/pipeline/base/height_observations.py create mode 100644 simulation/urban-plan-research/pipeline/base/height_reference.py create mode 100644 simulation/urban-plan-research/pipeline/base/observed_boundaries.py create mode 100644 simulation/urban-plan-research/pipeline/base/qualify_junctions.py create mode 100644 simulation/urban-plan-research/pipeline/config-mv.json create mode 100644 simulation/urban-plan-research/pipeline/config-ortho.json create mode 100644 simulation/urban-plan-research/pipeline/definition.json create mode 100644 simulation/urban-plan-research/pipeline/strip_validation/revalidate_strips.py create mode 100644 simulation/urban-plan-research/pipeline/strip_validation/strip_validation.py create mode 100644 simulation/urban-plan-research/pipeline/strip_validation/test_strip_validation.py create mode 100644 simulation/urban-plan-research/pipeline/timing-profile.json create mode 100644 simulation/urban-plan-research/pipeline/worker-profile.json create mode 100644 simulation/urban-plan-research/plan_acceptance.py create mode 100644 simulation/urban-plan-research/plan_boundaries.py create mode 100644 simulation/urban-plan-research/plan_continuity.py create mode 100644 simulation/urban-plan-research/plan_coverage.py create mode 100644 simulation/urban-plan-research/plan_junctions.py create mode 100644 simulation/urban-plan-research/plan_primitives.py create mode 100644 simulation/urban-plan-research/plan_refinement.py create mode 100644 simulation/urban-plan-research/plan_scene.py create mode 100644 simulation/urban-plan-research/plan_shapes.py create mode 100644 simulation/urban-plan-research/qualify_continuity.py create mode 100644 simulation/urban-plan-research/qualify_junctions.py create mode 100644 simulation/urban-plan-research/qualify_refinement.py create mode 100644 simulation/urban-plan-research/qualify_scene_assembly.py create mode 100644 simulation/urban-plan-research/qualify_scene_invariants.py create mode 100644 simulation/urban-plan-research/qualify_scene_junctions.py create mode 100644 simulation/urban-plan-research/recall_pass/README.md create mode 100644 simulation/urban-plan-research/recall_pass/audit_recall.py create mode 100644 simulation/urban-plan-research/recall_pass/bundle.json create mode 100644 simulation/urban-plan-research/recall_pass/diagnose_recall.py create mode 100644 simulation/urban-plan-research/recall_pass/recall_extent.py create mode 100644 simulation/urban-plan-research/recall_pass/recall_rules.py create mode 100644 simulation/urban-plan-research/recall_pass/recall_targets.py create mode 100644 simulation/urban-plan-research/recall_pass/recall_templates.py create mode 100644 simulation/urban-plan-research/recall_pass/refine_recall.py create mode 100644 simulation/urban-plan-research/recall_pass/render_recall.py create mode 100644 simulation/urban-plan-research/recall_pass/test_recall.py create mode 100644 simulation/urban-plan-research/refinement_evidence.py create mode 100644 simulation/urban-plan-research/registration_pass/README.md create mode 100644 simulation/urban-plan-research/registration_pass/audit_registration.py create mode 100644 simulation/urban-plan-research/registration_pass/bundle.json create mode 100644 simulation/urban-plan-research/registration_pass/refine_registration.py create mode 100644 simulation/urban-plan-research/registration_pass/registered_template.py create mode 100644 simulation/urban-plan-research/registration_pass/registration.py create mode 100644 simulation/urban-plan-research/registration_pass/render_registration.py create mode 100644 simulation/urban-plan-research/registration_pass/test_registration.py create mode 100644 simulation/urban-plan-research/replay/COMPACT_SYMBOLS.md create mode 100644 simulation/urban-plan-research/replay/LINEAR_WINDOWS.md create mode 100644 simulation/urban-plan-research/replay/README.rst create mode 100644 simulation/urban-plan-research/replay/arrow_admission.py create mode 100644 simulation/urban-plan-research/replay/arrow_admission_bundle.json create mode 100644 simulation/urban-plan-research/replay/arrow_evidence.py create mode 100644 simulation/urban-plan-research/replay/arrow_frames.py create mode 100644 simulation/urban-plan-research/replay/arrow_mosaics.py create mode 100644 simulation/urban-plan-research/replay/arrow_tip_registration.py create mode 100644 simulation/urban-plan-research/replay/audit_arrow_admission.py create mode 100644 simulation/urban-plan-research/replay/audit_arrow_sources.py create mode 100644 simulation/urban-plan-research/replay/audit_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/audit_completed_zigzags.py create mode 100644 simulation/urban-plan-research/replay/audit_linear_support.py create mode 100644 simulation/urban-plan-research/replay/audit_linear_windows.py create mode 100644 simulation/urban-plan-research/replay/audit_uniform_sources.py create mode 100644 simulation/urban-plan-research/replay/audit_zigzag_coverage.py create mode 100644 simulation/urban-plan-research/replay/compact_bicycle.py create mode 100644 simulation/urban-plan-research/replay/compact_evidence.py create mode 100644 simulation/urban-plan-research/replay/compact_mosaics.py create mode 100644 simulation/urban-plan-research/replay/compact_symbols_bundle.json create mode 100644 simulation/urban-plan-research/replay/compact_targets.py create mode 100644 simulation/urban-plan-research/replay/crossing_discovery.py create mode 100644 simulation/urban-plan-research/replay/diagnose_arrow_gates.py create mode 100644 simulation/urban-plan-research/replay/diagnose_marking_surfaces.py create mode 100644 simulation/urban-plan-research/replay/diagnose_remaining_patterns.py create mode 100644 simulation/urban-plan-research/replay/discover_crossings.py create mode 100644 simulation/urban-plan-research/replay/discover_uniform_arrows.py create mode 100644 simulation/urban-plan-research/replay/final_symbol_admission.py create mode 100644 simulation/urban-plan-research/replay/fit_standard_arrows.py create mode 100644 simulation/urban-plan-research/replay/fixed_arrow_bundle.json create mode 100644 simulation/urban-plan-research/replay/inspect_zigzag_gaps.py create mode 100644 simulation/urban-plan-research/replay/linear_coverage_views.py create mode 100644 simulation/urban-plan-research/replay/linear_window_support.py create mode 100644 simulation/urban-plan-research/replay/linear_windows_bundle.json create mode 100644 simulation/urban-plan-research/replay/merge_arrow_artwork.json create mode 100644 simulation/urban-plan-research/replay/paved_registration.py create mode 100644 simulation/urban-plan-research/replay/plan_linear_coverage.py create mode 100644 simulation/urban-plan-research/replay/pose_survey.py create mode 100644 simulation/urban-plan-research/replay/prefilter_compact_shape.py create mode 100644 simulation/urban-plan-research/replay/prefilter_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/prepare_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/prepare_uniform_symbols.py create mode 100644 simulation/urban-plan-research/replay/probe_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/refine_arrow_admission.py create mode 100644 simulation/urban-plan-research/replay/refine_standard_arrows.py create mode 100644 simulation/urban-plan-research/replay/refine_uniform_arrows.py create mode 100644 simulation/urban-plan-research/replay/refine_zigzag_extensions.py create mode 100644 simulation/urban-plan-research/replay/refine_zigzag_terminals.py create mode 100644 simulation/urban-plan-research/replay/render_arrow_admission.py create mode 100644 simulation/urban-plan-research/replay/render_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/render_linear_changes.py create mode 100644 simulation/urban-plan-research/replay/render_marking_overview.py create mode 100644 simulation/urban-plan-research/replay/render_standard_proposals.py create mode 100644 simulation/urban-plan-research/replay/semantic_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/standard_arrow_evidence.py create mode 100644 simulation/urban-plan-research/replay/standard_arrow_regions.py create mode 100644 simulation/urban-plan-research/replay/standard_arrow_templates.py create mode 100644 simulation/urban-plan-research/replay/survey_grid.py create mode 100644 simulation/urban-plan-research/replay/test_arrow_admission.py create mode 100644 simulation/urban-plan-research/replay/test_compact_symbols.py create mode 100644 simulation/urban-plan-research/replay/test_crossing_discovery.py create mode 100644 simulation/urban-plan-research/replay/test_standard_arrows.py create mode 100644 simulation/urban-plan-research/replay/test_zigzag_extensions.py create mode 100644 simulation/urban-plan-research/replay/test_zigzag_terminal_views.py create mode 100644 simulation/urban-plan-research/replay/verify_arrow_observations.py create mode 100644 simulation/urban-plan-research/replay/verify_discovered_crossings.py create mode 100644 simulation/urban-plan-research/replay/verify_standard_arrows.py create mode 100644 simulation/urban-plan-research/replay/verify_uniform_arrows.py create mode 100644 simulation/urban-plan-research/replay/verify_zigzag_extensions.py create mode 100644 simulation/urban-plan-research/replay/verify_zigzag_terminals.py create mode 100644 simulation/urban-plan-research/replay/zigzag_extension.py create mode 100644 simulation/urban-plan-research/replay/zigzag_extension_bundle.json create mode 100644 simulation/urban-plan-research/replay/zigzag_terminal.py create mode 100644 simulation/urban-plan-research/rows_pass/README.rst create mode 100644 simulation/urban-plan-research/rows_pass/audit_rows.py create mode 100644 simulation/urban-plan-research/rows_pass/bundle.json create mode 100644 simulation/urban-plan-research/rows_pass/refine_rows.py create mode 100644 simulation/urban-plan-research/rows_pass/render_rows.py create mode 100644 simulation/urban-plan-research/rows_pass/row_evidence.py create mode 100644 simulation/urban-plan-research/rows_pass/row_profiles.py create mode 100644 simulation/urban-plan-research/rows_pass/test_rows.py create mode 100644 simulation/urban-plan-research/search_pass/README.rst create mode 100644 simulation/urban-plan-research/search_pass/audit_search.py create mode 100644 simulation/urban-plan-research/search_pass/bundle.json create mode 100644 simulation/urban-plan-research/search_pass/corridor_profiles.py create mode 100644 simulation/urban-plan-research/search_pass/extract_search.py create mode 100644 simulation/urban-plan-research/search_pass/refine_search.py create mode 100644 simulation/urban-plan-research/search_pass/render_plan.py create mode 100644 simulation/urban-plan-research/search_pass/render_search.py create mode 100644 simulation/urban-plan-research/search_pass/search_rules.py create mode 100644 simulation/urban-plan-research/search_pass/search_views.py create mode 100644 simulation/urban-plan-research/search_pass/test_search.py create mode 100644 simulation/urban-plan-research/sections_pass/README.rst create mode 100644 simulation/urban-plan-research/sections_pass/audit_sections.py create mode 100644 simulation/urban-plan-research/sections_pass/bundle.json create mode 100644 simulation/urban-plan-research/sections_pass/refine_sections.py create mode 100644 simulation/urban-plan-research/sections_pass/render_sections.py create mode 100644 simulation/urban-plan-research/sections_pass/section_profiles.py create mode 100644 simulation/urban-plan-research/sections_pass/test_sections.py create mode 100644 simulation/urban-plan-research/shared_survey/README.md create mode 100644 simulation/urban-plan-research/shared_survey/compare_semantic_survey.py create mode 100644 simulation/urban-plan-research/shared_survey/semantic_consumers.py create mode 100644 simulation/urban-plan-research/shared_survey/semantic_survey.py create mode 100644 simulation/urban-plan-research/shared_survey/semantic_survey_stage.py create mode 100644 simulation/urban-plan-research/shared_survey/test_semantic_survey.py create mode 100644 simulation/urban-plan-research/surface_pass/audit_surface.py create mode 100644 simulation/urban-plan-research/surface_pass/bundle.json create mode 100644 simulation/urban-plan-research/surface_pass/diagnose_surface.py create mode 100644 simulation/urban-plan-research/surface_pass/refine_surface.py create mode 100644 simulation/urban-plan-research/surface_pass/surface_height.py create mode 100644 simulation/urban-plan-research/surface_pass/test_surface.py create mode 100644 simulation/urban-plan-research/survey_index.py create mode 100644 simulation/urban-plan-research/symbol_pass/README.rst create mode 100644 simulation/urban-plan-research/symbol_pass/audit_symbols.py create mode 100644 simulation/urban-plan-research/symbol_pass/bundle.json create mode 100644 simulation/urban-plan-research/symbol_pass/catalog_evidence.py create mode 100644 simulation/urban-plan-research/symbol_pass/prepare_symbols.py create mode 100644 simulation/urban-plan-research/symbol_pass/refine_symbols.py create mode 100644 simulation/urban-plan-research/symbol_pass/render_symbols.py create mode 100644 simulation/urban-plan-research/symbol_pass/review_symbols.py create mode 100644 simulation/urban-plan-research/symbol_pass/semantic_symbols.py create mode 100644 simulation/urban-plan-research/symbol_pass/symbol_evidence.py create mode 100644 simulation/urban-plan-research/symbol_pass/symbol_rules.py create mode 100644 simulation/urban-plan-research/symbol_pass/test_symbols.py create mode 100644 simulation/urban-plan-research/systematic/CONNECTED_PAINT.md create mode 100644 simulation/urban-plan-research/systematic/INITIAL_VIEWS.md create mode 100644 simulation/urban-plan-research/systematic/JOINT_ASSEMBLY.md create mode 100644 simulation/urban-plan-research/systematic/admit_marking_contracts.py create mode 100644 simulation/urban-plan-research/systematic/admit_primary_arrows.py create mode 100644 simulation/urban-plan-research/systematic/array_archive.py create mode 100644 simulation/urban-plan-research/systematic/arrow-contract-lock.json create mode 100644 simulation/urban-plan-research/systematic/assemble_paint.py create mode 100644 simulation/urban-plan-research/systematic/assemble_surfaces.py create mode 100644 simulation/urban-plan-research/systematic/batched_concepts.py create mode 100644 simulation/urban-plan-research/systematic/batched_row_evidence.py create mode 100644 simulation/urban-plan-research/systematic/body_profiles.py create mode 100644 simulation/urban-plan-research/systematic/cached_text_processor.py create mode 100644 simulation/urban-plan-research/systematic/catalog_observations.py create mode 100644 simulation/urban-plan-research/systematic/compact_observations.py create mode 100644 simulation/urban-plan-research/systematic/component_axis.py create mode 100644 simulation/urban-plan-research/systematic/conditional_replacements.py create mode 100644 simulation/urban-plan-research/systematic/connected_configurations.py create mode 100644 simulation/urban-plan-research/systematic/connected_ridges.py create mode 100644 simulation/urban-plan-research/systematic/coverage_semantics.py create mode 100644 simulation/urban-plan-research/systematic/crossing_fit.py create mode 100644 simulation/urban-plan-research/systematic/definition.json create mode 100644 simulation/urban-plan-research/systematic/discover_primary_arrows.py create mode 100644 simulation/urban-plan-research/systematic/extract_observations.py create mode 100644 simulation/urban-plan-research/systematic/family_ownership.py create mode 100644 simulation/urban-plan-research/systematic/finite_strokes.py create mode 100644 simulation/urban-plan-research/systematic/fixed_observation_grid.py create mode 100644 simulation/urban-plan-research/systematic/initial_views.py create mode 100644 simulation/urban-plan-research/systematic/join_surfaces.py create mode 100644 simulation/urban-plan-research/systematic/joint_assembly.py create mode 100644 simulation/urban-plan-research/systematic/joint_choice.py create mode 100644 simulation/urban-plan-research/systematic/marking_rules.py create mode 100644 simulation/urban-plan-research/systematic/measured_row_graph.py create mode 100644 simulation/urban-plan-research/systematic/measured_rows.py create mode 100644 simulation/urban-plan-research/systematic/measurement_reads.py create mode 100644 simulation/urban-plan-research/systematic/object_context.py create mode 100644 simulation/urban-plan-research/systematic/object_evidence.py create mode 100644 simulation/urban-plan-research/systematic/observation_cache.py create mode 100644 simulation/urban-plan-research/systematic/observation_coverage.py create mode 100644 simulation/urban-plan-research/systematic/observation_tiles.py create mode 100644 simulation/urban-plan-research/systematic/observed_geometry.py create mode 100644 simulation/urban-plan-research/systematic/ortho_render.py create mode 100644 simulation/urban-plan-research/systematic/paint_conservation.py create mode 100644 simulation/urban-plan-research/systematic/paint_observations.py create mode 100644 simulation/urban-plan-research/systematic/paint_templates.py create mode 100644 simulation/urban-plan-research/systematic/paired_markings.py create mode 100644 simulation/urban-plan-research/systematic/prepare_primary_symbols.py create mode 100644 simulation/urban-plan-research/systematic/primary_components.py create mode 100644 simulation/urban-plan-research/systematic/primary_evidence.py create mode 100644 simulation/urban-plan-research/systematic/primary_line_observations.py create mode 100644 simulation/urban-plan-research/systematic/qualify_camera_ownership.py create mode 100644 simulation/urban-plan-research/systematic/qualify_component_axis_contract.py create mode 100644 simulation/urban-plan-research/systematic/qualify_concept_decoding.py create mode 100644 simulation/urban-plan-research/systematic/qualify_crossing_fit.py create mode 100644 simulation/urban-plan-research/systematic/qualify_family_ownership.py create mode 100644 simulation/urban-plan-research/systematic/qualify_initial_observations.py create mode 100644 simulation/urban-plan-research/systematic/qualify_primary_plan.py create mode 100644 simulation/urban-plan-research/systematic/qualify_row_graph_contract.py create mode 100644 simulation/urban-plan-research/systematic/qualify_strokes.py create mode 100644 simulation/urban-plan-research/systematic/reconstruct_primary_arrows.py create mode 100644 simulation/urban-plan-research/systematic/refine_markings.py create mode 100644 simulation/urban-plan-research/systematic/row_discovery.py create mode 100644 simulation/urban-plan-research/systematic/search_views.py create mode 100644 simulation/urban-plan-research/systematic/semantic_primary_symbols.py create mode 100644 simulation/urban-plan-research/systematic/semantic_survey.py create mode 100644 simulation/urban-plan-research/systematic/semantic_survey_stage.py create mode 100644 simulation/urban-plan-research/systematic/shared_surface_edges.py create mode 100644 simulation/urban-plan-research/systematic/solve_catalog.py create mode 100644 simulation/urban-plan-research/systematic/solve_crossings.py create mode 100644 simulation/urban-plan-research/systematic/stroke_axis.py create mode 100644 simulation/urban-plan-research/systematic/stroke_inventory.py create mode 100644 simulation/urban-plan-research/systematic/stroke_observations.py create mode 100644 simulation/urban-plan-research/systematic/stroke_seeds.py create mode 100644 simulation/urban-plan-research/systematic/test_conditional_replacements.py create mode 100644 simulation/urban-plan-research/systematic/test_connected_configurations.py create mode 100644 simulation/urban-plan-research/systematic/test_connected_ridges.py create mode 100644 simulation/urban-plan-research/systematic/test_initial_views.py create mode 100644 simulation/urban-plan-research/systematic/test_joint_choice.py create mode 100644 simulation/urban-plan-research/systematic/test_object_context.py create mode 100644 simulation/urban-plan-research/systematic/test_object_evidence.py create mode 100644 simulation/urban-plan-research/systematic/test_observed_geometry.py create mode 100644 simulation/urban-plan-research/systematic/test_shared_surface_edges.py create mode 100644 simulation/urban-plan-research/test_boundary_anchors.py create mode 100644 simulation/urban-plan-research/test_boundary_competition.py create mode 100644 simulation/urban-plan-research/test_gap_evidence.py create mode 100644 simulation/urban-plan-research/test_material_regions.py create mode 100644 simulation/urban-plan-research/test_observed_plan.py create mode 100644 simulation/urban-plan-research/test_plan_continuity.py create mode 100644 simulation/urban-plan-research/test_plan_geometry.py create mode 100644 simulation/urban-plan-research/test_plan_junctions.py create mode 100644 simulation/urban-plan-research/test_plan_refinement.py create mode 100644 simulation/urban-plan-research/test_plan_scene.py create mode 100644 simulation/urban-plan-research/test_plan_shapes.py create mode 100644 simulation/urban-plan-research/test_survey_index.py create mode 100644 simulation/urban-plan-research/test_transfer_contract.py create mode 100644 simulation/urban-plan-research/topdown/README.md create mode 100644 simulation/urban-plan-research/topdown/admission_contract.py create mode 100644 simulation/urban-plan-research/topdown/assemble_reviewed_state.py create mode 100644 simulation/urban-plan-research/topdown/audit_contract.py create mode 100644 simulation/urban-plan-research/topdown/audit_topdown.py create mode 100644 simulation/urban-plan-research/topdown/candidate_registry.py create mode 100644 simulation/urban-plan-research/topdown/conditional_contract_audit.py create mode 100644 simulation/urban-plan-research/topdown/depth_audit.py create mode 100644 simulation/urban-plan-research/topdown/direct_fixed.py create mode 100644 simulation/urban-plan-research/topdown/endpoint_cause_audit.py create mode 100644 simulation/urban-plan-research/topdown/feasibility_audit.py create mode 100644 simulation/urban-plan-research/topdown/ground_observations.py create mode 100644 simulation/urban-plan-research/topdown/head_observation.py create mode 100644 simulation/urban-plan-research/topdown/object_evidence.py create mode 100644 simulation/urban-plan-research/topdown/observation_checks.py create mode 100644 simulation/urban-plan-research/topdown/observation_evaluator.py create mode 100644 simulation/urban-plan-research/topdown/observed_fixed.py create mode 100644 simulation/urban-plan-research/topdown/orthographic_colour.py create mode 100644 simulation/urban-plan-research/topdown/orthographic_depth.py create mode 100644 simulation/urban-plan-research/topdown/paint_channels_fast.py create mode 100644 simulation/urban-plan-research/topdown/pixel_geometry.py create mode 100644 simulation/urban-plan-research/topdown/plan_marking_policy.py create mode 100644 simulation/urban-plan-research/topdown/plan_registration.py create mode 100644 simulation/urban-plan-research/topdown/pose_domain_audit.py create mode 100644 simulation/urban-plan-research/topdown/prepare_topdown.py create mode 100644 simulation/urban-plan-research/topdown/preservation.py create mode 100644 simulation/urban-plan-research/topdown/reconcile_objects.py create mode 100644 simulation/urban-plan-research/topdown/reconstruct_topdown.py create mode 100644 simulation/urban-plan-research/topdown/registration_evaluator.py create mode 100644 simulation/urban-plan-research/topdown/render_native_geometry.py create mode 100644 simulation/urban-plan-research/topdown/spatial_index.py create mode 100644 simulation/urban-plan-research/topdown/surface_audit.py create mode 100644 simulation/urban-plan-research/topdown/test_orthographic_colour.py create mode 100644 simulation/urban-plan-research/topdown/test_topdown.py create mode 100644 simulation/urban-plan-research/topdown/verify_topdown.py create mode 100644 simulation/urban-plan-research/transitions_pass/README.rst create mode 100644 simulation/urban-plan-research/transitions_pass/audit_transitions.py create mode 100644 simulation/urban-plan-research/transitions_pass/bundle.json create mode 100644 simulation/urban-plan-research/transitions_pass/refine_transitions.py create mode 100644 simulation/urban-plan-research/transitions_pass/render_transitions.py create mode 100644 simulation/urban-plan-research/transitions_pass/test_transitions.py create mode 100644 simulation/urban-plan-research/transitions_pass/transition_profiles.py create mode 100644 tests/test_contour_refinement.py create mode 100644 tests/test_systematic_pipeline.py create mode 100644 tests/test_urban_ablation.py create mode 100644 tests/test_urban_final_symbol_admission.py create mode 100644 tests/test_urban_linear_windows.py diff --git a/simulation/urban-mapping/README.md b/simulation/urban-mapping/README.md index b2300e61..11168de3 100644 --- a/simulation/urban-mapping/README.md +++ b/simulation/urban-mapping/README.md @@ -63,3 +63,88 @@ In planning, the infrastructure toggle is independent of Gaussian/collision laye Contours do not enter picking, collision or rover control. Hiding the layer leaves the original scene and route unchanged. Delete only a map's `latest.json` pointer to unpublish it; immutable previous versions remain available for rollback. + + +## Whole-location command and shared storage + +The planning header command **Проанализировать инфраструктуру** creates one durable +job for the current world/collider/provider identities. The existing Worker coordinator +reserves the shared GPU using the same admission mechanism as simulation, reads the +verified complete-scene source, and launches two separate bounded containers in order: +Gaussian rendering / Mask2Former survey, then VMA object vectorization. Gaussian Pipeline +remains an independently owned module; no service is merged or restarted for this job. + +The input is the existing prepared `state/project-packages//` directory +(resolved through the worker's shared-cache link). Both stages bind the exact existing +files read-only. No downloads, `copy`, new PLY conversions, or source-scene files are +allowed in the analysis output. Output under `runtime/urban-mapping/jobs//` +contains only request/progress metadata and derived images, atlases and vectors. +Sources and receipts are checksum-verified before use. Repeated identical requests +reuse the job; retries validate and resume completed tile receipts. + +The first supported source contract is an already prepared complete-scene PLY plus +its calibrated decoded collider. An imported project that exists only as native SOG +has **not** yet qualified for this command: it must not silently invoke another scene +copy or conversion. Missing shared artifacts are reported as preparation failure. +Native-source reading is a separate provider extension, not a claim of this release. + +`whole_scene.py` tiles the complete collider XY bounds, independent of route A/B: +40 m core plus 10 m overlap, 60 m / 1200 px orthographic views, and up to four +800×600 perspective views per tile. The supported envelope is 256 tiles. Camera +candidates come from measured near-horizontal geometry. This is a heuristic survey; +roofs, missing ground and occlusion require inspection. All processed tiles and gaps +are recorded. “Whole-scene” describes the requested extent, not complete recognition. + +`vector/whole_vectors.py` runs the pinned VMA models, uses semantic/depth evidence to +admit objects, assigns overlapping polygons to one core tile and clips lines in XYZ. +The final v2 map remains unreviewed and observation-only. It is published only when +world/collider/provider/job identities match; a failed analysis preserves the previous +map. Worker restarts reconcile exactly labelled containers before releasing the GPU. + +The planning UI has independent Gaussian and collision switches, one infrastructure +switch, and a memory dropdown. Memory contains accumulated visits/attempts across +runs for a scene/collider/robot revision; the dropdown currently displays the latest +robot configuration's accumulated history. Fresh sensing remains authoritative. + + +## Contour consolidation + +After tile assembly, **Согласование контуров** runs in the vector container. +It reads the original survey in place and retains `urban-map.raw.json` before +publishing `urban-map.json`. `contour-refinement.json` records dropped observation +IDs, overlap removal and individual joins. The map stores source IDs, inferred gap +coordinates, spline knots/control points and runtime library versions. Original +observations remain recoverable; this stage never changes the collider or route +permissions. + +The geometric engine is GEOS through pinned Shapely 1.8.5.post1 (STRtree, +intersection/difference and linemerge), NetworkX connected components and SciPy +1.13.1 FITPACK cubic B-splines. There is no custom line-merging implementation. +Application policy restricts inputs to matching classes, compatible endpoint +directions/heights, unambiguous junctions and non-crossing geometry. Default +maximum gaps are 1.25 m for curbs, 0.5 m for lane paint, 0.2 m for stop lines; +gaps over 0.12 m additionally require source alpha/depth and oriented image +contrast. These are provisional metric engineering thresholds, not measurement +accuracy or autonomous-driving tolerances. Large missing sections stay open. + +Duplicate overlap uses 0.15 m tolerance. Isolated weak fragments below 1.5 m are +removed only with negative image evidence on observed ground. B-spline fitting +preserves structural corners/endpoints and checks rendered XY Hausdorff deviation +<=0.12 m, height deviation <=0.08 m, length and new intersections. Height inside +an inferred bridge is explicitly labelled endpoint interpolation. Crossing areas +and zebra paint polygons are unchanged. Geometric refinement cannot establish +that every VMA classification is correct; dubious long detections are not erased +just because their image contrast is low. + +Alternatives reviewed: GRASS `v.clean`/`v.generalize`, CartAGen smoothing, +momepy COINS and neatnet preprocessing. Their generic network simplification +must not collapse distinct curbs/lanes or remove legitimate dead ends. COINS +also expects non-overlapping input. For this stage the existing GEOS/SciPy +runtime avoids introducing another GIS dependency stack into legacy VMA CUDA. +Primary references: +- https://shapely.readthedocs.io/en/1.8.5/manual.html#shapely.ops.linemerge +- https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splprep.html +- https://grass.osgeo.org/grass-stable/manuals/v.clean.html +- https://cartagen.readthedocs.io/en/latest/manual.html +- https://docs.momepy.org/stable/api/momepy.COINS.html +- https://uscuni.org/neatnet/ diff --git a/simulation/urban-mapping/atlas.py b/simulation/urban-mapping/atlas.py index 0eba65b9..5f429349 100644 --- a/simulation/urban-mapping/atlas.py +++ b/simulation/urban-mapping/atlas.py @@ -63,6 +63,8 @@ def fuse(job, output, unproject, classes, write_json): z[~accepted.reshape(height, width)] = np.nan np.savez_compressed(output / 'surface-atlas.npz', labels=labels, z=z, views=observed.reshape(height, width), confidence=strength.reshape(height, width), bounds=bounds, cell_m=cell) + if job.get('atlas_only'): + return {'accepted_cells': int(accepted.sum())} rgb = np.full((height, width, 3), [25, 28, 32], np.uint8) features = [] import rasterio.features diff --git a/simulation/urban-mapping/mapping.py b/simulation/urban-mapping/mapping.py index d4b1e078..d8623f5b 100644 --- a/simulation/urban-mapping/mapping.py +++ b/simulation/urban-mapping/mapping.py @@ -69,13 +69,43 @@ def unproject(pixels, depth, view, intrinsics, projection): return (local @ np.linalg.inv(view).T)[:, :3] -def render(job, output): +def prepare_crops(jobs): + """One source walk per bounded batch; retain source row order and numeric operations.""" + from plyfile import PlyData + if not 1 <= len(jobs) <= 4 or any(j['source'] != jobs[0]['source'] for j in jobs): + raise ValueError('A crop batch requires one source and at most four windows') + source = Path('/input') / jobs[0]['source']['ply'] + transform = np.asarray(jobs[0]['source']['source_to_world'], dtype=np.float64) + data = PlyData.read(source, mmap='r')['vertex'].data + rows = [[] for _ in jobs] + for start in range(0, len(data), 250000): + d = data[start:start + 250000] + xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']]) + world = xyz @ transform[:3, :3].T + transform[:3, 3] + for job, selected in zip(jobs, rows): + bounds = np.asarray(job['bounds_xy'], dtype=float) + mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) & + (world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1) + selected.append(d[mask].copy()) + for selected in rows: + result = np.concatenate(selected) + selected.clear() + yield result + + +def render(job, output, prepared_rows=None): import torch from gsplat import rasterization from plyfile import PlyData source = Path('/input') / job['source']['ply'] - if digest(source) != job['source']['sha256']: - raise ValueError('Gaussian source checksum mismatch') + global _verified_sources + if '_verified_sources' not in globals(): _verified_sources = set() + stat = source.stat() + identity = (str(source), stat.st_size, stat.st_mtime_ns, job['source']['sha256']) + if identity not in _verified_sources: + if digest(source) != job['source']['sha256']: + raise ValueError('Gaussian source checksum mismatch') + _verified_sources.add(identity) transform = np.asarray(job['source']['source_to_world'], dtype=np.float64) if (transform.shape != (4, 4) or not np.isfinite(transform).all() or not np.allclose(transform[3], [0, 0, 0, 1]) @@ -83,18 +113,21 @@ def render(job, output): or not np.isclose(np.linalg.det(transform[:3, :3]), 1)): raise ValueError('Only rigid source transforms are supported; bake scale into the source') data = PlyData.read(source, mmap='r')['vertex'].data - rows = [] - bounds = np.asarray(job['bounds_xy'], dtype=float) - # Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo. - for start in range(0, len(data), 250000): - d = data[start:start + 250000] - xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']]) - world = xyz @ transform[:3, :3].T + transform[:3, 3] - mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) & - (world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1) - rows.append(d[mask].copy()) - d = np.concatenate(rows) - del rows + if prepared_rows is None: + rows = [] + bounds = np.asarray(job['bounds_xy'], dtype=float) + # Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo. + for start in range(0, len(data), 250000): + d = data[start:start + 250000] + xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']]) + world = xyz @ transform[:3, :3].T + transform[:3, 3] + mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) & + (world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1) + rows.append(d[mask].copy()) + d = np.concatenate(rows) + del rows + else: + d = prepared_rows if not len(d): raise ValueError('No Gaussians in the requested tile') def tensor(names): @@ -130,11 +163,15 @@ def infer(job, output): import torch from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation model_path = Path('/model') - for name, expected in job['model']['files'].items(): + global _semantic_cache + if '_semantic_cache' not in globals(): _semantic_cache = None + for name, expected in (job['model']['files'].items() if _semantic_cache is None else []): if digest(model_path / name) != expected: raise ValueError('Model asset checksum mismatch: ' + name) - processor = AutoImageProcessor.from_pretrained(model_path, local_files_only=True) - model = Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval() + if _semantic_cache is None: + _semantic_cache = (AutoImageProcessor.from_pretrained(model_path, local_files_only=True), + Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval()) + processor, model = _semantic_cache for spec in job['views']: if spec.get('projection', 'pinhole') != 'pinhole': continue # Mapillary is a street-view model; orthographic views are review only. diff --git a/simulation/urban-mapping/vector/contour_evidence.py b/simulation/urban-mapping/vector/contour_evidence.py new file mode 100644 index 00000000..aa6d83ec --- /dev/null +++ b/simulation/urban-mapping/vector/contour_evidence.py @@ -0,0 +1,67 @@ +"""Read existing orthographic survey tiles in place; bounded four-tile cache.""" +import json +from collections import OrderedDict +from pathlib import Path +import cv2 +import numpy as np +from PIL import Image + + +class SurveyEvidence: + def __init__(self, root): + self.root = Path(root) + self.tiles = [t for t in json.loads((self.root/'tile-index.json').read_text())['tiles'] if t['status']=='surveyed'] + self.cache = OrderedDict() + + def load(self, tile): + key = tile['id'] + if key not in self.cache: + folder = self.root/key + with np.load(folder/'top.geometry.npz') as g: + data = {k:g[k] for k in ('view','intrinsics','alpha','depth')} + rgb = np.asarray(Image.open(folder/'top.png').convert('RGB')) + data['gray'] = cv2.GaussianBlur(cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32), (3,3), .6) + self.cache[key] = data + if len(self.cache)>4:self.cache.popitem(last=False) + self.cache.move_to_end(key) + return self.cache[key] + + def support(self, points, key): + """Return observed-ground and oriented image support for each XYZ sample. + + Paint needs a bright ridge, a boundary needs cross-line contrast. Image + contrast alone never proves ground: depth and alpha must also agree. + """ + p = np.asarray(points, float); n = len(p) + ground, signal = np.zeros(n, bool), np.zeros(n, bool) + tangent = np.gradient(p[:, :2], axis=0) + normal = np.column_stack([-tangent[:,1], tangent[:,0]]) + normal /= np.maximum(np.linalg.norm(normal, axis=1)[:,None], 1e-9) + for tile in self.tiles: + low, high = np.asarray(tile['core_bounds']) + ids = np.flatnonzero(((p[:,:2]>=low-.1)&(p[:,:2]<=high+.1)).all(1)) + if not len(ids):continue + g = self.load(tile); k = g['intrinsics']; view = g['view']; gray = g['gray'] + q = p[ids]; cam = np.c_[q, np.ones(len(q))]@view.T + uv = cam[:,:2]*np.diag(k)[:2]+k[:2,2]-.5 + h,w = gray.shape + valid = ((uv>6)&(uv<[w-7,h-7])).all(1) + c,r = np.rint(uv).astype(int).T; c=np.clip(c,0,w-1);r=np.clip(r,0,h-1) + valid &= (g['alpha'][r,c]>=.65)&np.isfinite(g['depth'][r,c])&(np.abs(cam[:,2]-g['depth'][r,c])<=.5) + def at(offset): + shifted = q.copy(); shifted[:,:2] += normal[ids]*offset + xy = (np.c_[shifted,np.ones(len(q))]@view.T)[:,:2]*np.diag(k)[:2]+k[:2,2]-.5 + return cv2.remap(gray, xy[:,0].astype(np.float32)[None], xy[:,1].astype(np.float32)[None], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)[0] + center = np.maximum.reduce([at(x) for x in (-.05,0,.05)]) + left,right = at(-.25),at(.25) + if key[0]=='road_marking': + supported = (center > np.maximum(left,right)+7)&(center>75) + else: + supported = np.maximum.reduce([np.abs(left-right), np.abs(center-left), np.abs(center-right)])>8 + ground[ids] |= valid; signal[ids] |= valid&supported + return ground, signal + + def bridge(self, points, key): + ground, signal = self.support(points, key) + required = .9 if key[0]=='road_marking' else .7 + return bool(ground.all() and signal.mean()>=required) diff --git a/simulation/urban-mapping/vector/contour_geometry.py b/simulation/urban-mapping/vector/contour_geometry.py new file mode 100644 index 00000000..73d69c75 --- /dev/null +++ b/simulation/urban-mapping/vector/contour_geometry.py @@ -0,0 +1,83 @@ +"""Metric curve operations; no projection, classification or route authority.""" +import warnings +import numpy as np +from scipy.interpolate import splprep, splev +from shapely.geometry import LineString, Point + + +def distance(points): + return np.r_[0., np.cumsum(np.linalg.norm(np.diff(points[:, :2], axis=0), axis=1))] + + +def sample(points, step=.15): + points = np.asarray(points, float) + d = distance(points) + keep = np.r_[True, np.diff(d) > 1e-7] + points, d = points[keep], d[keep] + if len(d) < 2: + return points + at = np.linspace(0, d[-1], max(2, int(np.ceil(d[-1] / step)) + 1)) + return np.column_stack([np.interp(at, d, points[:, i]) for i in range(3)]) + + +def lift_piece(piece, original): + """Keep Z from the original metric curve after a planar overlap operation.""" + line = LineString(original[:, :2]); d = distance(original) + xy = np.asarray(piece.coords)[:, :2] + at = [line.project(Point(p)) for p in xy] + return np.column_stack([xy, np.interp(at, d, original[:, 2])]) + + +def end_direction(points, end): + p = sample(points if end == 0 else points[::-1], .2) + delta = p[0, :2] - p[min(4, len(p)-1), :2] + return delta / max(np.linalg.norm(delta), 1e-9) + + +def smooth(points, tolerance=.12): + """Piecewise cubic B-splines, fixed endpoints/corners, bounded XYZ deviation. + + The renderer consumes sampled XYZ. The actual knots/controls are retained + for CAD consumers, including linear spans where fitting is inappropriate. + """ + points = np.asarray(points, float) + line = LineString(points[:, :2]) + if line.length < .3 or not line.is_simple: + return points, [] + # Detect structural corners on a simplified curve, not on pixel noise. + skeleton = np.asarray(line.simplify(.12).coords) + corners = [] + for i in range(1, len(skeleton)-1): + a, b = skeleton[i]-skeleton[i-1], skeleton[i+1]-skeleton[i] + if np.dot(a, b) < .766 * np.linalg.norm(a) * np.linalg.norm(b): + corners.append(int(np.argmin(np.linalg.norm(points[:, :2]-skeleton[i], axis=1)))) + cuts = sorted(set([0, *corners, len(points)-1])) + result, curves = [], [] + for low, high in zip(cuts, cuts[1:]): + original = points[low:high+1] + p = sample(original, .25) + reference = LineString(original[:, :2]) + output = original; curve = dict(degree=1, controls=original.round(5).tolist()) + if len(p) >= 4: + weights = np.ones(len(p)); weights[[0, -1]] = 1e6 + for factor in (1., .25, .0625): + with warnings.catch_warnings(): + warnings.simplefilter('error', RuntimeWarning) + try: + tck, _ = splprep(p.T, w=weights, s=len(p)*(.07**2)*factor, k=3) + candidate = np.asarray(splev(np.linspace(0, 1, max(4, int(reference.length/.15)+1)), tck)).T + except (ValueError, RuntimeWarning): + continue + candidate[[0, -1]] = original[[0, -1]] + fitted = LineString(candidate[:, :2]) + at = distance(candidate); expected_z = np.interp(at / max(at[-1], 1e-9), distance(p)/distance(p)[-1], p[:, 2]) + if (fitted.is_simple and fitted.hausdorff_distance(reference) <= tolerance + and .94 <= fitted.length/reference.length <= 1.06 + and np.max(np.abs(candidate[:, 2]-expected_z)) <= .08): + output = candidate + curve = dict(degree=3, knots=np.asarray(tck[0]).round(8).tolist(), + controls=np.asarray(tck[1]).T.round(5).tolist()) + break + result.extend(output if not result else output[1:]) + curves.append(curve) + return np.asarray(result), curves diff --git a/simulation/urban-mapping/vector/infer_vectors.py b/simulation/urban-mapping/vector/infer_vectors.py index 501a8ca9..5880494a 100644 --- a/simulation/urban-mapping/vector/infer_vectors.py +++ b/simulation/urban-mapping/vector/infer_vectors.py @@ -37,15 +37,21 @@ def main(): predictions=[];timings={} for kind in args.kinds: weights=args.assets/('sd_'+kind+'.pth') - assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch' - cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py') - cfg.model.pretrained=None;cfg.model.train_cfg=None - # Upstream coder relaxes its threshold until it finds a detection. Keep - # all native top-k scores and enforce a FIXED threshold after decoding. - cfg.model.pts_bbox_head.bbox_coder.score_threshold=None - model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval() - load_checkpoint(model,str(weights),map_location='cpu',strict=True) - model.cuda();start=time.monotonic() + global _models + if '_models' not in globals(): _models = {} + stat = weights.stat() + key = (str(weights), stat.st_size, stat.st_mtime_ns) + if key not in _models: + assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch' + cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py') + cfg.model.pretrained=None;cfg.model.train_cfg=None + # Fixed threshold: never relax until a detection appears. + cfg.model.pts_bbox_head.bbox_coder.score_threshold=None + model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval() + load_checkpoint(model,str(weights),map_location='cpu',strict=True) + _models[key] = (cfg, model.cuda()) + cfg, model = _models[key] + start=time.monotonic() for x,y in positions: crop=rgb[y:y+1000,x:x+1000] image=torch.from_numpy(crop.copy()).permute(2,0,1).float().cuda()/255. @@ -62,7 +68,7 @@ def main(): points=points,tile_xy=[x,y])) print(json.dumps(dict(kind=kind,tile=[x,y],detections=int((result['scores_3d']>=args.threshold).sum()))),flush=True) timings[kind]=time.monotonic()-start - del model;torch.cuda.empty_cache() + doc=dict(schema_version='missioncore.vector-candidates/v1',source_image_sha256=sha(args.image), vma_commit='a6e98e8f704e72499b33da84715ba39e8705e02e',weights=manifest, input_size=[w,h],native_crop_size=1000,threshold=args.threshold, diff --git a/simulation/urban-mapping/vector/refine_contours.py b/simulation/urban-mapping/vector/refine_contours.py new file mode 100644 index 00000000..74949b98 --- /dev/null +++ b/simulation/urban-mapping/vector/refine_contours.py @@ -0,0 +1,188 @@ +"""Whole-location contour consolidation, independent of inference and navigation. + + native detections -> same-class overlap removal -> unambiguous endpoint + graph with image-checked bridges -> corner-preserving cubic B-splines + +All thresholds are metric. Missing coverage, branching, road-marking gaps and +different heights are never joined just to produce a more attractive drawing. +""" +import argparse +import hashlib +import json +from collections import defaultdict +from pathlib import Path +import numpy as np +import networkx as nx +import warnings +from scipy.spatial import cKDTree +from shapely.geometry import LineString, shape +from shapely.ops import unary_union, linemerge +from shapely.strtree import STRtree +from shapely.errors import ShapelyDeprecationWarning +from contour_geometry import distance, end_direction, lift_piece, sample, smooth + +VERSION = 'missioncore.contour-consolidation/v1' + + +def semantic(f): + p=f['properties'] + return p['class'], p.get('source_class'), p.get('geometry_role') + + +class SpatialLines: + """GEOS spatial index; the pinned Shapely 1.8 returns geometry objects.""" + def __init__(self, records): + self.records={id(a['line']):a for a in records} + with warnings.catch_warnings(): + warnings.simplefilter('ignore', category=ShapelyDeprecationWarning) + self.tree=STRtree([a['line'] for a in records]) + def near(self, line, radius=.2): + return sorted((self.records[id(g)] for g in self.tree.query(line.buffer(radius))), + key=lambda a:(a['ids'],a['line'].wkt)) + + +def consolidate(document, evidence=None, progress=lambda done,total:None): + """Pure input contract: returns a new document and an auditable edit receipt.""" + features=document['features'] + if len(features)>20000:raise ValueError('Contour refinement exceeds feature budget') + report=dict(schema_version=VERSION, input_features=len(features), + duplicates=[], removed_noise=[], trimmed_overlap_m=0., joins=[], smoothed_curves=0) + lines=[]; other=[]; progress(0,4) + for f in features: + if f['geometry']['type']!='LineString' or f['properties']['class'] not in ('curb','road_marking'): + other.append(f);continue + p=np.asarray(f['geometry']['coordinates'],float) + p=p[np.r_[True,np.linalg.norm(np.diff(p[:,:2],axis=0),axis=1)>1e-7]] + if len(p)<2:continue + lines.append(dict(f=f,p=p,key=semantic(f),line=LineString(p[:,:2]),ids=[f['id']],gaps=[])) + # Prefer the stronger observation; remove only close, same-height overlap. + spatial=SpatialLines(lines); accepted=set(); records=[] + for a in sorted(lines,key=lambda a:(-a['f']['properties']['confidence'],-a['line'].length,a['f']['id'])): + masks=[] + for b in spatial.near(a['line']): + if id(b) not in accepted or a['key']!=b['key'] or a['line'].distance(b['line'])>.15:continue + if min(a['line'].length,b['line'].length)<1. and abs(np.dot(end_direction(a['p'],0),end_direction(b['p'],0)))<.94:continue + if abs(np.median(a['p'][:,2])-np.median(b['p'][:,2]))>.15:continue + mask=b['line'].buffer(.15,cap_style=2) + overlap=a['line'].intersection(mask).length + # A transverse crossing only occupies a tiny part of a line. + if overlap>=min(1.,.8*a['line'].length):masks.append(mask) + uncovered=a['line'].difference(unary_union(masks)) if masks else a['line'] + if uncovered.length<.2*a['line'].length: + report['duplicates'].append(a['f']['id']);continue + accepted.add(id(a)) + pieces=[uncovered] if uncovered.geom_type=='LineString' else list(getattr(uncovered,'geoms',[])) + report['trimmed_overlap_m']+=a['line'].length-uncovered.length + for piece in pieces: + if piece.geom_type!='LineString' or piece.length<.25:continue + p=lift_piece(piece,a['p']) + records.append({**a,'p':p,'line':LineString(p[:,:2])}) + progress(1,4) + endpoints=np.array([a['p'][e] for a in records for e in (0,-1)]) + tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None + # Remove isolated, short, weak fragments only when the survey also rejects them. + keep=[] + for i,a in enumerate(records): + neighbours=set(tree.query_ball_point(endpoints[2*i,:2],1.))|set(tree.query_ball_point(endpoints[2*i+1,:2],1.)) + isolated=all(j//2==i for j in neighbours) + if evidence and isolated and a['line'].length<1.5 and a['f']['properties']['confidence']<.5: + ground,signal=evidence.support(sample(a['p'],.1),a['key']) + if ground.mean()>.8 and signal.mean()<.25: + report['removed_noise'].append(a['f']['id']);continue + keep.append(a) + records=keep + endpoints=np.array([a['p'][e] for a in records for e in (0,-1)]) + tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None + candidates=defaultdict(list); blockers=SpatialLines(records) + openings=[shape(f['geometry']) for f in other if f['properties']['class']=='curb_cut'] + for i,q in enumerate(endpoints): + a=records[i//2];va=end_direction(a['p'],i%2) + junction=[j for j in tree.query_ball_point(q[:2],.18) if records[j//2]['key']==a['key']] + if len(set(j//2 for j in junction))>2:continue + maximum=1.25 if a['key'][0]=='curb' else (.2 if a['key'][1]=='stopline' else .5) + for j in tree.query_ball_point(q[:2],maximum): + if j<=i or i//2==j//2:continue + b=records[j//2] + if a['key']!=b['key']:continue + other_junction=[k for k in tree.query_ball_point(endpoints[j,:2],.18) if records[k//2]['key']==a['key']] + if len(set(k//2 for k in other_junction))>2:continue + delta=endpoints[j,:2]-q[:2];gap=float(np.linalg.norm(delta));vb=end_direction(b['p'],j%2) + if np.dot(va,-vb)<.94 or abs(q[2]-endpoints[j,2])>.12+.12*gap:continue + if gap>.02 and min(np.dot(va,delta/gap),np.dot(-vb,delta/gap))<.85:continue + bridge=LineString([q[:2],endpoints[j,:2]]) + if any(bridge.intersects(o) for o in openings):continue + if gap>.02 and any(c is not a and c is not b and bridge.crosses(c['line']) for c in blockers.near(bridge)):continue + bridge_points=sample(np.array([q,endpoints[j]]),.05) if gap>.02 else np.array([q,endpoints[j]]) + if gap>.12 and (evidence is None or not evidence.bridge(bridge_points,a['key'])):continue + cost=gap+1-np.dot(va,-vb) + candidates[i].append((cost,j));candidates[j].append((cost,i)) + # Mutual, separated best matches: no greedy choice at a branching/ambiguous end. + best={} + for i,options in candidates.items(): + options.sort() + if len(options)==1 or options[1][0]-options[0][0]>.15:best[i]=options[0][1] + links={i:j for i,j in best.items() if best.get(j)==i} + # NetworkX identifies components; GEOS owns line assembly and orientation. + graph=nx.Graph();graph.add_nodes_from(range(len(records))) + for i,j in links.items(): + if i1e-7: + segments.append(LineString([q,p])) + gaps.append(dict(from_xyz=q.round(4).tolist(),to_xyz=p.round(4).tolist(),length_m=round(gap,4), + evidence='image-and-ground' if gap>.12 else 'endpoint-tolerance',height_source='endpoint-interpolation')) + joins.append(dict(sources=[records[i//2]['ids'][0],records[j//2]['ids'][0]],gap_m=round(gap,4))) + merged=linemerge(segments) + if merged.geom_type!='LineString' or not merged.is_simple: + chains.extend(members);continue + report['joins'].extend(joins) + chains.append({**members[0],'p':np.asarray(merged.coords),'ids':sorted({i for a in members for i in a['ids']}),'gaps':gaps}) + progress(2,4) + output=list(other) + for a in chains: + p,curves=smooth(a['p']) + original=LineString(a['p'][:,:2]); fitted=LineString(p[:,:2]) + if any(fitted.crosses(b['line']) and not original.crosses(b['line']) for b in blockers.near(fitted) if not set(a['ids'])&set(b['ids'])): + p=a['p'];curves=[] + report['smoothed_curves']+=sum(c['degree']==3 for c in curves) + coordinates=p.round(4).tolist() + ident=hashlib.sha256(json.dumps([a['key'],coordinates],sort_keys=True).encode()).hexdigest()[:20] + props={**a['f']['properties'],'review_status':'unreviewed','consolidation':dict(version=VERSION, + source_ids=a['ids'],inferred_gaps=a['gaps'],max_fit_deviation_m=.12,splines=curves)} + output.append(dict(type='Feature',id='contour-'+ident,properties=props,geometry=dict(type='LineString',coordinates=coordinates))) + progress(3,4) + report.update(output_features=len(output),input_lines=len(lines),output_lines=len(output)-len(other), + inferred_gap_m=round(sum(g['length_m'] for a in chains for g in a['gaps']),4), + trimmed_overlap_m=round(report['trimmed_overlap_m'],3)) + result={**document,'features':output,'analysis':{**document.get('analysis',{}),'contour_refinement':{k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}}} + progress(4,4) + return result,report + + +def refine_file(source, survey, output): + from contour_evidence import SurveyEvidence + output.mkdir(parents=True,exist_ok=True) + def progress(done,total): + p=output/'progress.json.tmp';p.write_text(json.dumps(dict(phase='refining',completed=done,total=total)));p.replace(output/'progress.json') + import scipy, shapely + payload=source.read_bytes() + result,report=consolidate(json.loads(payload),SurveyEvidence(survey),progress) + provenance=dict(raw_map_sha256=hashlib.sha256(payload).hexdigest(), + libraries=dict(shapely=shapely.__version__,scipy=scipy.__version__,networkx=nx.__version__)) + report.update(provenance) + result['analysis']['contour_refinement'].update(provenance) + (output/'urban-map.json').write_text(json.dumps(result,ensure_ascii=False,allow_nan=False)) + (output/'contour-refinement.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)) + print(json.dumps({k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}),flush=True) + + +if __name__=='__main__': + p=argparse.ArgumentParser() + for name in ('source','survey','output'):p.add_argument('--'+name,type=Path,required=True) + a=p.parse_args();refine_file(a.source,a.survey,a.output) diff --git a/simulation/urban-mapping/vector/whole_vectors.py b/simulation/urban-mapping/vector/whole_vectors.py new file mode 100644 index 00000000..6461faf6 --- /dev/null +++ b/simulation/urban-mapping/vector/whole_vectors.py @@ -0,0 +1,75 @@ +"""Run native VMA over the surveyed tiles, then assemble one metric map.""" +import argparse +import json +import sys +from pathlib import Path +from types import SimpleNamespace +from vector_map import assemble, digest + + +def merge(index, documents, request): + # Load geometry after the VMA runtime; this pinned GEOS/CUDA stack is order-sensitive. + from shapely.geometry import box, shape, mapping + features=[] + for tile,document in documents: + low,high=tile['core_bounds'];core=box(*low,*high) + for f in document['features']: + geom=shape(f['geometry']) + if geom.geom_type=='Polygon': + centre=geom.centroid + if not low[0]<=centre.x20000:raise ValueError('Infrastructure result exceeds feature budget') + # Known gaps are retained as coverage facts; they never become inferred roads. + return dict(schema_version='missioncore.urban-map/v2',type='FeatureCollection', + coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False), + source={**request['source'], 'vma_commit':'a6e98e8f704e72499b33da84715ba39e8705e02e', 'weights':__import__('assets').WEIGHTS},coverage=dict(kind='objects-only',cell_m=.05,accepted_cells=0,extent_xy=index['bounds_xy']), + analysis=dict(job_key=request['key'],provider_sha256=request['identity']['provider_sha256'],scope='whole-scene', + tiles_total=len(index['tiles']),tiles_mapped=len(documents),tiles_without_ground=len(index['tiles'])-len(documents), + tiles=[{k:v for k,v in t.items() if k!='job'} for t in index['tiles']]), + review_status='unreviewed',features=features) + + +def run(root,assets,package,survey=None): + survey=survey or root + request=json.loads((root/'request.json').read_text());index=json.loads((survey/'tile-index.json').read_text()) + from infer_vectors import main as infer + documents=[] + for i,tile in enumerate(index['tiles']): + (root/'progress.json.tmp').write_text(json.dumps(dict(phase='vectorizing',completed=i,total=len(index['tiles'])))) + (root/'progress.json.tmp').replace(root/'progress.json') + if tile['status']!='surveyed':continue + folder=survey/tile['id'];out=root/tile['id']/'vectors';out.mkdir(parents=True,exist_ok=True) + receipt=out/'vector-receipt.json' + valid=False + if receipt.exists(): + old=json.loads(receipt.read_text()) + valid=old['source']==digest(folder/'survey-receipt.json') and digest(out/'urban-map.json')==old['result'] + if not valid: + sys.argv=['infer_vectors','--image',str(folder/'top.png'),'--assets',str(assets),'--output',str(out)] + infer() + assemble(SimpleNamespace(candidates=out/'candidates.json',job=folder/'job.json',image=folder/'top.png', + geometry=folder/'top.geometry.npz',atlas=folder/'surface-atlas.npz',package=package,output=out)) + receipt.write_text(json.dumps(dict(source=digest(folder/'survey-receipt.json'),result=digest(out/'urban-map.json')))) + documents.append((tile,json.loads((out/'urban-map.json').read_text()))) + result=merge(index,documents,request) + raw=root/'urban-map.raw.json' + raw.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False)) + from refine_contours import refine_file + refine_file(raw,survey,root) + (root/'progress.json.tmp').write_text(json.dumps(dict(phase='assembling',completed=len(index['tiles']),total=len(index['tiles'])))) + (root/'progress.json.tmp').replace(root/'progress.json') + result=json.loads((root/'urban-map.json').read_text()) + print(json.dumps(dict(features=len(result['features']),tiles=len(index['tiles']),mapped=len(documents))),flush=True) + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--assets',type=Path,required=True);p.add_argument('--package',type=Path,required=True) + p.add_argument('--survey',type=Path) + a=p.parse_args();run(a.root,a.assets,a.package,a.survey) diff --git a/simulation/urban-mapping/whole_scene.py b/simulation/urban-mapping/whole_scene.py new file mode 100644 index 00000000..214e088f --- /dev/null +++ b/simulation/urban-mapping/whole_scene.py @@ -0,0 +1,92 @@ +"""Bounded whole-scene survey. Tile cameras come from measured geometry, never A/B.""" +import argparse +import json +import math +from pathlib import Path +import numpy as np +from mapping import render, infer, write_json, digest, unproject, CLASSES +from atlas import fuse +from terrain import load_glb + + +def plan_tiles(request, vertices, faces): + triangles = vertices[faces] + normals = np.cross(triangles[:,1]-triangles[:,0], triangles[:,2]-triangles[:,0]) + flat = np.abs(normals[:,2]) > np.linalg.norm(normals, axis=1)*math.cos(math.radians(25)) + samples = np.concatenate([triangles[flat].reshape(-1,3), triangles[flat].mean(1)]) + if not len(samples): + raise ValueError('No measured near-horizontal surface in this scene') + bounds = np.array([vertices[:,:2].min(0), vertices[:,:2].max(0)]) + origin = np.floor(bounds[0]/40)*40 + shape = np.ceil((bounds[1]-origin)/40).astype(int) + if int(np.prod(shape)) > 256: + raise ValueError('Scene exceeds the supported 256-tile analysis envelope') + tiles=[] + for ix in range(shape[0]): + for iy in range(shape[1]): + low=origin+[ix*40,iy*40]; high=low+40; centre=(low+high)/2 + local=samples[((samples[:,:2]>=low-10)&(samples[:,:2]<=high+10)).all(1)] + item=dict(id=f'tile-{ix:03d}-{iy:03d}',core_bounds=[low.tolist(),high.tolist()],bounds_xy=[(low-10).tolist(),(high+10).tolist()]) + if len(local)<100: + tiles.append(dict(item,status='no-surface'));continue + # Lowest measured flat surface per 2m cell supplies camera candidates. + cells=np.floor((local[:,:2]-(low-10))/2).astype(int) + order=np.argsort(local[:,2]);_,indices=np.unique(cells[order],axis=0,return_index=True) + ground=local[order[indices]] + if len(ground)<8: + tiles.append(dict(item,status='no-surface'));continue + cameras=[];used=set() + for offset in [(-12,-12),(-12,12),(12,-12),(12,12)]: + anchor=centre+offset; index=int(np.argmin(np.linalg.norm(ground[:,:2]-anchor,axis=1))) + eye=ground[index].copy() + if index in used or np.linalg.norm(eye[:2]-anchor)>12:continue + used.add(index) + direction=centre-eye[:2] + if np.linalg.norm(direction)<1:direction=np.array([1.,0.]) + direction/=np.linalg.norm(direction) + target_xy=eye[:2]+direction*12 + target=ground[np.argmin(np.linalg.norm(ground[:,:2]-target_xy,axis=1))].copy() + target[:2]=target_xy;eye[2]+=1.8 + cameras.append(dict(id=f'view-{len(cameras)}',projection='pinhole',size=[800,600],eye=eye.tolist(),target=target.tolist(),fov_degrees=100)) + if not cameras: + tiles.append(dict(item,status='no-surface'));continue + top_z=float(local[:,2].max()+25) + top=dict(id='top',projection='ortho',size=[1200,1200],width_m=60,eye=[*centre,top_z],target=[*centre,top_z-1],up=[0,1,0]) + job=dict(schema_version='missioncore.urban-mapping-job/v1',source=request['source'],model=request['model'], + bounds_xy=item['bounds_xy'],cell_m=.1,halo_m=25,min_confidence=.65,atlas_only=True,views=[top,*cameras]) + tiles.append(dict(item,status='pending',job=job)) + return dict(bounds_xy=bounds.tolist(),tiles=tiles) + + +def run(request, package, output): + terrain=json.loads((package/'terrain.json').read_text()) + collider=package/(request['source']['collider_sha256']+'.decoded.glb') + meta=json.loads(collider.with_suffix('.json').read_text()) + if meta['source_sha256']!=request['source']['collider_sha256'] or digest(collider)!=meta['sha256']: + raise ValueError('Collider source mismatch') + vertices,faces=load_glb(collider,terrain['collision_rotation']) + index=plan_tiles(request,vertices,faces);del vertices,faces + for i,tile in enumerate(index['tiles']): + write_json(output/'progress.json',dict(phase='survey',completed=i,total=len(index['tiles']))) + if tile['status']!='pending':continue + folder=output/tile['id'];folder.mkdir(exist_ok=True) + job=tile.pop('job');write_json(folder/'job.json',job) + receipt=folder/'survey-receipt.json' + if receipt.exists(): + old=json.loads(receipt.read_text()) + if old['job_sha256']==digest(folder/'job.json') and all((folder/n).exists() and digest(folder/n)==h for n,h in old['files'].items()): + tile['status']=old['status'];continue + render(job,folder) + infer(job,folder) + fuse(job,folder,unproject,CLASSES,write_json) + atlas=np.load(folder/'surface-atlas.npz',allow_pickle=False) + tile['status']='surveyed' if np.count_nonzero(np.isfinite(atlas['z']))>=100 else 'unobserved-ground' + names=['top.png','top.geometry.npz','surface-atlas.npz'] + write_json(receipt,dict(job_sha256=digest(folder/'job.json'),status=tile['status'],files={n:digest(folder/n) for n in names})) + write_json(output/'tile-index.json',index) + write_json(output/'tile-index.json',index) + write_json(output/'progress.json',dict(phase='survey',completed=len(index['tiles']),total=len(index['tiles']))) + +if __name__=='__main__': + p=argparse.ArgumentParser();p.add_argument('--request',type=Path,required=True);p.add_argument('--package',type=Path,required=True);p.add_argument('--output',type=Path,required=True) + a=p.parse_args();run(json.loads(a.request.read_text()),a.package,a.output) diff --git a/simulation/urban-mapping/worker-profile.json b/simulation/urban-mapping/worker-profile.json new file mode 100644 index 00000000..d64d7e6f --- /dev/null +++ b/simulation/urban-mapping/worker-profile.json @@ -0,0 +1,10 @@ +{ + "schema_version": "missioncore.infrastructure-worker/v1", + "platform": "windows-docker-linux-cuda", + "mapper_image": "sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0", + "vector_image": "sha256:4b5ca7b8b082e469aaffaafa34eef0595de56a3ace6bca120430438c3636ca16", + "semantic_model": "assets/mask2former-mapillary/2cc022513f0012ff47d4438516284fd0946a196a", + "vector_assets": "../urban-mapping/vma-assets", + "maximum_seconds": 21600, + "minimum_free_gib": 12 +} diff --git a/simulation/urban-plan-research/README.rst b/simulation/urban-plan-research/README.rst new file mode 100644 index 00000000..3154f837 --- /dev/null +++ b/simulation/urban-plan-research/README.rst @@ -0,0 +1,534 @@ +Urban plan geometry qualification +================================ + +Offline geometric engines for four observed classes: carriageway, pedestrian +area, building facade, and road marking. Not the installed infrastructure-job +provider. Keep this module outside the production provider identity until the +complete semantic input lifecycle and new map contract are integrated. + +plan_coverage.py + Three-label Potts alpha expansion using SciPy integer maximum-flow, followed + by shared GEOS coverage simplification. All adjacent classes use one planar + coverage; no independently rounded polygons or mismatched tile borders. + +plan_primitives.py + Exposed frontage envelope from observed first-floor planes, bounded collinear + joining that cannot create facade crossings, and constant-width paint fitting. + Arbitrary symbols keep their observed polygon and holes when a strip model + does not fit. No unseen building footprint closure is generated. + +plan_acceptance.py + Executable checks for four classes, finite valid XYZ, shared coverage, facade + crossings and facade/road conflicts. Open partial paint footprints are allowed + only when explicitly typed as such. Route authority remains unassigned. + +test_plan_geometry.py + Eleven synthetic checks: all unary label changes, noise versus real obstacles, + passage preservation, shared T junctions and holes, invalid input rejection, + exposed versus recessed planes, unsupported gaps, paint widths, unknown symbols, + false facade joins and spatial conflicts. Run on the qualified mapping image: + python3 -B test_plan_geometry.py + +The runtime qualification uses Shapely 2.1.2 / GEOS 3.13.1, rasterio, SciPy, +NumPy and OpenCV. Whole-scene evidence, exact source/runtime hashes, alternative +methods, exports and visual acceptance stay in private simulation qualification +storage. Do not commit private scene data or mistake model agreement for a +surveyed accuracy result. Sampling resolution and fitting tolerances do not +certify physical positioning accuracy or safe rover passage. + +Observed-boundary revision (2026-10-11) +-------------------------------------- + +plan_boundaries.py separates physical interfaces from scan coverage boundaries +and semantic frontiers inside visible data. A missing class is not a physical +street end. It emits open chains and preserves a closed loop only when the +entire loop has physical edge support (for example, an observed traffic island). +It never extrapolates a street or closes the extent of an observation. + +frontage_chains.py joins compatible observed facade planes and nearby measured +corners, retaining source plane indices. It does not create building backs. + +paint_templates.py qualifies bounded metric A/arrow hypotheses against actual +paint geometry. Narrow lane dashes cannot be accepted as arrow templates. +Model object masks nominate regions; they must not be used as exact paint +footprints, since that fills letter holes and widens lines. + +test_observed_plan.py adds eight synthetic regressions for false caps, visible +but unclassified continuations, real islands, facade crossings/gaps and false +arrow classifications. All eight passed in the mapping qualification image. + +The whole-scene output is still NOT visually accepted or activated in the +application. Specific open side streets remain under-recognised. Unconstrained +LSD/edge continuation, material-classifier continuation and the SAM2 trials did +not meet visual acceptance; none of those extrapolations is a production +method. Geometry invariants and model confidence do not establish curb accuracy +or complete intersection coverage. Automatic SAM3 geometric re-query of visible +frontiers is under qualification separately from these geometry utilities. + + +Intersection continuation qualification (2026-10-11) +-------------------------------------------------- + +The private qualification additionally compared automatic SAM3 visual exemplars, +text-only local windows, direct curb prompts, neighbouring overlapping windows, +longitudinal contour filtering and a joint two-boundary street model. None met +whole-scene visual acceptance. Two junctions gained longer observed branches, +but gaps, class ambiguity and a third incomplete junction remain. Relaxing +Gaussian depth gates introduced false curves and was rejected. Visual box +prompts condition the segmentation; they are not a restriction to an image ROI. + +Do not copy these private experiments into the production provider or treat +longer contours, interpolated metres, model scores or passing geometry tests as +intersection acceptance. The installed application map remains unchanged. + + +Schematic continuity policy (owner correction, 2026-10-11) +--------------------------------------------------------- + +Internal quality gaps between compatible observed curb anchors are eligible for +interpolation even when the gap itself has no Gaussian evidence. This supersedes +an observation-only interpretation of internal coverage frontiers. External +survey ends remain open; opposite street sides must never be capped together. +Known openings can be protected explicitly; automatic driveway detection is +outside this first pass. + +plan_continuity.py composes existing FITPACK smoothing, CubicHermiteSpline, +cKDTree endpoint lookup and GEOS topology checks. It retains source IDs and +explicit inferred spans, pins observed endpoints, and keeps route authority +unassigned. Road evidence is asymmetric: missing evidence permits a hypothesis, +but positive road evidence on both sides, or opposite material sides at the two +anchors, rejects the join. Pass the road_occupancy callback for scene qualification; +geometry-only endpoint compatibility does not establish same-edge identity. + +The external scan_domain should exclude unscanned extensions while allowing +internal quality holes. Explicit survey-exterior, scan-limit and known-opening +endpoint tags remain protected. Six metres is the initial configurable join +budget, not a certified range or an owner-imposed permanent limit. The fitting +bound measures displacement from input vectors, not physical survey accuracy. + +Run test_plan_continuity.py on Worker. qualify_continuity.py is the offline +adapter for the existing Gaussian render cache. It is not called by the installed +provider. Exact inputs, runtime/source hashes, visual review and execution +receipts belong in private simulation qualification storage. This pass is not +a semantic detector: it cannot repair a falsely identified curb merely by +smoothing or joining it. Whole-scene acceptance remains outstanding. + + +Shape review after owner feedback (2026-10-11) +-------------------------------------------- + +The owner identified incorrect turn extents, rounded square entries, unresolved +vehicle/scooter occlusions and missing visible side-street continuations in six +review windows. Continuity counts and displacement from old vectors do not +qualify those shapes. The old two-sided hard semantic/alpha extraction drops +visible interfaces when a neighbouring class is missing; subsequent local +refinement and smoothing inherit that omission and the original radius bias. + +plan_shapes.py is an offline primitive utility only. Five synthetic cases in +test_plan_shapes.py passed on Worker: short line, noisy straight, square corner, +local tangent arc between straights, and coordinate translation. This does not +qualify scene boundary detection or independently moved primitive junctions. + +Three private Gaussian-image adaptations were visually rejected: pixel-path +edge following; whole-primitive raster scoring; and collinear-LSD continuation. +The last recovered a long continuation candidate but not a reliable curb and +introduced connector steps. They are archived under the private qualification +plan-shape-20261011, not installed as a provider. One adaptation also changed +partition tolerance, so the comparison is not a one-variable ablation. + +The next bounded qualification must reconstruct a junction jointly from long +approach supports, paired side-street boundaries, sharp-corner / local-arc / +parking-pocket alternatives and occlusion-aware evidence weights. Coincident +junction positions must be shared parameters, and G1 tangency applies only to +smooth joins. Missing classes are uncertainty, not proof of an opening. Preserve +external open street ends and the owner's internal-gap interpolation policy. +Before whole-scene use, qualify all six feedback cases, including a previously +better case as a regression control, then check overlap seams. No alternative +from this review is accepted or activated. The existing live map is unchanged. + + +Joint junction qualification (2026-10-11) +---------------------------------------- + +plan_junctions.py adds analytic line/circular-fillet chains with shared endpoints +and G1 tangency, exact radius-zero corners, bounded local Hermite seam repair, +and a nomination test for detached competing fragments. Fragment nomination is +an ambiguity layer, not semantic deletion: a real narrow island may share that +2D signature. The original geometry must remain available for review. + +test_plan_junctions.py has 18 synthetic regressions. They passed on Worker 006, +including left/right normals, overlap rejection, pocket geometry, coordinate +invariance, opposite-curb rejection, anchored local seams, and preservation of +collinear continuations and closed islands during fragment nomination. + +qualify_junctions.py is an offline six-window adapter using the existing Gaussian +orthographic render cache, known projections, prior Gaussian-derived vector +proposals and soft material/vehicle masks. It fits paired approaches and local +turns jointly with bounded SciPy Powell searches, multiple initial radii, vehicle +weights and soft road/sidewalk contrast. OpenCV and GEOS supply existing image +and topology operations. No point-cloud input or new trained model is used. +Long reliable approach directions have tighter bounds than incomplete branches. +A short opening is a zero-radius hypothesis; this is not a qualified general +classifier of courtyard entrances. The parallel-pair model also does not cover +all possible street tapers or asymmetric geometry. + +The final private qualification is plan-junctions-20261011/f6720ad1c874365f. +It improved the six feedback windows: paired visible continuation at 009, +square entry at 007, local junctions and a repaired pocket seam at 012, a 5.09 m +vehicle-occluded pocket gap at 014, and an 8.08 m scooter-area gap at 022; 023 +remained the regression control. Three competing fragments were preserved in a +separate review layer, including two beside the 012 pocket. Every output chain +is simple; there are no inter-chain crossings or closed ends in these windows. +The sole overlap, 022/023, differs by 0.0047909 m in Hausdorff distance. This is +vector consistency, not physical survey accuracy or a test against ground truth. + +A hard LSD radius cap and contrast-dominant alternatives were rejected visually. +The final source and output hashes match the Worker receipt; 31 input files are +hashed. The final bounded CPU container took about 10.5 seconds on existing +caches, excluding cache preparation and earlier trials, and was removed with +its reservation released. Keep exact evidence and private scene coordinates in +.runtime/simulation-qualifications, not Git or Ops experiment diaries. + +This is still a review candidate, not an installed provider or a complete +whole-scene map. The six outputs overlap and must not simply be concatenated +into a production map. Heights are inherited/interpolated, not refitted, and +route authority remains unassigned. Before integration, construct a common +whole-scene boundary graph with shared junction ownership, qualify remaining +junctions/overlap seams and refit height evidence. Facades and paint templates +were outside this increment. The live map remains unchanged. + +Whole-scene curb assembly (2026-10-11) +------------------------------------ + +plan_scene.py and qualify_scene_assembly.py compose the reviewed local shapes +into one map. qualify_scene_junctions.py enumerates all 27 cache windows with +both road and native semantic masks, preserving the parent curve and its XY +station intervals through clipping, pocket absorption and local joins. Accepted +patches own explicit source intervals; duplicate overlapping window proposals +are rejected, and unconsumed source continuations survive once. Artificial cuts +reconnect only by the same parent/station. No tiled feature concatenation is +used. Previously reviewed windows have precedence; the review ordering carries +no geometric corrections. + +A scene-wide continuation pass then resolves short compatible seams and +occluded gaps, retaining source coordinates outside the local seam trims. The +continuity helper's preserve_input option avoids regularizing the accepted +geometry again. Optional bridge validation admits long gaps only with positive +road/sidewalk contrast; unknown short spans remain eligible between compatible +anchors. Four competing fragments remain in separate evidence layers. Source +construction, inherited uncertainty and newly inferred spans survive assembly. +The boundary graph indexes open curb ends and edges, with construction seam +provenance separately; it is not a traversability or rover route graph. + +Final private qualification: plan-scene-20261011/1d64edcfeeb7466b. The common map +contains 13 curb chains, 1864.579 m in XY, and preserves all 723 non-curb features +unchanged (736 features total). There are 17 source-interval seams, a further +0.722 m endpoint gap reconciled locally, and global inferred spans totalling +83.444 m (a 7.669 m parking gap and a 75.775 m missing section). The latter has +81% positive road/sidewalk edge samples; this is mask support, not accuracy or +probability. A competing 41.6 m connection across a side-street region was +rejected. All final chains are simple, with no inter-chain crossings or rings. + +Fifty focused tests passed on Worker 006: 18 junction, 18 continuity and 14 +scene assembly tests. All 10 Worker source hashes and 206 output hashes were +verified after transfer. The input manifest hashes 259 files, including all 68 +render windows used in the overview and masks for the 27 fitting windows. +The final bounded CPU run took 43.735 seconds on existing caches; container and +reservation cleanup were confirmed. Reprojection views use identical final +geometry in every window. The canonical service and its 605-feature live map +were preserved. + +This increment qualifies common XY assembly, not a complete urban plan. Some +side-street branches remain absent in the input detector; the 017 street taper +is approximated by the paired-direction model, and old long-edge wiggles remain. +Unmatched ends are not automatically evidence of survey limits. Heights remain +inherited/interpolated, route permission unassigned, and facades/paint templates +unqualified by this increment. Direct overlay inspection and static HTML/JS +checks passed; interactive HTML browser QA was unavailable because the browser +policy rejects local file URLs. Exact images, results, receipts and notes live +under .runtime/simulation-qualifications/plan-scene-20261011, not in Git or Ops. + +The separate qualify_scene_invariants.py acceptance pass independently verified +source-interval accounting for all 29 parents, no pairwise contacts or overlaps, +26 endpoint nodes / 13 graph edges, unchanged non-curb objects and all 69 +inferred spans lying on final geometry. Its receipt is the private +plan-scene-20261011/48773e74e8e8b82f qualification. This script reads the accepted +candidate from /final and its immutable parent map from /continuity; it does not +refit geometry. The reviewed map SHA-256 is +0a78cd9bda60429bd2ea62dba7b2065aef1cc466799c3807bbd93e3885591eb8. + +Reviewed-region evidence refinement (2026-10-11) +---------------------------------------------- + +plan_refinement.py follows image-normal evidence profiles with dynamic +programming, then fits a robust cubic B-spline with pinned endpoint positions +and tangent directions. long_edge_refinement.py uses OpenCV LSD, coherent +line consensus and a Huber fit for long near-straight runs; short bright splat +borders cannot introduce independent local bends into that model. +refinement_evidence.py samples the most central available Gaussian render and +its derived road/sidewalk/vehicle masks across overlapping windows. + +For an explicitly owner-confirmed opening, driveway_refinement.py selects a +parallel pair of LSD side anchors using asphalt/paving texture contrast. It +intersects those sides with the existing curb and bounds their visible extent +by a supported transverse frontier. It removes the old cross-opening frontier, +retains two open branch ends, and records the intentional removed interval. +This is not a qualified automatic driveway detector. Missing side support is +an error, not permission to invent an opening. + +qualify_refinement.py reads a private review-hints.json from /candidate and +selects relevant cached windows by their bounds. Hints select review regions; +target vertices come from the evidence. It consumes the immutable assembled +baseline at /baseline, Gaussian renders at /survey, and derived masks at +/evidence; outputs go to /out. All scene computation runs on Worker 006. +The qualification refreshes the whole map and endpoint graph, accounts for +baseline curb intervals, preserves prior construction separately, and marks +all newly fitted or extrapolated geometry as inferred. Heights are inherited. + +Private qualified candidate: plan-refinement-20261011/5acb71dd0e07276c. +The four owner-marked regions now contain a square-sided driveway, adjusted +parking-pocket transitions and a corrected long curb bow. It has 14 curb +chains (1877.133 m XY), with all 723 non-curb features preserved. All 26 prior +open endpoints survive; the new access adds two. No geometry outside the four +review regions changed, to the 1 micrometre numerical comparison tolerance. +That tolerance measures preservation, not physical accuracy. + +61 focused tests passed: 11 refinement and 50 existing geometry/assembly tests. +audit_refinement.py independently checks saved JSON for finite simple curves, +no pair contacts/rings, source-interval accounting including the known opening, +unchanged exterior geometry, graph endpoint/status consistency, and complete +inferred labeling of changed geometry. It verified 28 nodes / 14 edges and 74 +inferred spans on the final curves. Source and delivery hashes are verified +against the Worker receipt. Final map SHA-256: +bbbbb647126fe9f4a96c43149acfb97891bd771e4e81b6a1676daf645cc4a18d. + +This is a local visual-review candidate. Accuracy against independent ground +truth, general driveway discovery, heights, facades and marking templates are +not qualified here. The unnumbered minor review circles were not individually +refitted. Route permission remains unassigned and the canonical live map was +not replaced. Private images, review coordinates, receipts and intermediate +trials remain under .runtime/simulation-qualifications/plan-refinement-20261011. + +Shared physical-boundary qualification (2026-10-11) +-------------------------------------------------- + +boundary_anchors.py adds scene-independent physical evidence to the existing +Gaussian-derived semantic boundary candidates. It combines OpenCV image +derivatives with height/alpha/vehicle validity, follows normal-profile +candidates with dynamic programming, and uses SciPy sparse weighted smoothing +between supported runs. Missing internal observations are explicitly inferred; +unsupported exterior tails are not extrapolated. The public input interface +contains arrays and metric resolution, with no scene names or review regions. + +Multiscale material contrast requires a central oriented edge. Junction fits +use evidence_cost over all samples, so a short visible fragment cannot win by +discarding unsupported samples. plan_continuity.regularize checks the complete +joined chain for simplicity. plan_scene.assemble_checked rejects conflicting +replacement proposals atomically, restoring their complete parent geometry; +conflicts in source geometry fail instead of receiving a clean audit. + +The private anchor-pass-20261011 v3 qualification ran the same source hashes +and parameters on all 88 Pokrovka and 68 Maroseyka windows. It reuses the prior +read-only multiview Mapillary evidence and Gaussian render products, without +manual review hints or previous vectors as computation inputs. Both runs +passed the same 92 tests and independent final geometry checks with no pair +contacts or self-intersections. Two internal assembly stations remain unresolved +on Maroseyka. Geometry took about 355 seconds combined, excluding cached rendering +and inference. Canonical live maps were unchanged. + +This is NOT a qualified complete urban plan. Full visual review still finds +missing/internal fragments, paint-related false boundaries, car/pocket ambiguity +and false side-entry arcs. Shared execution is demonstrated on two scenes; +accuracy or generalisation to arbitrary streets is not. Review addresses and +all imagery/receipts remain private qualification artifacts, not algorithm +configuration. Do not promote either candidate based on test counts or zero +intersections alone. + +Automatic material-context qualification (2026-10-11) +----------------------------------------------------- + +material_regions.py uses OpenCV GrabCut with automatic road/sidewalk core +seeds. Its colour mixtures are initialised from definite cores only, then +frozen for the spatial pass. Insufficient seeds explicitly return no material +decision. Enclosed paint holes do not become independent boundary proposals; +observed sidewalk cores protect islands. The boundary_anchors material input +is optional and only ranks candidates; physical anchor confirmation remains +separate. No scene identity, manual ROI or review coordinates enter this API. + +The private anchor-pass-20261011 v5 qualification uses the same 50 source-file +hashes and parameters across all 88 Pokrovka and 68 Maroseyka windows. Both +passed the same 98 tests and independent geometry audits, with zero pair +contacts/self-intersections. Geometry took about 371 seconds combined on +cached Gaussian renders and multiview Mapillary scores; rendering/inference +are excluded. All 156 windows were visually reviewed. Live maps are unchanged. + +This is an optional research candidate, NOT an accepted replacement for v3 +or a complete plan. A preceding hard material gate (v4) was rejected because +it removed valid branches. Soft ranking restores those branches and removes +some false paint/U-shaped fragments, but still leaves internal gaps and can +worsen junction radii. Pokrovka has three unresolved assembly stations; +Maroseyka has zero, which does not imply complete curb coverage. Whole-scene +visual improvement is mixed and independent geometric accuracy is unmeasured. +The integration runner, inputs, images, reviews and receipts remain private +under .runtime/simulation-qualifications/anchor-pass-20261011. + +Visibility-aware remaining-gap qualification (2026-10-11) +-------------------------------------------------------- + +plan_continuity.py optionally limits equivalent cubic Bezier control handles +of SciPy Hermite interpolation. gap_evidence.py treats low-opacity Gaussian +coverage, vehicles and uncertain classes as unknown; observed road/sidewalk +contradictions remain vetoes. It requires two material-separated, directionally +compatible parent approaches. gap_observations.py samples immutable Gaussian +render/class fields. Explicit exterior/opening endpoints, survey-domain, +intersection and reciprocal-choice checks remain in force. All additions are +labelled inferred; endpoint and pair decisions are auditable. + +The private v6 qualification adds this pass after unchanged v3 extraction, +junction fitting and assembly. It does not combine the optional v5 GrabCut +experiment. The identical source hashes and parameters were used for both +full scenes, without manual region hints, review priorities or baseline +vectors as computation inputs. Both runs passed 104 tests and independent +no-intersection/full-control-preservation checks. Maroseyka gained three +bridges totalling 69.782 m, reducing 25 chains to 22. Pokrovka stayed at 30 +chains with unchanged geometry. Live maps and service 8000 were unchanged. + +Visual review covered the new spans and both overview projections; unchanged +control geometry was checked programmatically rather than claiming a fresh +visual pass over every old window. A long scan dropout is now connected, but +an existing parallel parking fragment and a separate vehicle-adjacent gap +remain. This is an improvement to continuity, not a qualified complete plan, +independent accuracy result or proof of arbitrary-scene generalisation. +Private runners, source snapshots, reports and images stay under +.runtime/simulation-qualifications/anchor-pass-20261011. + + +Evidence-backed parallel-fragment qualification (2026-10-11) +------------------------------------------------------------ + +boundary_competition.py compares complete detached road-boundary hypotheses +with longer overlapping alternatives. Suppression requires directional overlap +and observed same-material evidence on both sides at 0.25 m and 1 m offsets, +while the retained alternative separates road and sidewalk. Unknown/occluded +observations cannot certify removal. Attached branches, unmatched extensions, +rings and opposite island faces are excluded. Full removed features and all +decisions remain in competition-audit.json. The API accepts metric geometry +and a field sampler, without scene identifiers, manual regions or priorities. + +The private anchor-pass-20261011 v8 qualification ran identical source hashes +and parameters over all 88 Pokrovka and 68 Maroseyka windows on Worker006. +Both runs passed 112 tests and independent no-contact/no-self-intersection +audits. Pokrovka retained all v6 geometry; Maroseyka removed one false detached +24.155 m sidewalk fragment. A separate set-difference audit verifies that no +geometry outside the recorded quarantine changed. Visual review covered the +removed fragment and both scene overviews; unchanged areas were verified by +geometry comparison, not presented as a new exhaustive visual review. + +The preceding v7 radius-support experiment is rejected as a replacement: +Huber fitting to provisional source curves sharpened some actual rounded +corners and enlarged another. Tests and clean topology did not imply visual +improvement. v8 retains the v6 radius objective and search. All v7 source, +receipts and comparison images remain private for diagnosis; they are not +an accepted radius upgrade. + +This accepted increment is limited to detached competing hypotheses. False +segments embedded in longer chains, existing corner errors and remaining +occlusion gaps are unresolved. Existing earlier geometric quarantine passes +are not newly certified by the tests for this module. Generalisation beyond +the two scenes, independent accuracy and height accuracy remain unmeasured. +Research source snapshots, exact cached-input mounts, source hashes, resource +receipts and replay scripts remain under .runtime/simulation-qualifications/ +anchor-pass-20261011/operator/reviews/v8. Product runtime/live maps are unchanged. + +Resolution and local-shape ablations (2026-10-11/12) +-------------------------------------------------- + +Two bounded experiments retained the accepted v8 control and used identical +source/configuration hashes across both developed-on scenes. Neither candidate +is promoted. Exact snapshots, receipts, failures and decisions remain under +``.runtime/simulation-qualifications/anchor-pass-20261011/operator/reviews``. + +v9 sampled native 4096-pixel Gaussian RGB instead of the existing reduced +RGB fields, retaining the same metric filters. Depth, alpha and semantic +resolution were unchanged. Pokrovka passed 117 tests and topology checks, +but acquired a new assembly failure and visibly enlarged a junction. Maroseyka +stopped on an unresolved source-geometry conflict; it has no accepted final +map. This rejects this RGB-only ablation, not every high-resolution approach. + +v10 reobserved physical edge targets around each initial junction, then +compared a corner, circular arc and convex cubic using the same targets. +Straight approaches and terminal extent remained fixed. Both scenes passed +119 tests and topology checks. Pokrovka's assembled map is byte-identical to +v8: local changed proposals did not survive existing assembly checks. Maroseyka +changed 126.645 metres of boundary but retained two old unmatched stations. +All 13 changed Maroseyka windows were reviewed. Some turns improved, while +branch offsets, parking ambiguities and gaps remained; no overall replacement +was accepted. The experimental fitter is retained privately, not published +as the default geometry implementation. + +An evaluation-only set of 116 manually marked visible-curb points covers +13 sections in five source windows. It was marked before inspecting v9 +outputs and is forbidden as fitting input. It is a regression reference with +approximately 0.20 m annotation uncertainty, not independent surveying or a +complete-map precision/recall benchmark. On Pokrovka, median/p90 distance +changed from 0.268/0.779 m (v8) to 0.501/3.775 m (v9). On Maroseyka it changed +from 0.439/1.495 m (v8) to 0.347/1.474 m (v10), below the predeclared 0.20 m +meaningful-gain threshold. These numbers do not certify map-wide accuracy. + +The accepted control remains v8. Altering radius shape alone cannot repair +incorrect branch approaches, and clean topology cannot establish correct +curb placement. A separate held-out scene is required for transfer evidence. + +Held-out scan transfer: Smolensk (2026-10-12) +-------------------------------------------- + +The private ``blind-smolensk-20261011`` qualification completed an offline +Gaussian-only pass from a third registered source package and its original +20,496 scanner poses. The old 490,355-splat cache covered only a small fragment; +the test instead converted the complete registered LOD1 payload (10,243,765 +Gaussians). A pose-only uniform survey adapter bootstrapped Gaussian expected +depth, followed by unchanged terrain admission, orthographic observation, +SAM3 occluder masks, multiview Mapillary fusion and frozen v8 geometry. +No collider, point-cloud surface, manual geometry or map-specific ROI was used. +All common v8 source files except the historical-baseline audit are identical. +The observation configuration differs only in source paths/scene identity. + +The run processed 39 orthographic windows, 73 stations and 292 street-level +views. All 112 primary geometry tests passed; the final map contains 16 open +chains, 180.278 m total XY length, no self-intersections or pair contacts. +These execution/topology results are supplemented by direct owner review on +2026-10-12. The initial assistant review incorrectly treated degraded roadway +as a reliably visible missing boundary. The owner clarified that the broad +green region is pedestrian space and is correctly segmented; the roadway +above/left of it is poorly visible, and extraction where roadway is visible +is reasonably correct. The blanket transfer-failure conclusion is withdrawn. +This supports limited qualitative transfer to the third scene, not measured +accuracy, complete-road recall or arbitrary-scene acceptance. The initial +review is retained in private review-history, superseded by owner-review.json. + +A diagnostic replay produced byte-identical initial geometry and measured +203.880 m of semantic-interface candidates entering physical refinement, +141.368 m surviving that refinement, and 180.278 m after existing continuity. +These are stage-retention lengths, not ground-truth recall. They cannot +establish excessive rejection without a reference limited to genuinely visible +curbs. The owner's visibility clarification removes the basis for diagnosing +this scene as a general extraction failure. Evaluate missing observations +separately from recognition errors. Keep the same algorithm across scenes, +interpolate internal gaps between supported anchors, and leave genuinely +unscanned exterior branches open. No new threshold tuning follows from this +review correction. + +The first fusion attempt exposed a missing orchestration dependency on cached +orthographic vehicle masks. It was corrected by running the unchanged pinned +orthographic segmentation stage, then replaying fusion. Both failed and +successful receipts are retained. No semantic or geometry parameters were +tuned after seeing this scan. The original transfer harness retains historical +``parameters_changed`` flags; the independent final-verification record and +source comparison establish that this transfer used frozen v8 parameters. + +The private qualification retains complete inputs, source snapshots, runners, +stage receipts, review and unqualified vector output. Native RGB files that +were temporarily archived are restored to all 312 original Worker paths with +SHA-256 verification. Worker containers and reservations are released; +canonical service 8000 and its prior live maps remain unchanged. Nothing from +this qualification has been promoted to the product runtime. diff --git a/simulation/urban-plan-research/assembly_pass/README.rst b/simulation/urban-plan-research/assembly_pass/README.rst new file mode 100644 index 00000000..0e72ee06 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/README.rst @@ -0,0 +1,66 @@ +Gaussian marking pose, pattern extraction and line assembly +========================================================= + +Offline continuation of catalog-pass-20261014. One algorithm and metric policy +for all three scenes; Gaussian renders only, no manual processing areas or map +identity in the algorithm. Every computation, test and image render runs on +Worker006. No live deployment, rover command, Git commit or Ops publication. + +Changes +------- +* Bicycle registration uses the existing attributed SVG. OpenCV raster scoring + evaluates 24 initial angles, retaining six separated orientations. SciPy + Powell refines centre, angle, dimensions and stroke offset. Rotation is about + the centre rather than the template tail. Image-admission thresholds remain + those of the previous catalogue pass. The expanded pose search requires a + stronger shape score of 0.80: image overlap alone can fit random road texture. + This is a shared class rule, not a location-specific rejection list. +* A native-image chromatic paint channel supplements existing general proposals. + Yellow zigzags can separate from adjacent white lines or letters. Existing + white/general candidates remain available. Colour alone admits nothing: + scikit-image skeleton, OpenCV simplification, regular-leg fit and calibrated + image checks still apply. +* Per-leg negative-space checks exclude other legs of the same complete model. + They still check positive paint and off-pattern pixels. The complete pattern + keeps its original negative-space check. Geometry selects image ownership; + brightness does not choose a favourable view. +* A regular zigzag may continue only while each next leg has complete strong + primary evidence and agrees with every available secondary portion. Unknown, + contradictory and dark continuation stops growth. Existing accepted paint + is preserved during an extension; new neighbor overlaps are forbidden. +* Long lines use the existing two-mosaic chain assembly implementation and its + original thresholds. OpenCV Huber fitting operates on original fragments. + Every edited seam needs two views; real dashed gaps and protected symbols + are barriers. Original non-marking layers remain byte-for-byte identical. + +Qualification +------------- +All transactions replay against the accepted catalogue map. Symbol changes and +line joins have separate audits plus a combined audit. Native chromatic +extraction can be reused only when its transitive local import hashes, image +digest and accepted baseline match. Final classification, joins, audit and +rendering use one frozen source bundle across every scene. Containers use the +official recorded-job reservation, no network, a read-only root, bounded CPU, +memory and runtime. Pinned wheels load only into disposable tmpfs. + +Limits +------ +Real visible symbols may still fail proposal extraction or registration. +These are known-scene regressions, not a holdout generalization benchmark. +Full recall, false-positive rate, geodetic accuracy and GOST compliance are not +measured. Two views of one Gaussian reconstruction are correlated. Old road, +facade and pedestrian-contour errors are outside this marking pass. + +Attribution +----------- +Bicycle artwork: Major Alexey, CC BY-SA 4.0. Adaptation: polygon construction, +coordinate normalization and metric registration. +https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg +https://creativecommons.org/licenses/by-sa/4.0/ +Original SHA-256: 53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59 +Existing arrow artwork: +https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg + +OpenCV, SciPy, Shapely and scikit-image remain the implementation components. +Exact outcomes and visual limitations are in verification.json and +visual-review.json. Source exports carry pinned wheels and their licences. diff --git a/simulation/urban-plan-research/assembly_pass/assembly_evidence.py b/simulation/urban-plan-research/assembly_pass/assembly_evidence.py new file mode 100644 index 00000000..a5478981 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/assembly_evidence.py @@ -0,0 +1,45 @@ +"""Two geometry-selected image mosaics for every point of a finite object. + +No demand that both complete camera rectangles contain a long polygon's bbox. +Unknown paint pixels remain unknown; different ranks never use the same tile. +""" +import numpy as np,cv2,shapely +from fit_scene import project +from layer_common import sample +from row_evidence import choose_owners +from discovery_rules import glyph_score + +def mosaic_views(p,views,kind=None,parameters=None,negative_context=None): + lo=np.asarray(p.bounds[:2])-1.;hi=np.asarray(p.bounds[2:])+1.;cell=.04 + xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell);x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()] + distance=np.linalg.norm(points[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool) + for i,tile in enumerate(views.tiles): + uv=project(points,views.geometry(tile['id']));coverage[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180) + owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1]) + for rank in [0,1]: + colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={} + for i in np.unique(owners[:,rank]): + if i<0:continue + select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5 + def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]) + colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points[select],views.low,views.high)==1);covered[select]=True + if target[select].any():names.add(name);source_counts[name]=int(target[select].sum()) + score=glyph_score(colors.reshape(len(yy),len(xx),3),allowed.reshape(len(yy),len(xx)),points,p,kind=None,parameters=None) + rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV) + bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(31,31))) + paint=((gray.astype(float)-bg>15)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))) + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0 + if negative_context is not None: + # Adjacent legs belong to the same known pattern; they are not + # unexplained paint in this leg's background. The whole pattern + # still receives its original negative-space check. + context=shapely.contains_xy(negative_context.buffer(.08),points[:,0],points[:,1]) + region=shapely.contains_xy(p.convex_hull.buffer(.15),points[:,0],points[:,1]) + negative=region&~context&allowed&covered + score['negative_paint']=float(paint.ravel()[negative].mean())if negative.any()else 0. + score['negative_space_scope']='exclude-other-legs-of-same-pattern' + known=target&allowed&covered + score['observed_support']=float(near[known].mean())if known.any()else 0. + score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank) + ev.append(score) + return ev,sorted(names) diff --git a/simulation/urban-plan-research/assembly_pass/assembly_rules.py b/simulation/urban-plan-research/assembly_pass/assembly_rules.py new file mode 100644 index 00000000..d7749e42 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/assembly_rules.py @@ -0,0 +1,17 @@ +"""Shared assembly policy, with unchanged catalogue image thresholds.""" +from catalog_rules import POLICY as CATALOG_POLICY,accept_bicycle as catalogue_bicycle,accept_zigzag +VERSION='marking-assembly-v1' +POLICY={**CATALOG_POLICY,'bicycle_fit_score':.80,'bicycle_initializer':'24-angle-centred-multistart','zigzag_max_added_legs_per_end':12,'zigzag_extension_support':.95,'zigzag_extension_valid':.97,'zigzag_junction_radius_m':.20} + +def accept_bicycle(ev,score): + # Wider pose search raises the risk of fitting random road texture. + # Image overlap alone is not a substitute for strong class-shape evidence. + return catalogue_bicycle(ev,score)if score>=POLICY['bicycle_fit_score']else None + +def extension_supported(ev): + if len(ev)!=2:return False + first,second=ev + def good(e): + coverage=e['paint_coverage'] + return coverage>0 and e['paint_valid']/coverage>=POLICY['zigzag_extension_valid']and e['observed_support']>=POLICY['zigzag_extension_support']and e['negative_paint']<=POLICY['strong_negative_paint'] + return first['paint_coverage']==1. and good(first)and(second['paint_coverage']==0. or good(second)) diff --git a/simulation/urban-plan-research/assembly_pass/assembly_templates.py b/simulation/urban-plan-research/assembly_pass/assembly_templates.py new file mode 100644 index 00000000..dedab8ab --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/assembly_templates.py @@ -0,0 +1,52 @@ +"""OpenCV raster / SciPy registration with global orientation initialization.""" +import numpy as np, cv2, shapely +from shapely.geometry import Polygon +from scipy.optimize import minimize +from catalog_templates import bicycle + +def fit_bicycle(p,all_hypotheses=False): + if p.is_empty or p.area<.10:return None + rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6) + if not(1..015 for h in holes)<2:return None + cell=.02;lo=np.asarray(p.bounds[:2])-.4;hi=np.asarray(p.bounds[2:])+.4;size=np.ceil((hi-lo)/cell).astype(int)[::-1] + def draw(poly): + m=np.zeros(size,np.uint8) + for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])): + if q.is_empty or q.geom_type!='Polygon':continue + cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1) + for h in q.interiors:cv2.fillPoly(m,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0) + return m + target=draw(p);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5));near=cv2.dilate(target,kernel);best=None + def quality(x): + m=draw(bicycle(x,fast=True));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou + coordinates=shapely.get_coordinates(p) + seeds=[] + # Global orientation search, rotated around the symbol centre. The final + # parameters still use the shared SVG base-point convention. + def from_center(x): + cx,cy,a,ll,ww,b=x + return np.r_[np.array([cx,cy])-ll/2*np.array([np.cos(a),np.sin(a)]),a,ll,ww,b] + for a in np.arange(24)*np.pi/12: + axis=np.array([np.cos(a),np.sin(a)]);normal=np.array([-axis[1],axis[0]]) + uv=np.c_[coordinates@axis,coordinates@normal] + for trim in [0.,.02]: + low,high=np.quantile(uv,[trim,1-trim],axis=0);ll,ww=high-low + if min(ll,ww)<.3:continue + center=((low+high)/2)[0]*axis+((low+high)/2)[1]*normal + x=np.r_[center,a,ll,ww,0.];seeds.append((quality(from_center(x))[2],x)) + starts=[] + for score,x in sorted(seeds,key=lambda v:-v[0]): + if any(abs(np.arctan2(np.sin(x[2]-q[2]),np.cos(x[2]-q[2])))=quality(from_center(x))[2]else x);q=quality(z) + hypothesis=dict(polygon=bicycle(z),score=q[2],support=q[0],recall=q[1],parameters=z.tolist());hypotheses.append(hypothesis) + return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else max(hypotheses,key=lambda x:x['score'],default=None) diff --git a/simulation/urban-plan-research/assembly_pass/assembly_zigzag.py b/simulation/urban-plan-research/assembly_pass/assembly_zigzag.py new file mode 100644 index 00000000..a6c6cab7 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/assembly_zigzag.py @@ -0,0 +1,18 @@ +"""Extend a regular seed only while each additional leg is observed.""" +import numpy as np +from shapely.geometry import LineString +from assembly_rules import POLICY + +def extend(vertices,width,check): + q=np.asarray(vertices,float);k=np.arange(len(q));X=np.c_[k,(-1.)**k,np.ones(len(k))];coef=np.linalg.lstsq(X,q,rcond=None)[0] + if np.linalg.norm(X@coef-q,axis=1).max()>.01:return dict(vertices=q.tolist(),evidence=[],legs_added=0) + def point(k):return np.array([k,(-1.)**k,1.])@coef + accepted=[];left=[];right=[] + for direction in [-1,1]: + current=q[0]if direction==-1 else q[-1] + for step in range(1,POLICY['zigzag_max_added_legs_per_end']+1): + index=-step if direction==-1 else len(q)-1+step;endpoint=point(index);p=LineString([current,endpoint]).buffer(width/2,cap_style=2,join_style=2) + okay,ev,names=check(p) + if not okay:break + (left if direction==-1 else right).append(endpoint.tolist());accepted.append(dict(direction=direction,step=step,vertices=[current.tolist(),endpoint.tolist()],evidence=ev,source_tiles=names));current=endpoint + return dict(vertices=list(reversed(left))+q.tolist()+right,evidence=accepted,legs_added=len(left)+len(right)) diff --git a/simulation/urban-plan-research/assembly_pass/audit_assembly.py b/simulation/urban-plan-research/assembly_pass/audit_assembly.py new file mode 100644 index 00000000..e717021c --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/audit_assembly.py @@ -0,0 +1,42 @@ +from pathlib import Path +import json,hashlib,runpy,numpy as np,shapely +from shapely.geometry import shape,LineString +from assembly_rules import POLICY,VERSION,accept_bicycle,accept_zigzag,extension_supported +from assembly_zigzag import extend +from discovery_rules import uncovered +old=json.loads(Path('/fullplan/full-map.json').read_text());intermediate=json.loads(Path('/out/assembly-map.json').read_text());new=json.loads(Path('/out/full-map.json').read_text());rows=json.loads(Path('/out/assembly-additions.json').read_text());current={f['id']:f for f in old['features']} +def poly(f):return shapely.force_2d(shape(f['geometry'])) +checks=dict(additions_replay=True,only_paint_changed=True,evidence_passes=True,neighbors_preserved=True) +for r in rows: + ids=r['source_ids'];before=r['before'];after=r['after'];q=poly(after[0]);existing=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking']) + checks['additions_replay']&=r['output_ids']==[f['id']for f in after]and len(after)==1 and all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and all(f['id']not in current for f in after) + checks['only_paint_changed']&=all(f['properties']['class']=='road_marking'for f in before+after) + okay=True;ev=r['evidence'] + if r['kind']=='preset-bicycle': + okay=not before and r['lane_context']['passed']and r['lane_context']['supporting_length_m']>=POLICY['bicycle_context_length_m']and accept_bicycle(ev,r['template_fit_score'])==r['evidence_mode'] + checks['neighbors_preserved']&=uncovered(q,existing) + elif r['kind']=='regularized-zigzag': + fit=dict(legs=r['leg_count'],fit_residual_m=r['fit_residual_m'],proposal_recall=r['proposal_recall']);okay=not before and accept_zigzag(ev['whole'],ev['legs'],fit)==r['evidence_mode'];checks['neighbors_preserved']&=uncovered(q,existing) + elif r['kind']=='observed-zigzag-extension': + okay=len(before)==1 and before[0]['properties']['subtype']=='zigzag'and len(ev)==r['legs_added']and all(extension_supported(e['evidence'])for e in ev)and extension_supported(r['whole_evidence']) + original=poly(before[0]);params=before[0]['properties'];afterprops=after[0]['properties'] + def check(p): + match=next((e for e in ev if p.symmetric_difference(LineString(e['vertices']).buffer(r['width_m']/2,cap_style=2,join_style=2)).area<1e-7),None) + return (bool(match)and extension_supported(match['evidence']),match['evidence']if match else[],match['source_tiles']if match else[]) + replay=extend(params['vertices'],params['width_m'],check) + okay&=replay['legs_added']==r['legs_added']and np.allclose(replay['vertices'],afterprops['vertices']) + expected=shapely.union_all([original,LineString(replay['vertices']).buffer(r['width_m']/2,cap_style=2,join_style=2)]) + okay&=q.symmetric_difference(expected).area<1e-7 and original.difference(q).area<1e-8 + other=shapely.union_all([poly(f)for fid,f in current.items()if fid not in ids and f['properties']['class']=='road_marking']);checks['neighbors_preserved']&=q.difference(original).intersection(other).area<=.005 + else:okay=False + checks['evidence_passes']&=bool(okay) + for fid in ids:del current[fid] + for f in after:current[f['id']]=f +checks['intermediate_matches_replay']=current=={f['id']:f for f in intermediate['features']} +joined=runpy.run_path('/candidate/audit_assembly_joins.py')['result'];checks['join_audit_passed']=joined['passed'] +features={f['id']:f for f in new['features']};checks['original_nonpaint_unchanged']=all(features.get(f['id'])==f for f in old['features']if f['properties']['class']!='road_marking') +report=json.loads(Path('/out/assembly-report.json').read_text());checks['policy_pinned']=report['policy']==POLICY and report['policy_version']==VERSION +checks['proposal_caches_pinned']=report['proposal_cache_sha256']==hashlib.sha256(Path('/searchplan/search-proposals.json').read_bytes()).hexdigest()and report['catalog_proposals_sha256']==hashlib.sha256(Path('/fullplan/catalog-proposals.json').read_bytes()).hexdigest()and report['chromatic_proposals_sha256']==hashlib.sha256(Path('/out/assembly-proposals.json').read_bytes()).hexdigest() +checks['all_operations_counted']=report['symbol_transactions']==len(rows)and report['changed_segments']==len(json.loads(Path('/out/assembly-rows.json').read_text())) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(Path('/out/full-map.json').read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/assembly-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/assembly_pass/audit_assembly_joins.py b/simulation/urban-plan-research/assembly_pass/audit_assembly_joins.py new file mode 100644 index 00000000..ac313fe0 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/audit_assembly_joins.py @@ -0,0 +1,33 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +from row_profiles import POLICY,VERSION,fit_chain +old=json.loads(Path('/out/assembly-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/rows-rows.json').read_text());removed=set(json.loads(Path('/out/rows-replacements.json').read_text())['removed_ids']);original={f['id']:f for f in old['features']};features={f['id']:f for f in new['features']};checks={} +checks['unique_ids']=len(features)==len(new['features']) +checks['unchanged_features_identical']=all(features.get(fid)==f for fid,f in original.items()if fid not in removed) +checks['only_nondashed_linear_replaced']=all(original[fid]['properties'].get('subtype')=='linear_marking'and original[fid]['properties'].get('line_kind')!='dashed'for fid in removed) +checks['every_source_traced']=removed==set(fid for r in rows for fid in r['source_ids']) +checks['disjoint_source_groups']=sum(len(r['source_ids'])for r in rows)==len(removed) +checks['new_outputs_traced']=set(features)-set(original)==set(fid for r in rows for fid in r['output_ids']) +checks['objects_count_closes']=len(features)==len(original)-len(removed)+len(rows) +checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']) +protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and(f['properties'].get('subtype')!='linear_marking' or f['properties'].get('line_kind')=='dashed')]) +checks['protected_markings_avoided']=all(shape(features[r['output_ids'][0]]['geometry']).intersection(protected).area<=.005 for r in rows) +def geometry_check(r): + inputs=[shapely.force_2d(shape(original[fid]['geometry']))for fid in r['source_ids']];rec=fit_chain(inputs) + if rec is None or rec['max_axis_displacement_m']>POLICY['max_axis_displacement_m']:return False + p=shapely.force_2d(shape(features[r['output_ids'][0]]['geometry'])) + if r['kind']=='whole-row-fit':return p.symmetric_difference(rec['polygon']).area<1e-8 + before=shapely.union_all(inputs);domain=shape(r['edit_domain']) + return r['kind']=='preserved-contour-union'and p.symmetric_difference(shapely.union_all([before,domain])).area<1e-8 and p.difference(domain).symmetric_difference(before.difference(domain)).area<1e-8 +checks['every_chain_geometry_bounded']=all(geometry_check(r)for r in rows) +def image_evidence(r): + if len(r['views'])!=2 or len(set(r['source_tiles']))<2:return False + def local(v):return v['median_contrast']>=22 and v['longest_visible_dark_run_m']<=.20 and v['ridge_median_offset_m']<=.065 and v['ridge_q90_offset_m']<=.10 and all(s['valid']>=.95 and s['support']>=.9 for s in v['seams']) + full=[local(v)and v['valid']>=.95 and v['support']>=.85 for v in r['views']] + return all(local(v)for v in r['views'])and (all(full)if r['kind']=='whole-row-fit'else any(full)) +checks['two_evidence_mosaics_pass_every_seam']=all(image_evidence(r)for r in rows) +checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes() +checks['same_policy']=new['row_refinement']==VERSION and json.loads(Path('/out/rows-report.json').read_text())['policy']==POLICY +result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/rows-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/assembly_pass/bundle.json b/simulation/urban-plan-research/assembly_pass/bundle.json new file mode 100644 index 00000000..0bb87258 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/bundle.json @@ -0,0 +1,230 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "assembly_evidence.py": "assembly_pass/assembly_evidence.py", + "assembly_rules.py": "assembly_pass/assembly_rules.py", + "assembly_templates.py": "assembly_pass/assembly_templates.py", + "assembly_zigzag.py": "assembly_pass/assembly_zigzag.py", + "audit_assembly.py": "assembly_pass/audit_assembly.py", + "audit_assembly_joins.py": "assembly_pass/audit_assembly_joins.py", + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_catalog.py": "catalog_pass/audit_catalog.py", + "audit_completion.py": "completion_pass/audit_completion.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_corridor.py": "corridor_pass/audit_corridor.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_search.py": "search_pass/audit_search.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "bicycle_artwork.py": "catalog_pass/bicycle_artwork.py", + "catalog_context.py": "catalog_pass/catalog_context.py", + "catalog_dependencies.py": "catalog_pass/catalog_dependencies.py", + "catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py", + "catalog_evidence.py": "catalog_pass/catalog_evidence.py", + "catalog_rules.py": "catalog_pass/catalog_rules.py", + "catalog_templates.py": "catalog_pass/catalog_templates.py", + "catalog_zigzag.py": "catalog_pass/catalog_zigzag.py", + "completion_profiles.py": "completion_pass/completion_profiles.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "coordinate_cache.py": "orthophoto/coordinate_cache.py", + "corridor_profiles.py": "search_pass/corridor_profiles.py", + "coverage_evidence.py": "corridor_pass/coverage_evidence.py", + "coverage_plan.py": "corridor_pass/coverage_plan.py", + "diagnose_assembly.py": "assembly_pass/diagnose_assembly.py", + "diagnose_corridor.py": "corridor_pass/diagnose_corridor.py", + "diagnose_coverage.py": "corridor_pass/diagnose_coverage.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_assembly.py": "assembly_pass/extract_assembly.py", + "extract_catalog.py": "catalog_pass/extract_catalog.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "extract_search.py": "search_pass/extract_search.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "inspect_bicycles.py": "catalog_pass/inspect_bicycles.py", + "inspect_catalog.py": "catalog_pass/inspect_catalog.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "join_assembly.py": "assembly_pass/join_assembly.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "mapping.py": "corridor_pass/mapping.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "ortho_terrain.py": "orthophoto/ortho_terrain.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "refine_assembly.py": "assembly_pass/refine_assembly.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_catalog.py": "catalog_pass/refine_catalog.py", + "refine_completion.py": "completion_pass/refine_completion.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_corridor.py": "corridor_pass/refine_corridor.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_search.py": "search_pass/refine_search.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_assembly.py": "assembly_pass/render_assembly.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_catalog.py": "catalog_pass/render_catalog.py", + "render_completion.py": "completion_pass/render_completion.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_corridor.py": "corridor_pass/render_corridor.py", + "render_coverage.py": "corridor_pass/render_coverage.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "catalog_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_search.py": "search_pass/render_search.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "corridor_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "search_rules.py": "search_pass/search_rules.py", + "search_views.py": "search_pass/search_views.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "test_assembly.py": "assembly_pass/test_assembly.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_catalog.py": "catalog_pass/test_catalog.py", + "test_completion.py": "completion_pass/test_completion.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_corridor.py": "corridor_pass/test_corridor.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_search.py": "search_pass/test_search.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py", + "validation.py": "corridor_pass/validation.py" + }, + "reference_qualification": "assembly-pass-20261014", + "source_snapshot": "696ffe52ca7aecc01171", + "source_sha256": { + "assembly_evidence.py": "0fda82c403f9734ea0b0267504ac82437092d410882dc21417a492de9509c09b", + "assembly_rules.py": "04798c28e0daccc8be5fb045cc736160721308f7c41189f287b97a509999ddbf", + "assembly_templates.py": "41ec0428032ae328d5f46c34702d5b0be43f724e5821278e745554c72326d402", + "assembly_zigzag.py": "dbee99c505381fbdccbecec0817e0ec4e028ac1eb475124829cd58811251b9ca", + "audit_assembly.py": "8defc22e391c330962c503b27c49b9d13cecee90b0170dab1b8372858bda3638", + "audit_assembly_joins.py": "e8a3ded181b69961c8a0a5f88e171ff5ada82f0a43e55c217bb40734e411c094", + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2", + "audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f", + "catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80", + "catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca", + "catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a", + "catalog_evidence.py": "6eeb6f18e9dc2fef6f490ba5a09eba64c2021c16dbdf0594921ed5a563d23868", + "catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb", + "catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092", + "catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f", + "completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4", + "corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672", + "coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497", + "coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda", + "diagnose_assembly.py": "44ef17e6bdecc9285ae8150ccb5c4dd397006381b34b013ebd3e2ed6c2b34bbc", + "diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6", + "diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "extract_assembly.py": "d2f1cd5a1fc03b95496b32e024452c3e8ba489a06299a6cba967d4d18a5c3b33", + "extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb", + "inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "join_assembly.py": "293fd78d10f0ba13b1339a69d737c3f96ef003ea3f6dd63fdf02d14c40fa324f", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "refine_assembly.py": "0da00d12e4bda06760a3fc78fcddb6875012edc046e9f83a00074846031b4939", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb", + "refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_assembly.py": "b8471dceb42be102eeb1918eb7950e038d3fc9e0ebab0a3b01b3aaea8be710fa", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b", + "render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f", + "render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41", + "search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "test_assembly.py": "80510625a71ea9fc04add883d9a7e40a3bfdcac4251bd702b5507ce76f9bba8f", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4", + "test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e", + "validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c" + }, + "external_dependencies": { + "packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759", + "scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660", + "imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf", + "networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", + "lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc", + "tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/assembly_pass/diagnose_assembly.py b/simulation/urban-plan-research/assembly_pass/diagnose_assembly.py new file mode 100644 index 00000000..2a74f953 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/diagnose_assembly.py @@ -0,0 +1,29 @@ +"""Exhaustive geometric zigzag proposal review; no manually selected ROI.""" +from pathlib import Path +import json,numpy as np,cv2,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S,parts +from search_views import SearchViews +from fit_scene import project +from catalog_zigzag import fit_zigzag +proposals=json.loads(Path('/fullplan/catalog-proposals.json').read_text())['glyphs'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,None,None,None,None);font=ImageFont.truetype('/candidate/review-font.ttf',18);rows=[];frames=[] +for i,r in enumerate(proposals): + p=shape(r['geometry']);rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True) + if not(3.65)).astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0 + gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2) + ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel);binary=((ridge>12)&(gray>90)&(hsv[:,:,1]>35)&(hsv[:,:,0]>10)&(hsv[:,:,0]<38)&allowed).astype('uint8') + cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[] + if hier is not None: + for i,c in enumerate(cc): + if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.008:continue + holes=[];j=hier[0,i,2] + while j>=0: + if cv2.contourArea(cc[j])*mpp*mpp>.003:holes.append(xy(cc[j][:,0])) + j=hier[0,j,0] + components.extend(parts(shapely.make_valid(Polygon(xy(c[:,0]),holes)))) + union=shapely.union_all(components);candidates=list(components) + for radius in [.08,.16]: + for region in parts(union.buffer(radius).buffer(-radius)): + if eligible(region):candidates.append(union.intersection(region.buffer(.015))) + accepted=[] + for p in candidates: + if not eligible(p):continue + if any(p.intersection(q).area/min(p.area,q.area)>.85 for q in accepted):continue + accepted.append(p);glyphs.append(dict(geometry=mapping(p),source_tile=name)) + reports.append(dict(tile=name,proposal_pixels=size,candidates=len(accepted)));print('TILE',name,'CANDIDATES',len(accepted),flush=True) +candidates=[];ordered=sorted([(r,shape(r['geometry']))for r in glyphs],key=lambda v:-v[1].area) +geometries=[p for _,p in ordered];tree=shapely.STRtree(geometries);accepted=set() +for i,(r,p) in enumerate(ordered): + if any(j in accepted and p.intersection(geometries[j]).area/min(p.area,geometries[j].area)>.85 for j in tree.query(p,predicate='intersects')):continue + candidates.append(r);accepted.add(i) +(O/'assembly-proposals.json').write_text(json.dumps(dict(glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),source='all native Gaussian frames; additional yellow channel; no manual regions'),allow_nan=False)) +print('PROPOSALS',len(candidates),'SECONDS',time.monotonic()-start,flush=True) diff --git a/simulation/urban-plan-research/assembly_pass/join_assembly.py b/simulation/urban-plan-research/assembly_pass/join_assembly.py new file mode 100644 index 00000000..8c9bd65b --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/join_assembly.py @@ -0,0 +1,62 @@ +from pathlib import Path +import os,json,time,hashlib,numpy as np,cv2,shapely +from shapely.geometry import shape +from shapely.ops import transform +from layer_common import O,S,sample,feature +from row_profiles import POLICY,VERSION,pair,fit_chain,check_chain +from search_views import SearchViews +cv2.setNumThreads(3);started=time.monotonic();baseline=O/'assembly-map.json';old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']} +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +# A known dashed feature is an explicit transition barrier. Existing crosswalks +# and symbols are also protected, as in prior passes. +protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and(f['properties'].get('subtype')!='linear_marking' or f['properties'].get('line_kind')=='dashed')]) +linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['properties'].get('line_kind')!='dashed'and f['geometry']['type']=='Polygon'} +views=SearchViews(tiles,labels,low,high,protected);current={fid:dict(polygon=p,source_ids=[fid])for fid,p in linear.items()};considered=set();history=[];diagnostics=[] +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +while True: + candidates=[];entries=sorted(current.items()) + for i,(aid,a)in enumerate(entries): + for bid,b in entries[:i]: + identity=tuple(sorted(a['source_ids']+b['source_ids'])) + if identity in considered or a['polygon'].distance(b['polygon'])>.56:continue + candidate=pair(a['polygon'],b['polygon']) + if candidate is not None:candidates.append((abs(candidate['gap_m']),identity,aid,bid)) + accepted=False + for _,identity,aid,bid in sorted(candidates): + considered.add(identity);rec=fit_chain([linear[fid]for fid in identity]) + if rec is None:diagnostics.append(dict(source_ids=identity,reason='whole-chain-geometry'));continue + p=rec['polygon'] + if p.intersection(protected).area>.005:diagnostics.append(dict(source_ids=identity,reason='protected-marking'));continue + # Do not make a new overlap with an unselected line. Old overlaps can + # remain for a later evidence-based cleanup; this pass cannot grow them. + before=shapely.union_all([linear[fid]for fid in identity]);novel=p.difference(before) + if any(novel.intersection(q).area>.005 for fid,q in linear.items()if fid not in identity):diagnostics.append(dict(source_ids=identity,reason='new-neighbor-overlap'));continue + readers,used=views.readers(rec['origin'],rec['axis']);okay,ev=check_chain(rec,readers) + diagnostics.append(dict(source_ids=identity,reason='accepted'if okay else 'image-veto',views=ev,source_views=used)) + if not okay:continue + p=rec['output_polygon'];novel=p.difference(before) + if p.intersection(protected).area>.005 or any(novel.intersection(q).area>.005 for fid,q in linear.items()if fid not in identity):continue + fid='chain-'+hashlib.sha256('|'.join(identity).encode()).hexdigest()[:20] + current.pop(aid);current.pop(bid);current[fid]=dict(polygon=p,source_ids=list(identity),record=rec,views=ev,source_views=used) + history.append(dict(source_ids=list(identity),chain_id=fid));accepted=True;print('JOIN',len(history),'FRAGMENTS',len(identity),'LENGTH',round(rec['length'],2),flush=True);break + if not accepted:break + if len(history)>1000:raise RuntimeError('Unbounded chain growth') +removed=set();generated=[];rows=[] +for fid,g in current.items(): + if len(g['source_ids'])<2:continue + rec=g['record'];ids=g['source_ids'];p=g['polygon'];source_tiles=sorted(set(g['source_views'][0])|set(g['source_views'][1]));removed.update(ids) + f=feature(lift(p),'road_marking',subtype='linear_marking',line_kind='solid',method=VERSION,source_ids=ids,source_tiles=source_tiles,template_width_m=rec['width'],whole_chain_refit=True,assembly_operation=rec['operation'],standard_compliance='not_assessed');generated.append(f) + rows.append(dict(kind=rec['operation'],edit_domain=shapely.geometry.mapping(rec['edit_domain']),source_ids=ids,output_ids=[f['id']],source_tile=source_tiles[0],source_tiles=source_tiles,source_views=g['source_views'],bounds_xy=p.bounds,axis=rec['axis'].tolist(),origin=rec['origin'].tolist(),length_m=rec['length'],width_m=rec['width'],max_axis_displacement_m=rec['max_axis_displacement_m'],seams=rec['seams'],views=g['views'],added_area_m2=p.difference(shapely.union_all([linear[i]for i in ids])).area)) +result={**old,'features':[f for f in old['features']if f['id']not in removed]+generated,'row_refinement':VERSION} +(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'rows-rows.json').write_text(json.dumps(rows,indent=2));(O/'rows-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'rows-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed)),indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(rows),merged_fragments=len(removed),final_rows=len(rows),accepted_joins=len(history),whole_row_fits=sum(r['kind']=='whole-row-fit'for r in rows),preserved_contour_unions=sum(r['kind']=='preserved-contour-union'for r in rows),candidate_chains=len(considered),before_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in old['features']),after_linear_objects=sum(f['properties'].get('subtype')=='linear_marking'for f in result['features']),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'rows-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) + +combined=json.loads((O/'assembly-additions.json').read_text()) +for row in rows: + row['before']=[original[fid]for fid in row['source_ids']];row['after']=[f for f in generated if f['id']in row['output_ids']] +combined+=rows +(O/'assembly-rows.json').write_text(json.dumps(combined,indent=2)) + +r=json.loads((O/'assembly-report.json').read_text());r.update(symbol_transactions=len(json.loads((O/'assembly-additions.json').read_text())),changed_segments=len(combined),merged_fragments=len(removed),joined_lines=len(rows),join_policy=POLICY,join_policy_version=VERSION);(O/'assembly-report.json').write_text(json.dumps(r,indent=2)) diff --git a/simulation/urban-plan-research/assembly_pass/refine_assembly.py b/simulation/urban-plan-research/assembly_pass/refine_assembly.py new file mode 100644 index 00000000..f634d201 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/refine_assembly.py @@ -0,0 +1,97 @@ +from pathlib import Path +import os,json,time,hashlib,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping,LineString,Point +from shapely.ops import transform +from layer_common import O,S,sample,feature,parts +from search_views import SearchViews +from discovery_rules import unpack,uncovered,glyph_context +from discovery_evidence import glyph_views +from assembly_evidence import mosaic_views +from line_reconstruction import rows +from beta_profiles import describe,profiles,section_evidence +from interval_profiles import rectangle +from corridor_profiles import missing_sections +from assembly_templates import fit_bicycle +from catalog_zigzag import fit_zigzag +from assembly_rules import VERSION,POLICY,accept_bicycle,accept_zigzag,extension_supported +from assembly_zigzag import extend +from catalog_context import bicycle_context +cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']} +proposal_path=Path('/searchplan/search-proposals.json');proposals=json.loads(proposal_path.read_text()) +fresh_path=Path('/fullplan/catalog-proposals.json');fresh=json.loads(fresh_path.read_text()) +proposals['glyphs']=fresh['glyphs'] +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +def poly(f):return shapely.force_2d(shape(f['geometry'])) +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking']) +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +views=SearchViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[] +def admit(p,subtype,kind,evidence,names,**extra): + global existing + if not uncovered(p,existing):return False + f=feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_tile=names[0],source_tiles=names,standard_compliance='not_assessed',**extra) + if f['id']in current:return False + current[f['id']]=f;existing=shapely.union_all([existing,p]);transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']],before=[],after=[f],bounds_xy=p.bounds,evidence=evidence,source_tiles=names,**extra));print('ADMIT',len(transactions),subtype,kind,flush=True);return True + +for i,r in enumerate(proposals['glyphs']): + p=shape(r['geometry']);fits=fit_bicycle(p,all_hypotheses=True) + if not fits:continue + for fit in fits: + diag={k:v for k,v in fit.items()if k!='polygon'};diag.update(kind='bicycle',proposal=i);diagnostics.append(diag) + if fit['score'].005:continue + names=sorted(set(props.get('source_tiles',[]))|{n for e in growth['evidence']for n in e['source_tiles']}) + metadata={k:v for k,v in props.items()if k not in ['class','method','source_tile','source_tiles','vertices','leg_count','source_ids','extension_evidence','extended_from']} + out=feature(lift(q),'road_marking',method=VERSION,source_tile=names[0],source_tiles=names,vertices=growth['vertices'],leg_count=len(growth['vertices'])-1,source_ids=[fid],extended_from=fid,**metadata) + del current[fid];current[out['id']]=out + transactions.append(dict(kind='observed-zigzag-extension',source_ids=[fid],output_ids=[out['id']],before=[f],after=[out],bounds_xy=q.bounds,source_tiles=names,evidence=growth['evidence'],whole_evidence=whole_evidence,legs_added=growth['legs_added'],width_m=props['width_m'])) + existing=shapely.union_all([existing,q]);print('EXTENDED',growth['legs_added'],'LEGS',flush=True) +result={**old,'features':list(current.values()),'assembly_refinement':VERSION};(O/'assembly-map.json').write_text(json.dumps(result,allow_nan=False));(O/'assembly-additions.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'assembly-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_cache_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),catalog_proposals_sha256=hashlib.sha256(fresh_path.read_bytes()).hexdigest(),chromatic_proposals_sha256=hashlib.sha256(chromatic_path.read_bytes()).hexdigest(),proposal_cache_baseline_sha256=proposals['baseline_sha256'],changed_segments=len(transactions),added_objects=sum(not r['before']for r in transactions),added_subtypes=dict(collections.Counter(r['after'][0]['properties']['subtype']for r in transactions if not r['before'])),stages=dict(collections.Counter(r['kind']for r in transactions)),zigzag_legs_added=sum(r.get('legs_added',0)for r in transactions),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'assembly-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/assembly_pass/render_assembly.py b/simulation/urban-plan-research/assembly_pass/render_assembly.py new file mode 100644 index 00000000..58358ea8 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/render_assembly.py @@ -0,0 +1,33 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from search_views import SearchViews +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'assembly-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('assembly-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +views=SearchViews(tiles,None,None,None,None);tiles=views.tiles +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='assembly-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('assembly-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'assembly-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) diff --git a/simulation/urban-plan-research/assembly_pass/test_assembly.py b/simulation/urban-plan-research/assembly_pass/test_assembly.py new file mode 100644 index 00000000..07ccdff0 --- /dev/null +++ b/simulation/urban-plan-research/assembly_pass/test_assembly.py @@ -0,0 +1,38 @@ +import runpy,json,numpy as np,shapely +from shapely.geometry import box,LineString +from shapely.affinity import rotate,translate +from catalog_templates import bicycle +from assembly_templates import fit_bicycle +from assembly_zigzag import extend +from assembly_rules import extension_supported +catalog_scope=runpy.run_path('/candidate/test_catalog.py');prior=catalog_scope['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +for angle,L,W in [(0.41,.75,1.4),(1.13,1.5,.85),(2.85,.85,1.6)]: + p=bicycle([24,-17,angle,L,W,0]);fit=fit_bicycle(p) + checks['global_bicycle_pose_'+str(angle)]=fit is not None and fit['score']>.85 and fit['polygon'].symmetric_difference(p).area/p.area<.30 +q=np.array([(0,0),(2,2),(4,0),(6,2),(8,0)],float) +strong=dict(paint_coverage=1.,paint_valid=1.,observed_support=.99,negative_paint=.02) +absent=dict(paint_coverage=0.,paint_valid=0.,observed_support=0.,negative_paint=1.) +checks['zig_extension_strong_complete_view']=extension_supported([strong,absent]) +checks['zig_extension_incomplete_primary_rejected']=not extension_supported([{**strong,'paint_coverage':.9},absent]) +checks['zig_extension_contradiction_rejected']=not extension_supported([strong,{**strong,'observed_support':.3}]) +checks['zig_extension_unknown_primary_rejected']=not extension_supported([{**strong,'paint_valid':.5},absent]) +observed=LineString([(-4,0),(-2,2)]+q.tolist()+[(10,2),(12,0)]).buffer(.075,cap_style=2,join_style=2) +def check(p):return p.difference(observed).area<1e-7,[strong,absent],['synthetic'] +g=extend(q,.12,check);checks['zig_extension_stops_at_observed_ends']=g['legs_added']==4 and np.allclose(g['vertices'][0],[-4,0])and np.allclose(g['vertices'][-1],[12,0]) +g=extend(q,.12,lambda p:(False,[],[]));checks['zig_extension_no_evidence_no_growth']=g['legs_added']==0 and g['vertices']==q.tolist() +rotated=rotate(observed,37,origin=(0,0));a=np.deg2rad(37);R=np.array([[np.cos(a),-np.sin(a)],[np.sin(a),np.cos(a)]]);g=extend(q@R.T,.12,lambda p:(p.difference(rotated).area<1e-7,[strong,absent],['synthetic']));checks['zig_extension_rotation_invariant']=g['legs_added']==4 +from assembly_evidence import mosaic_views +fv=catalog_scope['FakeViews']([0,5]);leg=box(-.5,-.06,.5,.06);context=box(-5,-.06,5,.06) +plain,_=mosaic_views(leg,fv);aware,_=mosaic_views(leg,fv,negative_context=context) +checks['adjacent_known_pattern_is_not_background_error']=all(b['negative_paint']a['negative_paint']for n,a in zip(noise,aware)) +from assembly_rules import accept_bicycle +complete={**strong,'support':1.,'recall':1.} +checks['bicycle_image_support_cannot_rescue_weak_shape']=accept_bicycle([complete,complete],.75)is None +checks['bicycle_strong_shape_and_image_can_pass']=accept_bicycle([complete,complete],.85)is not None +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/assembly-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed'] diff --git a/simulation/urban-plan-research/audit_refinement.py b/simulation/urban-plan-research/audit_refinement.py new file mode 100644 index 00000000..6947fe77 --- /dev/null +++ b/simulation/urban-plan-research/audit_refinement.py @@ -0,0 +1,54 @@ +"""Independent checks of the saved candidate; never refits geometry.""" +import numpy as np +from shapely.geometry import shape,box,LineString +from shapely.ops import unary_union + +def audit(base,result,hints,reports,graph): + old=[f for f in base['features']if f['properties']['class']=='road_boundary'] + new=[f for f in result['features']if f['properties']['class']=='road_boundary'] + other=lambda doc:[f for f in doc['features']if f['properties']['class']!='road_boundary'] + assert other(base)==other(result) + assert base['source']==result['source']and base['coordinate_system']==result['coordinate_system'] + geoms=[shape(f['geometry'])for f in new] + assert all(g.is_simple and not g.is_ring and np.isfinite(g.coords).all()for g in geoms) + contacts=[(new[i]['id'],new[j]['id'])for i,a in enumerate(geoms)for j in range(i+1,len(geoms))if a.intersects(geoms[j])] + assert not contacts,contacts + reviewed=unary_union([box(*h['bounds'])for h in hints['cases']]) + before=unary_union([shape(f['geometry'])for f in old]);after=unary_union(geoms) + outside_before=before.difference(reviewed);outside_after=after.difference(reviewed) + lost=outside_before.difference(outside_after.buffer(1e-6)).length;added=outside_after.difference(outside_before.buffer(1e-6)).length + assert lost<1e-5 and added<1e-5,(lost,added) + oldends=[f['geometry']['coordinates'][i]for f in old for i in(0,-1)] + newends=[f['geometry']['coordinates'][i]for f in new for i in(0,-1)] + assert all(p in newends for p in oldends) + assert len(newends)==len(oldends)+2 + accounting=[] + for f in old: + intervals=[] + for n in new: + for part in n['properties']['construction']: + intervals.extend(p['interval_m']for p in part['parents']if p['id']==f['id']) + openings=[r['opening']['source_interval_m']for r in reports if r['feature_id']==f['id']and'opening'in r] + cursor=0.;overlap=0.;gap=0. + for a,b in sorted(intervals+openings): + overlap+=max(0.,cursor-a);gap+=max(0.,a-cursor);cursor=max(cursor,b) + gap+=max(0.,shape(f['geometry']).length-cursor) + assert gap<1e-5 and overlap<1e-5,(f['id'],gap,overlap) + accounting.append(dict(id=f['id'],unaccounted_m=gap,duplicate_m=overlap,retained_intervals=intervals,known_opening_intervals=openings)) + spans=[] + for f,g in zip(new,geoms): + for span in f['properties'].get('inferred_spans',[]): + s=LineString(span['coordinates']);assert s.difference(g.buffer(1e-6)).length<1e-5,(f['id'],span['method']);spans.append(s) + changed=after.difference(before.buffer(1e-6));unmarked=changed.difference(unary_union(spans).buffer(2e-6)).length + assert unmarked<1e-4,unmarked + nodes={n['id']:n for n in graph['nodes']};assert len(graph['edges'])==len(new) + features={f['id']:f for f in new} + for e in graph['edges']: + assert e['geometry']==features[e['id']]['geometry'] + assert nodes[e['start_node']]['coordinates']==e['geometry']['coordinates'][0] + assert nodes[e['end_node']]['coordinates']==e['geometry']['coordinates'][-1] + props=features[e['id']]['properties'] + assert nodes[e['start_node']]['status']==props.get('start_reason','open-curb-end') + assert nodes[e['end_node']]['status']==props.get('end_reason','open-curb-end') + assert graph['route_permission']==result['route_permission']=='unassigned' + return dict(status='passed',curb_chains=len(new),total_features=len(result['features']),length_xy_m=sum(g.length for g in geoms),non_curbs_unchanged=len(other(base)),self_intersections=0,pair_contacts=0,rings=0,prior_endpoints_preserved=len(oldends),new_open_access_ends=2,changed_outside_review_m=lost+added,unmarked_new_geometry_m=unmarked,inferred_spans=len(spans),graph_nodes=len(nodes),graph_edges=len(graph['edges']),source_accounting=accounting) diff --git a/simulation/urban-plan-research/beta_pass/README.rst b/simulation/urban-plan-research/beta_pass/README.rst new file mode 100644 index 00000000..e4302045 --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/README.rst @@ -0,0 +1,81 @@ +Whole-map linear marking batch, 2026-10-12 +======================================== + +This offline research candidate processes the rows-pass-20261012 maps with a +single common policy. It is not a live map deployment or a general urban-map +acceptance. Roads, sidewalks, facades, crosswalks and symbols are preserved. + +Stages in refine_beta.py +----------------------- + +1. All eligible existing linear objects seed a Gaussian image search, extending + 12 metres beyond each endpoint. Every profile uses two spatially selected + evidence mosaics. Their sources are selected by coverage and distance before + reading paint intensity. They are distinct renders of the same reconstruction. +2. OpenCV transverse background removal, SciPy prominence/width measurements and + the existing robust periodic-row fitter discover bounded short/long dash rows. + Both views must contain actual stroke edges. Constant spacing cannot authorize + a missing observation. Short rows need four strokes, long rows three. Rhythm + changes and unknown observations bound accepted subsequences. A faint paint + underlay requires an observed prominent peak sequence and contrast drop in + both views. Output stroke width, phase and period come from the scene. +3. Solid endpoints may move by 0.12 to 2 metres only with observed paint inside, + a dark interval outside, and support throughout the edit in both views. + The full transverse corridor is checked before shortening a line; sideways + drift cannot be interpreted as a paint ending. Confirmed dark edge padding + can absorb obsolete tiny end caps when replacing a periodic family. + Missing alpha/road coverage, vehicles and protected symbols are unknown. +4. The qualified whole-chain assembler joins compatible solid fragments only + across image-supported seams, with known dashed objects acting as barriers. + +No scene-specific coordinates, manually selected detector ROI, point cloud, +collider, external road geometry, or street-specific threshold is used. The scene +selector chooses paths only. Additional Gaussian rendering was not performed. + +Geometry and audit +------------------ + +Each transaction records exact input/output features, edit domain, image evidence +and source tiles. Changes are limited to selected linear marking features. +Longitudinal residuals retain original XY outside accepted intervals; output Z +is sampled from the existing Gaussian-derived height field. All other features +are preserved byte-for-byte as JSON objects. Newly added overlaps with neighboring +markings are vetoed. Source IDs and transaction replay reconstruct the output. + +The audit checks transaction replay, finite valid XYZ, unchanged other layers, +protected paint, overlap growth, outside-interval preservation, common policy, +and numerical evidence gates. Controlled tests include all prior line passes. +The fourth stage can yield zero edits; execution is not a claim of additional +assembly improvement on each scene. + +Each accepted dash family retains a dimensional association with the existing +GOST catalog; dimensions and phase are not forced to nominal values. +The existing GOST crosswalk assessment is retained unchanged. Measurement remains +authoritative; no legal compliance or surveying accuracy is claimed. + +Reproduction +------------ + +Use the canonical Mission Core checkout and the recorded Worker006 qualification +runner. bundle.json references unchanged modules in their canonical locations; +new modules live in beta_pass. The qualified staging snapshot contains all Python +files and the pinned review font. The source ZIP excludes the external font. +Private cached Gaussian RGB/geometry/vehicle masks, Gaussian-derived semantic and +height fields, accepted baseline maps and the pinned Docker image are required. +An identical frozen source bundle is evaluated on Maroseyka, Pokrovka and Smolensk. + +Runner constraints: Worker006, 4 CPU, 20 GiB, network none, read-only root, +1 GiB tmpfs, no capabilities, 1800-second stage bound, canonical queue reservation +and explicit resource release. The Mac only orchestrates, copies and views results. +Qualification receipts, input hashes, map audits, JPG comparisons and transaction +JSON are retained with the result. The number of changed objects is not accuracy. + +Limitations +----------- + +Discovery needs at least one existing approximately aligned linear seed. Curved +rows, fully missed disconnected rows, symbols, arrows, road/facade reconstruction, +and additional rendering are outside this batch. Two-view gating may retain a +known defect where evidence is incomplete. This is conservative missing-evidence +handling, not proof that the unchanged geometry is correct. Qualitative review of +edits does not establish exhaustive detection recall on these or unseen scenes. diff --git a/simulation/urban-plan-research/beta_pass/audit_beta.py b/simulation/urban-plan-research/beta_pass/audit_beta.py new file mode 100644 index 00000000..639c997f --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/audit_beta.py @@ -0,0 +1,45 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +from beta_profiles import POLICY,VERSION,supported +old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/beta-rows.json').read_text());current={f['id']:f for f in old['features']};checks={} +def poly(f):return shapely.force_2d(shape(f['geometry'])) +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +checks['transaction_replay']=True;checks['only_linear_objects_replaced']=True;checks['no_new_neighbor_overlap']=True;checks['protected_paint_preserved']=True;checks['evidence_passes']=True;checks['outside_edit_interval_preserved']=True +for r in rows: + before=r['before'];after=r['after'];ids=r['source_ids'] + checks['transaction_replay']&=all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and r['output_ids']==[f['id']for f in after] + checks['only_linear_objects_replaced']&=all(f['properties'].get('subtype')=='linear_marking'for f in before+after) + a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in after]);novel=b.difference(a) + checks['protected_paint_preserved']&=novel.intersection(protected).area<=POLICY['max_new_neighbor_overlap_m2'] + checks['no_new_neighbor_overlap']&=all(novel.intersection(poly(f)).area<=POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and f['properties'].get('subtype')=='linear_marking') + ev=r['evidence'];ok=len(r['source_views'])==2 and len(r['source_tiles'])>=2 + if r['kind']=='periodic-row': + ok&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint']) + ok&=len(ev['gaps'])==2*(len(ev['observations'])-1) + ok&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps']) + ok&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=POLICY['max_edge_disagreement_m']for e in ev['observations']) + ok&=all(e['padding']<=POLICY['max_family_edge_padding_m']and len(e['views'])==2 and all(v.get('full_corridor')and supported(v,False)for v in e['views'])for e in ev['edges']) + # The transverse replacement section is wider than the modeled stripe; + # the outside longitudinal old contours must nevertheless be exact. + from interval_profiles import rectangle + d=shape(r['edit_domain']);o=np.array(r['origin']);u=np.array(r['axis']);tt=(np.asarray(d.exterior.coords)-o)@u;domain=rectangle(o,u,float(tt.min()),float(tt.max()),2.) + checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7 + elif r['kind']=='solid-endpoints': + ok&=all(len(e['evidence'])==2 and POLICY['min_endpoint_change_m']<=abs(e['delta'])<=POLICY['max_endpoint_change_m']and all(supported(v['paint'])and supported(v['dark'],False)and supported(v['edit'],e['kind']=='extend-solid')for v in e['evidence'])for e in ev) + ok&=all(v['dark'].get('full_corridor')and(e['kind']=='extend-solid'or v['edit'].get('full_corridor'))for e in ev for v in e['evidence']) + domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7 + elif r['kind']=='assembled-row': + ok&=len(ev)==2 and r['max_axis_displacement_m']<=.065 and all(v['local_evidence_passed']for v in ev)and any(v['passed']for v in ev) + else:ok=False + checks['evidence_passes']&=ok + for i in ids:current.pop(i,None) + for f in after:current[f['id']]=f +features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features']) +checks['unchanged_other_layers']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('subtype')!='linear_marking') +checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']) +checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes() +report=json.loads(Path('/out/beta-report.json').read_text());checks['same_policy']=new['beta_refinement']==VERSION and report['policy']==POLICY +checks['every_operation_counted']=report['changed_segments']==len(rows)and sum(report['stages'].values())==len(rows) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/beta-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/beta_pass/beta_profiles.py b/simulation/urban-plan-research/beta_pass/beta_profiles.py new file mode 100644 index 00000000..3008870b --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/beta_profiles.py @@ -0,0 +1,181 @@ +"""Row-scale paint interpretation using shared, metric image-evidence rules. + +OpenCV background subtraction, SciPy peaks/robust fitting and the existing +periodic-row fitter are reused. Both geometrically selected Gaussian mosaics +must support each edit. They are two renders, not independent physical scans. +""" +import numpy as np +from scipy.ndimage import gaussian_filter1d +from scipy.signal import find_peaks, peak_widths +from interval_profiles import strip, runs, rectangle +from line_reconstruction import observation, reconstruct + +VERSION='paint-row-batch-v1' +POLICY=dict(step_m=.025, extension_m=12., max_seed_length_m=70., + max_seed_width_m=.35, min_seed_length_m=.30, normal_half_width_m=.7, + max_ridge_offset_m=.13, max_view_offset_disagreement_m=.05, + min_valid=.95, min_bright=.82, min_contrast=22., min_dark=.85, + max_edge_disagreement_m=.20, max_phase_error_m=.20, + min_short_strokes=4,min_long_strokes=3,max_dash_length_m=10.5, + min_dash_length_m=.26,max_crack_m=.125,min_gap_m=.12, + max_endpoint_change_m=2.,min_endpoint_change_m=.12, + max_new_neighbor_overlap_m2=.005,min_material_change_m2=.015, + endpoint_dark_corridor_m=.20,max_endpoint_ridge_offset_m=.065, + max_family_edge_padding_m=.20) + +def describe(poly): + if poly.geom_type!='Polygon':return None + z=observation(np.asarray(poly.exterior.coords),'seed') + if not POLICY['min_seed_length_m']<=z['L']<=POLICY['max_seed_length_m'] or z['W']>POLICY['max_seed_width_m']:return None + u=z['axis'].astype(float);u/=np.linalg.norm(u) + return dict(origin=z['center'].astype(float),axis=u,length=float(z['L']),width=float(z['W'])) + +def profiles(seed,readers,extension=None): + if len(readers)!=2:return None + o,u=seed['origin'],seed['axis'];step=POLICY['step_m'];ext=POLICY['extension_m']if extension is None else extension + ts=np.arange(-seed['length']/2-ext,seed['length']/2+ext+step/2,step) + ns=np.arange(-POLICY['normal_half_width_m'],POLICY['normal_half_width_m']+step/2,step) + result=[] + for read in readers: + contrast,allowed=strip(o,u,ts,ns,read) + central=abs(ts)<=max(seed['length']/2,1.) + transverse=np.quantile(np.where(allowed[central],contrast[central],0),.8,axis=0) + pk,_=find_peaks(transverse,height=18,prominence=8,distance=4) + pk=[k for k in pk if abs(ns[k])<=POLICY['max_ridge_offset_m']] + if not pk:return None + k=min(pk,key=lambda k:abs(ns[k]));pw=peak_widths(transverse,[k],rel_height=.5)[0][0]*step + if not .045<=pw<=.35:return None + band=abs(ns-ns[k])<=.04 + sig=gaussian_filter1d(np.median(contrast[:,band],axis=1),1) + valid=allowed[:,band].all(1) + level=float(np.quantile(sig[central&valid],.8))if np.any(central&valid)else 0. + if levelcut)&valid + for a,b in runs(~paint): + if a>0 and b=POLICY['min_dash_length_m']] + peaks,_=find_peaks(np.where(valid,sig,0),prominence=18,distance=int(.45/step)) + widths=peak_widths(np.where(valid,sig,0),peaks,rel_height=.5) + peak_intervals=[(float(ts[0]+widths[2][j]*step),float(ts[0]+widths[3][j]*step))for j in range(len(peaks))if .26POLICY['max_view_offset_disagreement_m']:return None + return result + +def section_evidence(v,lo,hi,bright=True): + sel=(v['ts']>=lo)&(v['ts']<=hi) + if sel.sum()<3:return dict(valid=0.,support=0.,contrast=0.) + sig=v['signal'][sel] + return dict(valid=float(v['valid'][sel].mean()),support=float((sig>v['cut']).mean()if bright else(sig=POLICY['min_valid'] and ev['support']>=(POLICY['min_bright']if bright else POLICY['min_dark']) and (ev['contrast']>=POLICY['min_contrast']if bright else True) + +def corridor_dark(v,lo,hi): + """A bent/offset paint ridge is not an end: inspect the full local corridor.""" + sel=(v['ts']>=lo)&(v['ts']<=hi);band=abs(v['ns']-v['offset'])<=POLICY['endpoint_dark_corridor_m'] + if sel.sum()<3:return dict(valid=0.,support=0.,contrast=0.) + c=v['contrast'][sel][:,band];valid=v['allowed'][sel][:,band].all(1);signal=c.max(1) + return dict(valid=float(valid.mean()),support=float((signalmax(.15,.22*L):continue + rs=[dict(center=o+((a+b)/2)*u+offset*n,axis=u,L=b-a,W=width,source_tile='two-gaussian-mosaics')for a,b in seq] + fit=reconstruct(dict(records=rs,origin=o+offset*n,axis=u,points=np.array([r['center']for r in rs]),parallel=False),minimum_period_to_length=1.10) + if fit is None or fit['kind']!='dashed' or fit['period_m']-LPOLICY['max_edge_disagreement_m']:okay=False;break + observations.append(dict(center=c,edges=matched)) + if not okay:continue + centers=[r['center']for r in observations];gap_evidence=[] + for a,b in zip(centers,centers[1:]): + lo=a+fit['length']/2+.04;hi=b-fit['length']/2-.04 + for v in views: + ev=section_evidence(v,lo,hi,False) + # A visible low floor is allowed only with an independently + # identified high-contrast peak rhythm in both images. + if mode=='peak_intervals': + paint=min(section_evidence(v,a-fit['length']*.3,a+fit['length']*.3)['contrast'],section_evidence(v,b-fit['length']*.3,b+fit['length']*.3)['contrast']) + ev['contrast_drop']=paint-ev['contrast'];ok=ev['valid']>=POLICY['min_valid']and ev['contrast_drop']>=18 and ev['contrast'].01 for q in accepted):continue + accepted.append(r) + return accepted + +def endpoints(seed,views): + """Correct a solid end only where both paint and its following gap exist.""" + if views is None or seed['length']<2.7:return [] + changes=[];L=seed['length'];o,u=seed['origin'],seed['axis'] + for sign in [-1,1]: + edge=sign*L/2;inside=edge-sign*min(L*.4,2.5);options=[] + for v in views: + options.append([ab for ab in v['intervals']if ab[0]POLICY['max_edge_disagreement_m']:continue + end=float(np.mean(ends));delta=sign*(end-edge) + if not POLICY['min_endpoint_change_m']<=abs(delta)<=POLICY['max_endpoint_change_m']:continue + if any(abs(x[1]-x[0])<2.7 for x in ab):continue + evs=[];okay=True + for v in views: + bright=section_evidence(v,*sorted([end-sign*.5,end-sign*.08]));dark=corridor_dark(v,*sorted([end+sign*.08,end+sign*.35])) + if not supported(bright)or not supported(dark,False):okay=False;break + if delta>0 and abs(v['offset'])>POLICY['max_endpoint_ridge_offset_m']:okay=False;break + edited=section_evidence(v,*sorted([edge+sign*.03,end-sign*.06]))if delta>0 else corridor_dark(v,*sorted([end+sign*.06,edge-sign*.03])) + if not supported(edited,delta>0):okay=False;break + evs.append(dict(paint=bright,dark=dark,edit=edited)) + if not okay:continue + lo,hi=sorted([edge,end]);domain=rectangle(o,u,lo,hi,2.) + changes.append(dict(kind='extend-solid'if delta>0 else'trim-solid',sign=sign,delta=delta,lo=lo,hi=hi,domain=domain,polygon=rectangle(o,u,lo,hi,seed['width']),evidence=evs)) + return changes diff --git a/simulation/urban-plan-research/beta_pass/bundle.json b/simulation/urban-plan-research/beta_pass/bundle.json new file mode 100644 index 00000000..7d292d40 --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/bundle.json @@ -0,0 +1,96 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "fit_scene.py": "full_plan/fit_scene.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "continuation_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "row_evidence.py": "rows_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py" + }, + "reference_qualification": "beta-pass-20261012", + "source_snapshot": "b6572b4a70c07ae8aece", + "source_sha256": { + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/beta_pass/refine_beta.py b/simulation/urban-plan-research/beta_pass/refine_beta.py new file mode 100644 index 00000000..21849289 --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/refine_beta.py @@ -0,0 +1,118 @@ +from pathlib import Path +import os,json,time,hashlib,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping +from shapely.ops import transform +from layer_common import O,S,sample,feature,parts +from beta_profiles import POLICY,VERSION,describe,profiles,discover,endpoints +from row_evidence import GaussianViews +from row_profiles import pair,fit_chain,check_chain +from transition_profiles import residual_sections +from gost_catalog import assess_dash + +cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']};current=dict(original) +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +views=GaussianViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[];domains=[] +def poly(f):return shapely.force_2d(shape(f['geometry'])) +def linear(f):return f['properties'].get('subtype')=='linear_marking' +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +def make(p,kind,ids,**kw):return feature(lift(p),'road_marking',subtype='linear_marking',line_kind=kind,method=VERSION,source_ids=ids,standard_compliance='not_assessed',**kw) +def commit(kind,ids,new,domain,ev,used,extra=None): + before=[current[i]for i in ids];new=[f for f in new if not poly(f).is_empty];newids=[f['id']for f in new] + if len(set(newids))!=len(newids)or any(i in current and i not in ids for i in newids):return False + a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in new]);novel=b.difference(a) + if a.symmetric_difference(b).areaPOLICY['max_new_neighbor_overlap_m2']:return False + if any(novel.intersection(poly(f)).area>POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and linear(f)):return False + for i in ids:current.pop(i) + for f in new:current[f['id']]=f + rec=dict(kind=kind,source_ids=ids,output_ids=newids,before=before,after=new,bounds_xy=(shapely.union_all([a,b])if kind=='assembled-row'else domain).bounds,edit_domain=mapping(domain),evidence=ev,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),added_area_m2=float(novel.area),removed_area_m2=float(a.difference(b).area)) + if extra:rec.update(extra) + transactions.append(rec);print('EDIT',len(transactions),kind,len(ids),'->',len(new),flush=True);return True + +# Stage 1: every eligible existing axis seeds a 24m wider image search. Spatial +# neighborhoods already covered by an accepted periodic model are not reworked. +seeds=[] +for fid,f in original.items(): + if not linear(f):continue + rec=describe(poly(f)) + if rec is not None:seeds.append((fid,rec)) +proposals=[] +for index,(fid,seed)in enumerate(sorted(seeds,key=lambda x:-x[1]['length'])): + readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers) + found=discover(seed,pv);diagnostics.append(dict(seed_id=fid,stage='discover',profile_valid=pv is not None,proposals=len(found))) + for r in found:r.update(seed_id=fid,source_views=used);proposals.append(r) + if index%25==0:print('PROFILE',index+1,'/',len(seeds),'PROPOSALS',len(proposals),flush=True) + +# Stage 2: one normalized row replaces only its observed longitudinal section. +for r in sorted(proposals,key=lambda x:(-len(x['polygons']),-x['hi']+x['lo'])): + domain=r['domain'];u=r['axis'];o=r['origin'];n=np.array([-u[1],u[0]]);origin=o+r['offset']*n + if any(domain.intersection(d).area>.01 for d in domains):continue + ids=[];residual=[] + for fid,f in current.items(): + if not linear(f):continue + p=poly(f);d=describe(p) + if d is None or p.intersection(domain).area<.005 or abs(d['axis']@u).13:continue + # Old complete stroke centers must agree with the new ridge; crossings + # and a genuine neighboring stripe are not part of this row. + ids.append(fid) + for pp in parts(residual_sections(p,domain,o,u)): + if pp.area>.000001:residual.append(make(pp,f['properties'].get('line_kind','solid'),[fid],role='unchanged-section')) + if not ids:continue + generated=[make(p,'dashed',ids,period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']),observed_stroke=True)for p in r['polygons']] + before=shapely.union_all([poly(current[i])for i in ids]);new_strokes=sum(p.intersection(before).area/max(p.area,1e-9)<.35 for p in r['polygons']) + ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode']) + if commit('periodic-row',ids,residual+generated,domain,ev,r['source_views'],dict(period_m=r['period'],dash_length_m=r['length'],newly_captured_strokes=new_strokes,normalized_strokes=len(generated),axis=u.tolist(),origin=o.tolist())):domains.append(domain) + +# Stage 3: false solid ends and missed tails. Each edit needs visible paint and +# the following dark interval in both mosaics, including at existing transitions. +for fid in list(current): + f=current.get(fid) + if f is None or not linear(f)or f['properties'].get('line_kind')=='dashed':continue + p=poly(f);seed=describe(p) + if seed is None or seed['length']<2.7:continue + readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers,extension=2.5);changes=endpoints(seed,pv) + if not changes:continue + output=p;edit=[];ev=[] + for c in changes: + output=output.union(c['polygon'])if c['kind']=='extend-solid'else output.difference(c['domain']) + edit.append(c['domain']);ev.append({k:c[k]for k in ['kind','delta','evidence']}) + if output.geom_type!='Polygon' or not output.is_valid:continue + commit('solid-endpoints',[fid],[make(output,'solid',[fid])],shapely.union_all(edit),ev,used) + +# Stage 4: run the qualified whole-row assembly against the new graph. Known +# dashes and symbols remain barriers. All original fragments are fitted jointly. +barriers=shapely.union_all([protected]+[poly(f)for f in current.values()if linear(f)and f['properties'].get('line_kind')=='dashed']) +joinviews=GaussianViews(tiles,labels,low,high,barriers);initial={fid:poly(f)for fid,f in current.items()if linear(f)and f['properties'].get('line_kind')!='dashed'} +groups={fid:[fid]for fid in initial};considered=set() +while True: + choices=[];entries=sorted(groups) + for i,aid in enumerate(entries): + for bid in entries[:i]: + identity=tuple(sorted(groups[aid]+groups[bid])) + if identity in considered:continue + a,b=poly(current[aid]),poly(current[bid]) + if a.distance(b)>.56:continue + q=pair(a,b) + if q is not None:choices.append((abs(q['gap_m']),identity,aid,bid)) + accepted=False + for _,identity,aid,bid in sorted(choices): + considered.add(identity);r=fit_chain([initial[i]for i in identity]) + if r is None or r['polygon'].intersection(barriers).area>.005:continue + readers,used=joinviews.readers(r['origin'],r['axis']);okay,ev=check_chain(r,readers) + if not okay:continue + p=r['output_polygon'] + if p.intersection(barriers).area>.005:continue + f=make(p,'solid',[aid,bid],assembly_operation=r['operation']) + if commit('assembled-row',[aid,bid],[f],r['edit_domain'],ev,used,dict(assembly_operation=r['operation'],max_axis_displacement_m=r['max_axis_displacement_m'])): + groups.pop(aid);groups.pop(bid);groups[f['id']]=list(identity);accepted=True;break + if not accepted:break + if len(transactions)>1500:raise RuntimeError('Unbounded edits') + +result={**old,'features':list(current.values()),'beta_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False)) +(O/'beta-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'beta-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +counts=collections.Counter(r['kind']for r in transactions) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(counts),profiled_axes=len(seeds),proposed_periodic_rows=len(proposals),newly_captured_strokes=sum(r.get('newly_captured_strokes',0)for r in transactions),normalized_strokes=sum(r.get('normalized_strokes',0)for r in transactions),endpoint_extensions=sum(e['kind']=='extend-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),endpoint_trims=sum(e['kind']=='trim-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),before_linear_objects=sum(linear(f)for f in original.values()),after_linear_objects=sum(linear(f)for f in current.values()),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'beta-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/beta_pass/render_beta.py b/simulation/urban-plan-research/beta_pass/render_beta.py new file mode 100644 index 00000000..0a2bed23 --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/render_beta.py @@ -0,0 +1,41 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'beta-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('beta-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='beta-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('beta-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'beta-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) +# Revisit every short-dash family shown in the prior delivery, using its stored +# bounds only for review framing; these bounds never enter the detector. +references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[] +for gi,rec in enumerate(references): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]): + frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640') + fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only')) +(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2)) diff --git a/simulation/urban-plan-research/beta_pass/test_beta.py b/simulation/urban-plan-research/beta_pass/test_beta.py new file mode 100644 index 00000000..f53f43ec --- /dev/null +++ b/simulation/urban-plan-research/beta_pass/test_beta.py @@ -0,0 +1,67 @@ +import json,runpy,numpy as np +from interval_profiles import rectangle +from beta_profiles import describe,profiles,discover,endpoints,fit_series +prior=runpy.run_path('/candidate/test_rows.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +o=np.zeros(2);u=np.array([1.,0.]) +def reader(intervals,offset=0,missing=None,underlay=0): + def read(xy): + x,y=xy.T;on=np.zeros(len(x),bool) + for a,b in intervals:on|=(x>=a)&(x<=b) + sig=(underlay+140*on)*np.exp(-.5*((y-offset)/.045)**2) + rgb=np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8');valid=np.ones(len(x),bool) + if missing is not None:valid[(x>missing[0])&(x=10 +checks['every_new_stroke_has_two_observed_edges']=bool(fit)and all(len(x['edges'])==2 for x in fit[0]['observations']) +checks['one_view_cannot_authorize_row']=not discover(seed,profiles(seed,[read])) +unknown=reader(dash,missing=(2,4)) +checks['unknown_slot_not_invented']=all(not 2.1=0)&(x<=9) + signal=140*on*np.exp(-.5*((y-center)/.04)**2) + return np.repeat((65+signal)[:,None],3,1).astype('uint8'),np.ones(len(x),bool) +checks['bent_tail_not_mistaken_for_dark_end']=not endpoints(s,profiles(s,[bent,bent],extension=2.5)) +offsetread=reader([(0,9)],offset=.1) +checks['offset_paint_cannot_extend_old_axis']=not endpoints(s,profiles(s,[offsetread,offsetread],extension=2.5)) +nonstandard=reader([(i*1.65,i*1.65+.55)for i in range(-4,6)]) +nf=discover(seed,profiles(seed,[nonstandard,nonstandard])) +checks['nonstandard_period_retained']=bool(nf)and abs(nf[0]['period']-1.65)<.1 +verylong=reader([(0,20)]) +checks['long_extrapolation_bounded']=not endpoints(s,profiles(s,[verylong,verylong],extension=2.5)) +checks['wide_seed_not_lane_stripe']=describe(rectangle(o,u,0,5,.5))is None +checks['tiny_seed_not_lane_stripe']=describe(rectangle(o,u,0,.2,.1))is None +theta=.83;R=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([120.,-63.]) +from shapely.geometry import Polygon +sr=describe(Polygon(np.asarray(rectangle(o,u,0,.5,.12).exterior.coords)@R.T+shift));rr=lambda xy:read((xy-shift)@R) +fr=discover(sr,profiles(sr,[rr,rr]));checks['rigid_transform_preserves_detected_row']=bool(fr)and len(fr[0]['polygons'])==len(fit[0]['polygons']) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/beta-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed'] diff --git a/simulation/urban-plan-research/boundary_anchors.py b/simulation/urban-plan-research/boundary_anchors.py new file mode 100644 index 00000000..6c76c2cf --- /dev/null +++ b/simulation/urban-plan-research/boundary_anchors.py @@ -0,0 +1,241 @@ +"""Metric physical-edge anchors, followed by weighted minimum-curvature fitting. + +OpenCV derivatives, SciPy sampling/Viterbi costs and a sparse smoothing solve. +Semantic masks locate a search corridor, never certify an observed curb. +No scene names, route coordinates, tile IDs or model-specific parameters. +""" +from dataclasses import dataclass, asdict +import numpy as np +import cv2 +from scipy.ndimage import gaussian_filter, gaussian_filter1d, map_coordinates, maximum_filter +from scipy.sparse import diags +from scipy.sparse.linalg import spsolve +from shapely.geometry import LineString + + +@dataclass(frozen=True) +class AnchorPolicy: + sample_m: float = .20 + search_m: float = 3.0 + search_step_m: float = .10 + cross_section_m: float = .35 + occluder_margin_m: float = .35 + alpha_min: float = .80 + minimum_support_m: float = 1.0 + minimum_chain_m: float = 2.0 + maximum_internal_gap_m: float = 6.0 + anchor_score: float = .65 + smooth_lambda_m4: float = .045 + material_ranking_weight: float = .5 + + +def sample(array, p): + return map_coordinates(array, [p[..., 1], p[..., 0]], order=1, + mode='constant', cval=0) + + +def arclength(p): + return np.r_[0., np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))] + + +def resample(p, step): + d = arclength(p) + keep = np.r_[True, np.diff(d) > 1e-8] + p, d = p[keep], d[keep] + if len(p) < 2: + return p + t = np.linspace(0, d[-1], max(2, int(np.ceil(d[-1]/step))+1)) + return np.c_[np.interp(t, d, p[:, 0]), np.interp(t, d, p[:, 1])] + + +class PhysicalFields: + def __init__(self, rgb, z, alpha, occluder, road, side, cell_m, + policy=AnchorPolicy()): + self.cell = float(cell_m) + self.policy = policy + self.gray = gaussian_filter(cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)[:, :, 0].astype('float32'), .10/self.cell) + self.gx = cv2.Sobel(self.gray, cv2.CV_32F, 1, 0, ksize=3)/(8*self.cell) + self.gy = cv2.Sobel(self.gray, cv2.CV_32F, 0, 1, ksize=3)/(8*self.cell) + self.texture = np.sqrt(gaussian_filter(self.gx**2+self.gy**2, .35/self.cell)) + self.alpha = np.minimum(alpha, np.isfinite(z)).astype('float32') + self.z = np.nan_to_num(z).astype('float32') + self.occluder = maximum_filter(np.asarray(occluder, 'float32'), + size=2*int(np.ceil(policy.occluder_margin_m/self.cell))+1) + self.road = np.asarray(road, 'float32') + self.side = np.asarray(side, 'float32') + self.material = None + self.material_valid = None + + def measure(self, uv, normal): + """Normal points from road to sidewalk. Return reward and reliability.""" + n = np.broadcast_to(normal, uv.shape) + plus = uv+n*self.policy.cross_section_m/self.cell + minus = uv-n*self.policy.cross_section_m/self.cell + near = sample(self.gray, plus)-sample(self.gray, minus) + far = sample(self.gray, uv+n*.8/self.cell)-sample(self.gray, uv-n*.8/self.cell) + # A material boundary persists across scales; a narrow paint ridge does not. + gray_contrast = np.clip(np.minimum(abs(near), abs(far))/18, 0, 1)*(near*far>0) + oriented_edge = np.clip(abs(sample(self.gx, uv)*n[..., 0]+sample(self.gy, uv)*n[..., 1])/55, 0, 1) + dz = sample(self.z, plus)-sample(self.z, minus) + step = np.exp(-((dz-.12)/.12)**2)*(dz>.025)*(dz<.35) + texture = np.clip((sample(self.texture, plus)-sample(self.texture, minus))/20, 0, 1) + score = .65*gray_contrast*oriented_edge+.65*step+.25*oriented_edge+.20*texture + # Broad semantics are a weak context term; no hard mask constraint. + context = .5*(sample(self.side, plus)-sample(self.side, minus)+ + sample(self.road, minus)-sample(self.road, plus)) + score += .10*np.clip(context, -1, 1) + alpha = np.minimum.reduce([sample(self.alpha, uv), sample(self.alpha, plus), sample(self.alpha, minus)]) + blocked = np.maximum.reduce([sample(self.occluder, uv), sample(self.occluder, plus), sample(self.occluder, minus)]) + reliable = (alpha >= self.policy.alpha_min)*(blocked < .25)*(abs(dz) < .45) + return score.astype('float32'), reliable.astype('float32') + + def road_side_interface(self, uv, normal): + """A moved candidate retains road/sidewalk adjacency at its own position. + + A physical edge inside one material (paving, parking paint or a ramp) + cannot inherit the interface identity of a nearby semantic seed. + This is search eligibility; the physical score and its threshold stay + independent and are never increased by semantic agreement. + """ + n = np.broadcast_to(normal, uv.shape) + road_inside = sample(self.road, uv-n*.8/self.cell) > .5 + side_outside = sample(self.side, uv+n*.8/self.cell) > .5 + return road_inside & side_outside + + def ranked_score(self, score, uv, normal): + """Appearance ranks candidates but cannot invalidate physical evidence.""" + if self.material is None: + return score + n = np.broadcast_to(normal, uv.shape) + inside = sample(self.material, uv-n*.8/self.cell) + outside = sample(self.material, uv+n*.8/self.cell) + contrast = inside-outside + if self.material_valid is not None: + contrast *= sample(self.material_valid, uv) >= .5 + return score+self.policy.material_ranking_weight*contrast + + + +def evidence_cost(scores, reliability): + """Reward supported extent, without renormalizing away missing observations.""" + scores, reliability = np.asarray(scores), np.asarray(reliability) + if not scores.size or scores.shape != reliability.shape: + raise ValueError('Matching nonempty evidence arrays required') + return -float(np.mean(np.clip(scores, -1, 1.7)*reliability)) + + +def smooth_anchors(points, confidence, policy=AnchorPolicy(), corners=()): + """Weighted least squares + second derivative penalty; zero weight = missing. + + The positive-weight endpoint requirement prevents unsupported extrapolation. + Interior missing samples are reconstructed by the same variational spline. + Structural corners relax curvature only at their vertex, not over a radius. + """ + p = np.asarray(points, float) + w = np.asarray(confidence, float) + if len(p) < 4 or w.shape != (len(p),) or not(w[0]>0 and w[-1]>0): + raise ValueError('At least four samples and observed terminal anchors required') + ds = max(float(np.median(np.diff(arclength(p)))), policy.sample_m*.5) + D = diags([np.ones(len(p)-2), -2*np.ones(len(p)-2), np.ones(len(p)-2)], + [0, 1, 2], shape=(len(p)-2, len(p)), format='csr') + bend = np.ones(len(p)-2) + for i in corners: + if 0= policy.anchor_score + # Isolated high-contrast pixels do not qualify an anchor segment. + for a,b in mask_runs(confirmed): + if (b-a)*policy.sample_m < policy.minimum_support_m: + confirmed[a:b] = False + if not confirmed.any(): + return [] + first,last = np.flatnonzero(confirmed)[[0,-1]] + allowed = confirmed.copy() + for a,b in mask_runs(~confirmed): + if a>first and b<=last and (b-a)*policy.sample_m <= policy.maximum_internal_gap_m: + allowed[a:b] = True + outputs=[] + for a,b in mask_runs(allowed): + if (b-a)*policy.sample_m < policy.minimum_chain_m: + continue + obs = chosen[a:b];conf = confirmed[a:b].astype(float) + # Preserve supported sharp corners indicated by metre-scale straight arms. + approx = np.asarray(LineString(obs).simplify(.35).coords) + corners=[] + for j in range(1,len(approx)-1): + v=approx[j]-approx[j-1];u=approx[j+1]-approx[j] + if min(np.linalg.norm(v),np.linalg.norm(u))<2: + continue + if v@u < .65*np.linalg.norm(v)*np.linalg.norm(u): + k=int(np.argmin(np.linalg.norm(obs-approx[j],axis=1))) + if conf[k]>0:corners.append(k) + q=smooth_anchors(obs, conf, policy, corners) + if ring and a==0 and b==len(p) and np.linalg.norm(q[0]-q[-1])<.5: + q[-1]=q[0] + if not LineString(q).is_simple: + continue + spans=[] + for i,j in mask_runs(~confirmed[a:b]): + span=q[max(0,i-1):min(len(q),j+1)] + spans.append(dict(status='inferred',method='weighted-minimum-curvature', + pixels=(span/fields.cell).tolist(),length_m=LineString(span).length)) + outputs.append((q/fields.cell,dict(length_m=LineString(q).length, + anchor_fraction=float(conf.mean()),observed_anchor_length_m=float(conf.sum()*policy.sample_m), + mean_offset_m=float(np.mean(offsets[ix[a:b]])),image_edge_support=float(conf.mean()), + inferred_pixel_spans=spans,anchor_policy=asdict(policy), + terminal_extrapolation=False))) + return outputs diff --git a/simulation/urban-plan-research/boundary_competition.py b/simulation/urban-plan-research/boundary_competition.py new file mode 100644 index 00000000..0e7b8ca6 --- /dev/null +++ b/simulation/urban-plan-research/boundary_competition.py @@ -0,0 +1,77 @@ +"""Evidence-backed non-maximum suppression of overlapping curb hypotheses. + +Only complete detached fragments are eligible. Opposite faces, unmatched +extensions and uncertain alternatives survive. This module accepts metric +geometry and observations, never a scene identity or review rectangle. +""" +from dataclasses import dataclass,asdict +from copy import deepcopy +import numpy as np +from shapely.geometry import LineString,Point +from plan_continuity import resample,distances +from gap_evidence import known_material + + +@dataclass(frozen=True) +class CompetitionPolicy: + sample_m: float = .4 + corridor_m: float = 4.0 + min_overlap_fraction: float = .80 + min_parallel_fraction: float = .70 + max_fragment_m: float = 40.0 + min_reference_ratio: float = 1.5 + material_offset_m: float = 1.0 + near_offset_m: float = .25 + contradiction_fraction: float = .45 + separation_fraction: float = .25 + minimum_known_fraction: float = .4 + + +def oriented_samples(raw,step=.4): + p=resample(np.asarray(raw,float),step)[:,:2];t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-9) + return p,t,np.c_[-t[:,1],t[:,0]] + + +def material_summary(p,n,sample,offset=1.): + left=known_material(sample(p+n*offset));right=known_material(sample(p-n*offset)) + split=left*right==-1;known=(left!=0)&(right!=0) + return dict(known_fraction=float(known.mean()),separation_fraction=float(split.mean()), + road_inside_fraction=float(np.mean((left==1)&(right==1))),sidewalk_inside_fraction=float(np.mean((left==-1)&(right==-1))), + signed_side=float(np.mean(np.where(split,left,0)))) + + +def suppress(document,sample,policy=CompetitionPolicy(),diagnostic=False): + fs=[f for f in document['features']if f.get('properties',{}).get('class')=='road_boundary'and f['geometry']['type']=='LineString'] + lines=[LineString(np.asarray(f['geometry']['coordinates'])[:,:2])for f in fs];checks=[];proposals=[] + for i,(f,line)in enumerate(zip(fs,lines)): + if line.is_ring or not 1.policy.corridor_m:continue + stations=np.array([ref.project(Point(v))for v in p]);matched=np.array([ref.interpolate(s).coords[0]for s in stations]) + delta=matched-p;separation=np.linalg.norm(delta,axis=1);overlap=(stations>.15)&(stations.90 + if overlap.mean()=0 else -1 + if np.mean(progress*direction>=-.10)<.9:continue + rn=np.c_[-rt[:,1],rt[:,0]]*direction + a=material_summary(p,n,sample,policy.material_offset_m);b=material_summary(matched,rn,sample,policy.material_offset_m) + opposite=a['signed_side']*b['signed_side']<0 and min(abs(a['signed_side']),abs(b['signed_side']))>.15 + near=material_summary(p,n,sample,policy.near_offset_m) + contradiction=min(max(a['road_inside_fraction'],a['sidewalk_inside_fraction']),max(near['road_inside_fraction'],near['sidewalk_inside_fraction'])) + accepted=(not opposite and a['known_fraction']>=policy.minimum_known_fraction and contradiction>=policy.contradiction_fraction and b['separation_fraction']>=policy.separation_fraction and b['separation_fraction']>=a['separation_fraction']+.20) + check=dict(fragment_id=f['id'],reference_id=g['id'],length_m=line.length,reference_length_m=ref.length,overlap_fraction=float(overlap.mean()),parallel_fraction=float(parallel.mean()),median_distance_m=float(np.median(separation)),fragment=a,near_fragment=near,reference=b,opposite_faces=bool(opposite),accepted=bool(accepted),reason='contradicted-parallel-alternative'if accepted else'opposite-faces'if opposite else'insufficient-material-separation') + checks.append(check) + if accepted:proposals.append((contradiction+b['separation_fraction'],i,j)) + removed=set();winners=set() + for _,i,j in sorted(proposals,reverse=True): + if i in winners or j in removed:continue + removed.add(i);winners.add(j) + ids={fs[i]['id']for i in removed};out=deepcopy(document) + if not diagnostic:out['features']=[f for f in out['features']if f['id']not in ids] + audit=dict(policy=asdict(policy),checks=checks,removed_ids=sorted(ids),removed_m=sum(lines[i].length for i in removed),diagnostic_only=diagnostic,quarantined=[deepcopy(fs[i])for i in sorted(removed)]) + return out,audit diff --git a/simulation/urban-plan-research/catalog_pass/README.rst b/simulation/urban-plan-research/catalog_pass/README.rst new file mode 100644 index 00000000..941bb50b --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/README.rst @@ -0,0 +1,80 @@ +Gaussian marking catalogue and continuous observed stripes +========================================================= + +Offline continuation of search-pass-20261013. All image processing, tests and +renders run on Worker006. The operator Mac only edits sources and copies/views +evidence. No point clouds, colliders, manual processing ROIs, address-specific +parameters, live deployment or rover commands. + +Method +------ +* Search every native Gaussian ground-render image for compact bicycle paint + components and longer zigzag components. Keep calibrated road, vehicle and + alpha gates. Preserve small negative spaces in the component geometry. +* Fit the attributed bicycle vector artwork using OpenCV raster overlap and + bounded SciPy Powell registration. SVG vertical is road-longitudinal, as + with the existing arrow templates. Require wheel/frame negative topology, + agreement with nearby lane direction and paint support in geometrically + selected image mosaics under the two-view or stronger primary-view rules below. + Lane context is measured as the union length of projected stripe intervals, + so one continuous stripe and its fragments supply the same evidence and + duplicate observations cannot inflate the length. Both longitudinal/lateral artwork orientations are + considered: a real bicycle symbol can be wider across the lane than along it. Artwork is reused, not traced from worn paint. +* Propose repeating zigzag legs with scikit-image skeletonize, graph paths, + OpenCV Douglas-Peucker simplification and least-squares regularization. + Repetition alone is never sufficient to add an object. Two complete + mosaics use the usual checks. Where a second rendered view is absent or + partial, a stricter full primary view, tighter pattern fit and agreement + with every available secondary portion are required. These renders are + correlated samples of one Gaussian scene, not independent physical scans. +* Reuse the hash-pinned full-frame line proposals of the previous pass. A long + continuous painted stripe need not have its physical end inside the same + image. Emit only measured, two-view-supported portions, explicitly labelled + as observation-window-bounded, not physical endpoints. Subtract occupied + longitudinal intervals to avoid thin parallel duplicate slivers. +* Preserve every previous feature exactly. This addition-only pass cannot + repair old road contours, facade topology, old symbols or missing dashes. + Qualified changes are replayable transactions with source/evidence pins. +* Geometry chooses two covering frames independently at each object pixel. + The complete object need not fit inside two individual frame rectangles. + Paint coverage must be complete in the primary rank; road/alpha/vehicle validity + is measured on the painted shape instead of a surrounding convex hull. + +Execution +--------- +The replay helpers require the canonical checkout, official recorded-job queue, +accepted Worker caches, pinned container image and source bundle. Containers +have no network, a read-only root, 4 CPUs, 20 GiB RAM and bounded runtime. +Pinned Linux wheels are SHA-verified and extracted into disposable container +tmpfs with library execution enabled. No packages are installed on the host. +The source export contains those exact wheels and their bundled licences. +The review-only font remains in the private qualification cache. Extraction +may be reused only if every candidate-local module in its transitive import +closure, the container image and the accepted baseline match their receipt. +Classification and image rendering use the final frozen bundle in every scene. + +Limits +------ +Two renders of the same Gaussian reconstruction are correlated evidence. +More raster pixels do not establish higher physical accuracy. Cached road and +vehicle masks can still reject real paint. Existing missing proposal classes +and scene coverage remain limitations. Known-scene regression is not unseen-map +generalization. No full detection recall, absolute accuracy or legal GOST +compliance is claimed. GOST associations from earlier passes remain unchanged. + +Reuse and attribution +--------------------- +OpenCV, SciPy, Shapely and scikit-image are used as existing components. +https://scikit-image.org/docs/0.24.x/api/skimage.morphology.html#skimage.morphology.skeletonize + +Bicycle artwork by Major Alexey, CC BY-SA 4.0. Adaptation: cubic-curve sampling, +even-odd polygon construction, coordinate normalization and metric registration. +https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg +https://creativecommons.org/licenses/by-sa/4.0/ +Original SVG SHA-256: +53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59 + +Existing arrow artwork by the same author under the same licence: +https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg + +Qualified results are recorded in verification.json and visual-review.json. diff --git a/simulation/urban-plan-research/catalog_pass/audit_catalog.py b/simulation/urban-plan-research/catalog_pass/audit_catalog.py new file mode 100644 index 00000000..b9904ac0 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/audit_catalog.py @@ -0,0 +1,34 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +from catalog_rules import POLICY,VERSION,accept_bicycle,accept_zigzag +from discovery_rules import uncovered +old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/catalog-rows.json').read_text());current={f['id']:f for f in old['features']} +def poly(f):return shapely.force_2d(shape(f['geometry'])) +existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking']) +checks=dict(transaction_replay=True,only_paint_added=True,no_new_neighbor_overlap=True,evidence_passes=True) +for r in rows: + checks['transaction_replay']&=not r['before']and not r['source_ids']and r['output_ids']==[f['id']for f in r['after']]and all(f['id']not in current for f in r['after']) + checks['only_paint_added']&=all(f['properties']['class']=='road_marking'and f['properties']['method']==VERSION for f in r['after']) + okay=len(set(r['source_tiles']))>=1;ev=r['evidence'] + if r['kind']=='preset-bicycle': + okay&=r['lane_context']['passed']and r['lane_context']['supporting_length_m']>=POLICY['bicycle_context_length_m']and r['lane_context']['length_measure']=='union-of-longitudinal-intervals'and r['template_fit_score']>=POLICY['bicycle_fit_score']and accept_bicycle(ev,r['template_fit_score'])==r['evidence_mode'] + elif r['kind']=='regularized-zigzag': + fit=dict(legs=r['leg_count'],fit_residual_m=r['fit_residual_m'],proposal_recall=r['proposal_recall']) + okay&=r['leg_count']>=POLICY['min_zigzag_legs']and len(ev['legs'])==r['leg_count']and accept_zigzag(ev['whole'],ev['legs'],fit)==r['evidence_mode'] + elif r['kind']=='observed-continuous-section': + okay&=len(set(r['source_tiles']))>=2 + okay&=len(ev['profile'])==2 and all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']and e['contrast']>=POLICY['min_line_contrast']for e in ev['profile']) + okay&=len(ev['section'])==2 and all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']for e in ev['section']) + parent=shape(ev['parent_geometry']);okay&=all(poly(f).difference(parent.buffer(.001)).area<.001 for f in r['after'])and r['endpoint_authority']=='observed_window_not_physical_end' + else:okay=False + checks['evidence_passes']&=okay + for f in r['after']: + checks['no_new_neighbor_overlap']&=uncovered(poly(f),existing);existing=shapely.union_all([existing,poly(f)]);current[f['id']]=f +features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features']);checks['all_baseline_objects_unchanged']=all(features.get(f['id'])==f for f in old['features']);checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']) +checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes() +report=json.loads(Path('/out/catalog-report.json').read_text());checks['same_policy']=new['catalog_refinement']==VERSION and report['policy']==POLICY;checks['every_operation_counted']=report['changed_segments']==len(rows)and report['added_objects']==sum(len(r['after'])for r in rows) +checks['proposal_cache_pinned']=report['proposal_cache_sha256']==hashlib.sha256(Path('/fullplan/search-proposals.json').read_bytes()).hexdigest() +checks['new_full_frame_proposals_pinned']=report['catalog_proposals_sha256']==hashlib.sha256(Path('/out/catalog-proposals.json').read_bytes()).hexdigest() +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/catalog-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/catalog_pass/bicycle_artwork.py b/simulation/urban-plan-research/catalog_pass/bicycle_artwork.py new file mode 100644 index 00000000..ec56bab8 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/bicycle_artwork.py @@ -0,0 +1,7 @@ +"""Bicycle artwork by Major Alexey, CC BY-SA 4.0. +Source: https://commons.wikimedia.org/wiki/File:1.23.3_Russian_road_marking.svg +License: https://creativecommons.org/licenses/by-sa/4.0/ +Adaptation: curve sampling, even-odd geometry, metric scaling. +""" +SOURCE_SHA256="53f95d4e93d98c2d32a18d407e3189c721e252e5e7912365afdfda6313a78c59" +PATH='M140.5,170c-1.2,3.8-2.5,6.6-3,9.6c-0.2,1,1.4,2.9,2.5,3.5c14.6,7.8,24,19.6,27.8,35.7\n\tc7,30.2-13.5,60-44.2,64.6c-30.4,4.5-58.5-17.5-61.2-48c-3-33.9,25.7-61.7,59.6-57.7c1,0.1,2.1,0.1,3.5,0.2\n\tc3.1-10.2,6.1-20.4,9.3-30.5c2.1-6.7,4.5-13.4,7.1-19.9c2.8-7,8-11.2,15.8-11.4c6.6-0.2,13.3,0,20.2,0c0,3,0,6.3,0,10.2\n\tc-2.5,0-4.9,0-7.4,0c-1.6,0-3.2,0-4.8,0c-11.2,0.1-13,1.5-16,12.1c-0.7,2.4-1.3,4.9-2.1,7.8c1.3,0.1,2.4,0.3,3.6,0.3\n\tc28.5,0,57.1,0,85.6,0.1c2.5,0,4-0.6,4.6-3.2c0.5-2.2,1.5-4.3,2.4-6.9c-4.9-1.1-9.7-2.1-14.4-3.2c-2.5-0.6-4.9-1.2-7.2-2.2\n\tc-0.9-0.4-1.7-2-1.7-3c0-0.7,1.6-1.9,2.4-1.9c15-0.1,30-0.1,45.3-0.1c0,3.5,0,6.7,0,10.7c-3.1,0-6.3-0.3-9.3,0.1\n\tc-1.3,0.2-3,1.4-3.7,2.6c-2.6,4.5-2.6,8.9,0,13.8c4,7.4,7.1,15.2,10.4,22.9c1,2.5,2.1,2.9,4.8,2.3c30.5-7.7,60,10.6,66.2,41.2\n\tc7,33.8-20.8,65.7-55.2,63.5c-23.7-1.5-42.4-16.5-48.8-39.3c-0.7-2.4-1.5-3.3-4-3.2c-4.7,0.2-9.4-0.2-14,0.1\n\tc-7.6,0.5-13.4-2.3-18.3-7.9c-10.7-12.4-21.5-24.8-32.4-37C156.5,187.1,148.7,178.9,140.5,170z M121.5,190.5\n\tc-21-3.5-41.8,11.4-45.8,32c-4.2,21.9,9.7,43.3,31.4,47.9c21.6,4.6,43.3-9,48.3-30.3c4.5-19-6.7-41.9-22.6-46\n\tc-0.2,0.5-0.4,1-0.5,1.5c-3.7,11.6-7.4,23.3-11.2,34.9c-1,3.1-2.8,5.6-6.7,4.7c-3.3-0.8-4.9-3.9-4.1-8c0.6-3,1.5-5.9,2.4-8.8\n\tC115.6,209.3,118.5,200.1,121.5,190.5z M245.4,240.6c1,12.1,15.2,25.6,30.3,28.9c17.4,3.8,35.6-4.5,44.4-20.4\n\tc8.6-15.6,5.9-35.2-6.7-47.9c-10.9-11-29.9-15.8-40.6-10c2.3,5.1,4.6,10.1,6.9,15.2c3.8,8.5,7.7,17,11.3,25.5c2.2,5.2,0.4,8-5.1,8.4\n\tc-2.8,0.2-5.6,0.2-8.4,0.2C266.7,240.6,256.1,240.6,245.4,240.6z M209.3,227.9c8.8-23.7,17.4-46.7,26-69.8c-30.2,0-59.8,0-90.2,0\n\tC166.8,181.6,187.8,204.5,209.3,227.9z M261.9,196c-11.5,6.8-20,22.8-18,33.3c10.8,0,21.6,0,33,0C271.8,217.9,266.9,207.1,261.9,196\n\tz M230.6,229.1c0.9-19.5,9.5-34.4,25.9-45.2c-3.2-7-6.3-13.9-9.8-21.7c-8.7,22.9-17.1,44.7-25.5,66.8\n\tC224.6,229.1,227.5,229.1,230.6,229.1z' diff --git a/simulation/urban-plan-research/catalog_pass/bundle.json b/simulation/urban-plan-research/catalog_pass/bundle.json new file mode 100644 index 00000000..dce08d6e --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/bundle.json @@ -0,0 +1,206 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_catalog.py": "catalog_pass/audit_catalog.py", + "audit_completion.py": "completion_pass/audit_completion.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_corridor.py": "corridor_pass/audit_corridor.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_search.py": "search_pass/audit_search.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "bicycle_artwork.py": "catalog_pass/bicycle_artwork.py", + "catalog_context.py": "catalog_pass/catalog_context.py", + "catalog_dependencies.py": "catalog_pass/catalog_dependencies.py", + "catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py", + "catalog_evidence.py": "catalog_pass/catalog_evidence.py", + "catalog_rules.py": "catalog_pass/catalog_rules.py", + "catalog_templates.py": "catalog_pass/catalog_templates.py", + "catalog_zigzag.py": "catalog_pass/catalog_zigzag.py", + "completion_profiles.py": "completion_pass/completion_profiles.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "coordinate_cache.py": "orthophoto/coordinate_cache.py", + "corridor_profiles.py": "search_pass/corridor_profiles.py", + "coverage_evidence.py": "corridor_pass/coverage_evidence.py", + "coverage_plan.py": "corridor_pass/coverage_plan.py", + "diagnose_corridor.py": "corridor_pass/diagnose_corridor.py", + "diagnose_coverage.py": "corridor_pass/diagnose_coverage.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_catalog.py": "catalog_pass/extract_catalog.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "extract_search.py": "search_pass/extract_search.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "inspect_bicycles.py": "catalog_pass/inspect_bicycles.py", + "inspect_catalog.py": "catalog_pass/inspect_catalog.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "mapping.py": "corridor_pass/mapping.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "ortho_terrain.py": "orthophoto/ortho_terrain.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_catalog.py": "catalog_pass/refine_catalog.py", + "refine_completion.py": "completion_pass/refine_completion.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_corridor.py": "corridor_pass/refine_corridor.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_search.py": "search_pass/refine_search.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_catalog.py": "catalog_pass/render_catalog.py", + "render_completion.py": "completion_pass/render_completion.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_corridor.py": "corridor_pass/render_corridor.py", + "render_coverage.py": "corridor_pass/render_coverage.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "catalog_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_search.py": "search_pass/render_search.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "corridor_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "search_rules.py": "search_pass/search_rules.py", + "search_views.py": "search_pass/search_views.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_catalog.py": "catalog_pass/test_catalog.py", + "test_completion.py": "completion_pass/test_completion.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_corridor.py": "corridor_pass/test_corridor.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_search.py": "search_pass/test_search.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py", + "validation.py": "corridor_pass/validation.py" + }, + "reference_qualification": "catalog-pass-20261014", + "source_snapshot": "c0fe1a6d698212c9d404", + "source_sha256": { + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2", + "audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f", + "catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80", + "catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca", + "catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a", + "catalog_evidence.py": "6eeb6f18e9dc2fef6f490ba5a09eba64c2021c16dbdf0594921ed5a563d23868", + "catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb", + "catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092", + "catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f", + "completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4", + "corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672", + "coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497", + "coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda", + "diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6", + "diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb", + "inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb", + "refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b", + "render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f", + "render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41", + "search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4", + "test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e", + "validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c" + }, + "external_dependencies": { + "packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759", + "scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660", + "imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf", + "networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", + "lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc", + "tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/catalog_pass/catalog_context.py b/simulation/urban-plan-research/catalog_pass/catalog_context.py new file mode 100644 index 00000000..2053cebb --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_context.py @@ -0,0 +1,17 @@ +"""Lane evidence measured in metres, independent of proposal fragmentation.""" +import numpy as np +from catalog_rules import POLICY + +def bicycle_context(p,parameters,records): + u=np.array([np.cos(parameters[2]),np.sin(parameters[2])]);origin=np.asarray(parameters[:2]);support=[];intervals=[] + for r in records: + alignment=abs(r['axis']@u) + if r['W']>.35 or not(.3=POLICY['bicycle_context_length_m']),supporting_strips=len(support),supporting_length_m=float(length),length_measure='union-of-longitudinal-intervals',source_tiles=sorted(set(r['source_tile']for r in support))) diff --git a/simulation/urban-plan-research/catalog_pass/catalog_dependencies.py b/simulation/urban-plan-research/catalog_pass/catalog_dependencies.py new file mode 100644 index 00000000..ec0e8068 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_dependencies.py @@ -0,0 +1,12 @@ +"""Load pinned Linux wheels only into the disposable qualification container.""" +from pathlib import Path +import sys,zipfile,hashlib,json +from catalog_dependency_pins import PINS +root=Path('/candidate');target=Path('/tmp/catalog-dependencies');target.mkdir(exist_ok=True) +for pin in PINS: + path=root/pin['file'];assert hashlib.sha256(path.read_bytes()).hexdigest()==pin['sha256'] + with zipfile.ZipFile(path)as z: + assert all(not Path(n).is_absolute()and '..'not in Path(n).parts for n in z.namelist()) + z.extractall(target) +sys.path.insert(0,str(target)) +Path('/out/catalog-dependencies.json').write_text(json.dumps(PINS,indent=2)) diff --git a/simulation/urban-plan-research/catalog_pass/catalog_dependency_pins.py b/simulation/urban-plan-research/catalog_pass/catalog_dependency_pins.py new file mode 100644 index 00000000..a2b8be7c --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_dependency_pins.py @@ -0,0 +1 @@ +PINS=[{'name': 'scikit-image', 'version': '0.24.0', 'file': 'scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl', 'sha256': '8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660', 'url': 'https://files.pythonhosted.org/packages/2c/24/4bcd94046b409ac4d63e2f92e46481f95f5006a43e68f6ab2b24f5d70ab4/scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl', 'license': 'Files: * Copyright: 2009-2022 the scikit-image team License: BSD-3-Clause Files: doc/source/themes/scikit-image/layout.html Copyright: 2007-2010 the Sphinx team License: BSD-3-Clause Files: skimage/feature/_canny.py skimage/filters/edges.py skimage/filters/_rank_order.py skimage/morphology/_skeletonize.py skimage/morphology/tests/test_watershed.py skimage/morphology/watershed.py skimage/segmentation/heap_general.pxi skimage/segmentation/heap_watershed.pxi skimage/segmentation/_watershed.py skimage/segmentation/_watershed_cy.pyx Copyright: 2003-2009 Massachusetts Institute of Technology 2009-2011 Broad Institute 2003 Lee Kamentsky 2003-2005 Peter J. Verveer License: BSD-3-Clause Files: skimage/filters/thresholding.py skimage/graph/_mcp.pyx skimage/graph/heap.pyx Copyright: 2009-2015 Board of Regents of the University of Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck Institute of Molecular Cell Biology and Genetics 2009 Zachary Pincus 2009 Almar Klein License: BSD-2-Clause File: skimage/morphology/grayreconstruct.py skimage/morphology/tests/test_reconstruction.py Copyright: 2003-2009 Massachusetts Institute of Technology 2009-2011 Broad Institute 2003 Lee Kamentsky License: BSD-3-Clause File: skimage/morphology/_grayreconstruct.pyx Copyright: 2003-2009 Massachusetts Institute of Technology 2009-2011 Broad Institute 2003 Lee Kamentsky 2022 Gregory Lee (added a 64-bit integer variant for large images) License: BSD-3-Clause File: skimage/segmentation/_expand_labels.py Copyright: 2020 Broad Institute 2020 CellProfiler team License: BSD-3-Clause File: skimage/exposure/_adapthist.py Copyright: 1994 Karel Zuiderveld License: BSD-3-Clause Function: skimage/morphology/_skeletonize_cy.pyx:_skeletonize_loop Copyright: 2003-2009 Massachusetts Institute of Technology 2009-2011 Broad Institute 2003 Lee Kamentsky License: BSD-3-Clause Function: skimage/_shared/version_requirements.py:_check_version Copyright: 2013 The IPython Development Team License: BSD-3-Clause Function: skimage/_shared/version_requirements.py:is_installed Copyright: 2009-2011 Pierre Raybaut License: MIT File: skimage/feature/_fisher_vector.py Copyright: 2014 2014 Dan Oneata License: MIT File: skimage/_vendored/numpy_lookfor.py Copyright: 2005-2023, NumPy Developers License: BSD-3-Clause File: tools/emscripten/pytest_scikit_image_pyodide.js Copyright: 2007-2024 The scikit-learn developers License: BSD-3-Clause File: skimage/transform/_thin_plate_splines.py Copyright: 2007 Zachary Pincus License: BSD-3-Clause License: BSD-2-Clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS\'\' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. License: BSD-3-Clause Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. . THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS\'\' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. License: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.'}, {'name': 'lazy_loader', 'version': '0.4', 'file': 'lazy_loader-0.4-py3-none-any.whl', 'sha256': '342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc', 'url': 'https://files.pythonhosted.org/packages/83/60/d497a310bde3f01cb805196ac61b7ad6dc5dcf8dce66634dc34364b20b4f/lazy_loader-0.4-py3-none-any.whl', 'license': 'BSD 3-Clause License Copyright (c) 2022--2023, Scientific Python project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. '}, {'name': 'networkx', 'version': '3.4.2', 'file': 'networkx-3.4.2-py3-none-any.whl', 'sha256': 'df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f', 'url': 'https://files.pythonhosted.org/packages/b9/54/dd730b32ea14ea797530a4479b2ed46a6fb250f682a9cfb997e968bf0261/networkx-3.4.2-py3-none-any.whl', 'license': None}, {'name': 'imageio', 'version': '2.36.1', 'file': 'imageio-2.36.1-py3-none-any.whl', 'sha256': '20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf', 'url': 'https://files.pythonhosted.org/packages/5c/f9/f78e7f5ac8077c481bf6b43b8bc736605363034b3d5eb3ce8eb79f53f5f1/imageio-2.36.1-py3-none-any.whl', 'license': 'BSD-2-Clause'}, {'name': 'tifffile', 'version': '2024.9.20', 'file': 'tifffile-2024.9.20-py3-none-any.whl', 'sha256': 'c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd', 'url': 'https://files.pythonhosted.org/packages/50/0a/435d5d7ec64d1c8b422ac9ebe42d2f3b2ac0b3f8a56f5c04dd0f3b7ba83c/tifffile-2024.9.20-py3-none-any.whl', 'license': 'BSD'}, {'name': 'packaging', 'version': '24.2', 'file': 'packaging-24.2-py3-none-any.whl', 'sha256': '09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759', 'url': 'https://files.pythonhosted.org/packages/88/ef/eb23f262cca3c0c4eb7ab1933c3b1f03d021f2c48f54763065b6f0e321be/packaging-24.2-py3-none-any.whl', 'license': None}] diff --git a/simulation/urban-plan-research/catalog_pass/catalog_evidence.py b/simulation/urban-plan-research/catalog_pass/catalog_evidence.py new file mode 100644 index 00000000..f6bcbe47 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_evidence.py @@ -0,0 +1,36 @@ +"""Two geometry-selected image mosaics for every point of a finite object. + +No demand that both complete camera rectangles contain a long polygon's bbox. +Unknown paint pixels remain unknown; different ranks never use the same tile. +""" +import numpy as np,cv2,shapely +from fit_scene import project +from layer_common import sample +from row_evidence import choose_owners +from discovery_rules import glyph_score + +def mosaic_views(p,views,kind=None,parameters=None): + lo=np.asarray(p.bounds[:2])-1.;hi=np.asarray(p.bounds[2:])+1.;cell=.04 + xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell);x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()] + distance=np.linalg.norm(points[:,None,:]-views.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool) + for i,tile in enumerate(views.tiles): + uv=project(points,views.geometry(tile['id']));coverage[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180) + owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1]) + for rank in [0,1]: + colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={} + for i in np.unique(owners[:,rank]): + if i<0:continue + select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5 + def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]) + colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points[select],views.low,views.high)==1);covered[select]=True + if target[select].any():names.add(name);source_counts[name]=int(target[select].sum()) + score=glyph_score(colors.reshape(len(yy),len(xx),3),allowed.reshape(len(yy),len(xx)),points,p,kind=None,parameters=None) + rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV) + bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(31,31))) + paint=((gray.astype(float)-bg>15)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))) + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0 + known=target&allowed&covered + score['observed_support']=float(near[known].mean())if known.any()else 0. + score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank) + ev.append(score) + return ev,sorted(names) diff --git a/simulation/urban-plan-research/catalog_pass/catalog_rules.py b/simulation/urban-plan-research/catalog_pass/catalog_rules.py new file mode 100644 index 00000000..7755c5c2 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_rules.py @@ -0,0 +1,37 @@ +"""One metric policy shared by every scene; observation windows are explicit.""" +VERSION='marking-catalog-v1' +POLICY=dict(bicycle_fit_score=.65,bicycle_fit_support=.78,bicycle_fit_recall=.75, + bicycle_view_support=.78,bicycle_view_recall=.75,bicycle_view_valid=.97, + bicycle_negative_paint=.15,min_line_length_m=3.,min_line_valid=.98, + min_line_support=.93,min_line_contrast=22.,max_line_width_m=.30, + min_zigzag_legs=3,max_zigzag_joint_m=.30,max_zigzag_angle_error_deg=10., + min_zigzag_leg_support=.85,min_zigzag_valid=.97, + strong_bicycle_fit=.72,strong_bicycle_support=.93,strong_bicycle_recall=.90, + strong_negative_paint=.12,strong_zigzag_support=.97,strong_zigzag_leg_support=.95, + strong_zigzag_min_legs=4,strong_zigzag_max_residual_m=.10, + strong_zigzag_proposal_recall=.85,additional_view_min_valid=.95, + bicycle_context_length_m=6.,bicycle_context_radius_m=10.,bicycle_context_angle_deg=15., + manual_rois=[],point_cloud_input=False) + +def two_supported(ev,valid,support,recall=0.,negative=1.): + return len(ev)==2 and all(e['paint_coverage']==1. and e['paint_valid']>=valid and e['support']>=support and e['recall']>=recall and e['negative_paint']<=negative for e in ev) + +def additional_agrees(e,support): + coverage=e['paint_coverage'] + return coverage==0. or(e['paint_valid']/coverage>=POLICY['additional_view_min_valid']and e['observed_support']>=support and e['negative_paint']<=POLICY['strong_negative_paint']) + +def accept_bicycle(ev,score): + if two_supported(ev,POLICY['bicycle_view_valid'],POLICY['bicycle_view_support'],POLICY['bicycle_view_recall'],POLICY['bicycle_negative_paint']):return 'two-mosaics' + if len(ev)!=2 or score=POLICY['bicycle_view_valid']and e['support']>=POLICY['strong_bicycle_support']and e['recall']>=POLICY['strong_bicycle_recall']and e['negative_paint']<=POLICY['strong_negative_paint']and additional_agrees(ev[1],POLICY['strong_bicycle_support']):return 'strong-complete-view-plus-available-consistency' + return None + +def accept_zigzag(ev,legs,fit): + if two_supported(ev,POLICY['min_zigzag_valid'],POLICY['min_zigzag_leg_support'])and all(two_supported(ee,POLICY['min_zigzag_valid'],POLICY['min_zigzag_leg_support'])for ee in legs):return 'two-mosaics' + if len(ev)!=2 or fit['legs']POLICY['strong_zigzag_max_residual_m']or fit['proposal_recall']=POLICY['min_zigzag_valid']and e['support']>=support and e['negative_paint']<=POLICY['strong_negative_paint']and additional_agrees(ee[1],support)):return None + return 'strong-complete-view-plus-available-consistency' diff --git a/simulation/urban-plan-research/catalog_pass/catalog_templates.py b/simulation/urban-plan-research/catalog_pass/catalog_templates.py new file mode 100644 index 00000000..4fbf7f7c --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_templates.py @@ -0,0 +1,79 @@ +"""Attributed bicycle artwork and OpenCV/SciPy template registration. + +No map identity, review crop or world-coordinate exceptions are inputs. +""" +import re +import numpy as np, cv2, shapely +from shapely.geometry import Polygon +from shapely.affinity import affine_transform +from scipy.optimize import minimize +from bicycle_artwork import PATH + +def svg_rings(path): + tokens=re.findall(r'[MLHVClmhvcZz]|[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?',path) + rings=[];points=[];p=np.zeros(2);start=p.copy();i=0;command=None + while i5 and abs(x[5])>.001 else p + +def fit_bicycle(p,all_hypotheses=False): + if p.is_empty or p.area<.10:return None + rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6) + if not(1..015 for h in holes)<2:return None + cell=.02;lo=np.asarray(p.bounds[:2])-.4;hi=np.asarray(p.bounds[2:])+.4;size=np.ceil((hi-lo)/cell).astype(int)[::-1] + def draw(poly): + m=np.zeros(size,np.uint8) + for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])): + if q.is_empty or q.geom_type!='Polygon':continue + cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1) + for h in q.interiors:cv2.fillPoly(m,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0) + return m + target=draw(p);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5));near=cv2.dilate(target,kernel);best=None + def quality(x): + m=draw(bicycle(x,fast=True));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou + hypotheses=[] + for flip in [0,np.pi,np.pi/2,3*np.pi/2]: + along,across=(L,W)if flip in [0,np.pi]else(W,L) + a=ang+flip;u=np.array([np.cos(a),np.sin(a)]);base=origin-u*along/2;x=np.r_[base,a,along,across,0.] + bounds=[(base[0]-.25,base[0]+.25),(base[1]-.25,base[1]+.25),(a-.3,a+.3),(along*.85,along*1.15),(across*.75,across*1.25),(-.02,.025)] + opt=minimize(lambda x:1-quality(x)[2],x,method='Powell',bounds=bounds,options=dict(maxiter=35,xtol=.002,ftol=.002));q=quality(opt.x) + hypothesis=dict(polygon=bicycle(opt.x),score=q[2],support=q[0],recall=q[1],parameters=opt.x.tolist());hypotheses.append(hypothesis) + if best is None or q[2]>best['score']:best=hypothesis + return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else best diff --git a/simulation/urban-plan-research/catalog_pass/catalog_zigzag.py b/simulation/urban-plan-research/catalog_pass/catalog_zigzag.py new file mode 100644 index 00000000..2fa253cc --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/catalog_zigzag.py @@ -0,0 +1,54 @@ +"""Raster skeleton + Douglas-Peucker + repeated-leg least-squares model. + +The skeleton is only a proposal. Two original Gaussian render footprints must +support every regularized leg before anything is added to the map. +""" +import numpy as np,cv2,shapely +from shapely.geometry import Polygon,LineString +from scipy.sparse import coo_matrix +from scipy.sparse.csgraph import dijkstra +import catalog_dependencies +from skimage.morphology import skeletonize + +def fit_zigzag(p): + if p.is_empty or p.geom_type!='Polygon':return None + rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True) + if not(31200000:return None + mask=np.zeros(size,np.uint8) + cv2.fillPoly(mask,[np.rint((np.asarray(p.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1) + for h in p.interiors:cv2.fillPoly(mask,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0) + sk=skeletonize(mask>0);yy,xx=np.nonzero(sk) + if len(xx)<50:return None + lookup=np.full(mask.shape,-1,int);lookup[yy,xx]=np.arange(len(xx));aa=[];bb=[];dd=[] + for dy,dx in [(0,1),(1,0),(1,1),(1,-1)]: + y=yy+dy;x=xx+dx;valid=(y>=0)&(y=0)&(x=0;a=ids[ok];b=other[ok] + aa.extend(a);bb.extend(b);dd.extend([np.hypot(dx,dy)]*len(a));aa.extend(b);bb.extend(a);dd.extend([np.hypot(dx,dy)]*len(a)) + graph=coo_matrix((dd,(aa,bb)),shape=(len(xx),len(xx))).tocsr();degree=np.diff(graph.indptr);ends=np.flatnonzero(degree==1) + if not 2<=len(ends)<=8:return None + dist,pred=dijkstra(graph,indices=ends,return_predecessors=True);dist[~np.isfinite(dist)]=-1;k,j=np.unravel_index(np.argmax(dist[:,ends]),(len(ends),len(ends)));a=int(ends[k]);b=int(ends[j]);ids=[b] + while ids[-1]!=a: + node=int(pred[k,ids[-1]]) + if node<0:return None + ids.append(node) + xy=np.c_[xx[ids],yy[ids]]*cell+lo;curve=LineString(xy) + width=p.area/max(curve.length,1e-6) + if not .0455.5 or np.std(length)/np.mean(length)>.25:continue + u=legs/length[:,None];turn=np.arctan2(u[:-1,0]*u[1:,1]-u[:-1,1]*u[1:,0],(u[:-1]*u[1:]).sum(1)) + if np.any(turn[:-1]*turn[1:]>=0)or np.min(abs(turn))np.deg2rad(150)or np.std(abs(turn))>np.deg2rad(10):continue + idx=np.arange(len(q));X=np.c_[idx,(-1.)**idx,np.ones(len(q))];coef=np.linalg.lstsq(X,q,rcond=None)[0];fitted=X@coef;axis,amp=coef[:2] + if abs(axis@amp)/max(np.linalg.norm(axis)*np.linalg.norm(amp),1e-9)>.25:continue + residual=np.linalg.norm(fitted-q,axis=1) + if residual.max()>.16:continue + line=LineString(fitted);poly=line.buffer(width/2,cap_style=2,join_style=2) + score=p.intersection(poly.buffer(.04)).area/max(p.area,1e-6) + if score<.60:continue + if best is None or len(q)>len(best['vertices']):best=dict(polygon=poly,vertices=fitted.tolist(),width_m=float(width),legs=len(q)-1,fit_residual_m=float(residual.max()),proposal_recall=float(score)) + return best diff --git a/simulation/urban-plan-research/catalog_pass/children_warning.svg b/simulation/urban-plan-research/catalog_pass/children_warning.svg new file mode 100644 index 00000000..80165f2d --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/children_warning.svg @@ -0,0 +1,15 @@ + + +1.23 Дети + + + + + + + + + + + + \ No newline at end of file diff --git a/simulation/urban-plan-research/catalog_pass/extract_catalog.py b/simulation/urban-plan-research/catalog_pass/extract_catalog.py new file mode 100644 index 00000000..9b1875a4 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/extract_catalog.py @@ -0,0 +1,54 @@ +"""Native full-frame paint proposals for compact bicycles and long zigzags.""" +from pathlib import Path +import json,time,hashlib +import numpy as np,cv2,shapely +from shapely.geometry import Polygon,mapping,shape +from layer_common import O,S,sample,parts +from fit_scene import world,project +from search_views import SearchViews +cv2.setNumThreads(3);start=time.monotonic() +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None) +def eligible(p): + if p.is_empty or p.area<.08:return False + rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);L,W=sorted(rect[1],reverse=True) + if W<=0:return False + fill=p.area/(L*W) + return (1..65)).astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0 + gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2) + ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel);binary=((ridge>12)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))&allowed).astype('uint8') + cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[] + if hier is not None: + for i,c in enumerate(cc): + if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.008:continue + holes=[];j=hier[0,i,2] + while j>=0: + if cv2.contourArea(cc[j])*mpp*mpp>.003:holes.append(xy(cc[j][:,0])) + j=hier[0,j,0] + components.extend(parts(shapely.make_valid(Polygon(xy(c[:,0]),holes)))) + union=shapely.union_all(components);candidates=list(components) + for radius in [.08,.16]: + for region in parts(union.buffer(radius).buffer(-radius)): + if eligible(region):candidates.append(union.intersection(region.buffer(.015))) + accepted=[] + for p in candidates: + if not eligible(p):continue + if any(p.intersection(q).area/min(p.area,q.area)>.85 for q in accepted):continue + accepted.append(p);glyphs.append(dict(geometry=mapping(p),source_tile=name)) + reports.append(dict(tile=name,proposal_pixels=size,candidates=len(accepted)));print('TILE',name,'CANDIDATES',len(accepted),flush=True) +candidates=[];ordered=sorted([(r,shape(r['geometry']))for r in glyphs],key=lambda v:-v[1].area) +geometries=[p for _,p in ordered];tree=shapely.STRtree(geometries);accepted=set() +for i,(r,p) in enumerate(ordered): + if any(j in accepted and p.intersection(geometries[j]).area/min(p.area,geometries[j].area)>.85 for j in tree.query(p,predicate='intersects')):continue + candidates.append(r);accepted.add(i) +(O/'catalog-proposals.json').write_text(json.dumps(dict(glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),source='all native Gaussian frames; class-specific size ranges; no manual regions'),allow_nan=False)) +print('PROPOSALS',len(candidates),'SECONDS',time.monotonic()-start,flush=True) diff --git a/simulation/urban-plan-research/catalog_pass/inspect_bicycles.py b/simulation/urban-plan-research/catalog_pass/inspect_bicycles.py new file mode 100644 index 00000000..9e6865a0 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/inspect_bicycles.py @@ -0,0 +1,24 @@ +"""Exhaustive visual QA of every fitted bicycle proposal; no processing ROI.""" +import json,numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S,parts +from search_views import SearchViews +from fit_scene import project +from catalog_templates import bicycle +proposals=json.loads((O/'catalog-proposals.json').read_text())['glyphs'];diag=json.loads((O/'catalog-diagnostics.json').read_text());best={} +for r in diag: + if r['kind']!='bicycle':continue + i=r['proposal'] + if i not in best or r['score']>best[i]['score']:best[i]=r +rows=sorted(best.values(),key=lambda r:-r['score']);tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,None,None,None,None);font=ImageFont.truetype('/candidate/review-font.ttf',18) +for start in range(0,len(rows),12): + batch=rows[start:start+12];sheet=Image.new('RGB',(1800,340*int(np.ceil(len(batch)/3))),'white');d=ImageDraw.Draw(sheet) + for k,r in enumerate(batch): + item=proposals[r['proposal']];name=item['source_tile'];p=shape(item['geometry']);fit=bicycle(r['parameters']);g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);factor=raw.width/1200;coords=shapely.get_coordinates(p.union(fit));uv=project(coords,g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*.5/60;bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));over=raw.copy();draw=ImageDraw.Draw(over) + for poly in parts(fit): + for ring in [poly.exterior]+list(poly.interiors):draw.line([tuple(x)for x in project(ring.coords,g)*factor],fill='#efc400',width=2) + x=(k%3)*600;y=(k//3)*340 + sheet.paste(raw.crop(bbox).resize((295,295)),(x,y+40));sheet.paste(over.crop(bbox).resize((295,295)),(x+300,y+40));d.text((x+4,y+5),str(r['proposal'])+' score '+str(round(r['score'],3))+' '+name,font=font,fill='black') + sheet.save(O/('bike-review-%03d.jpg'%start),quality=95) +print('BICYCLE PROPOSALS REVIEWED',len(rows),flush=True) diff --git a/simulation/urban-plan-research/catalog_pass/inspect_catalog.py b/simulation/urban-plan-research/catalog_pass/inspect_catalog.py new file mode 100644 index 00000000..b59156d3 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/inspect_catalog.py @@ -0,0 +1,27 @@ +"""Exhaustive review of existing image proposals; no processing ROI selection.""" +from pathlib import Path +import json, numpy as np +from PIL import Image, ImageDraw, ImageFont +from shapely.geometry import shape +from layer_common import O,S +from search_views import SearchViews +from fit_scene import project +import sys,cv2,importlib.util +print('ENV',sys.version,'CV',cv2.__version__,'XIMGPROC',hasattr(cv2,'ximgproc'),'SCIPY',importlib.util.find_spec('scipy')is not None,flush=True) + +p=json.loads(Path('/fullplan/search-proposals.json').read_text()) +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +views=SearchViews(tiles,None,None,None,None) +font=ImageFont.truetype('/candidate/review-font.ttf',18) +stats=[] +for start in range(0,len(p['glyphs']),20): + group=p['glyphs'][start:start+20];sheet=Image.new('RGB',(1600,260*int(np.ceil(len(group)/5))),'white');d=ImageDraw.Draw(sheet) + for k,r in enumerate(group): + poly=shape(r['geometry']);name=r['source_tile'];g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);factor=raw.width/1200 + coords=np.array(poly.convex_hull.exterior.coords);uv=project(coords,g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+factor*12 + bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));sheet.paste(raw.crop(bbox).resize((240,240)),((k%5)*320,(k//5)*260+20)) + d.text(((k%5)*320,(k//5)*260),str(start+k)+' '+name,font=font,fill='black') + stats.append(dict(index=start+k,tile=name,area=poly.area,bounds=poly.bounds)) + sheet.save(O/('proposals-%03d.jpg'%start),quality=95) +(O/'proposal-inspection.json').write_text(json.dumps(stats,indent=2)) +print('PROPOSALS',len(stats),flush=True) diff --git a/simulation/urban-plan-research/catalog_pass/refine_catalog.py b/simulation/urban-plan-research/catalog_pass/refine_catalog.py new file mode 100644 index 00000000..b4d2fabd --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/refine_catalog.py @@ -0,0 +1,107 @@ +from pathlib import Path +import os,json,time,hashlib,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping,LineString +from shapely.ops import transform +from layer_common import O,S,sample,feature,parts +from search_views import SearchViews +from discovery_rules import unpack,uncovered,glyph_context +from discovery_evidence import glyph_views +from catalog_evidence import mosaic_views +from line_reconstruction import rows +from beta_profiles import describe,profiles,section_evidence +from interval_profiles import rectangle +from corridor_profiles import missing_sections +from catalog_templates import fit_bicycle +from catalog_zigzag import fit_zigzag +from catalog_rules import VERSION,POLICY,accept_bicycle,accept_zigzag +from catalog_context import bicycle_context +cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']} +proposal_path=Path('/fullplan/search-proposals.json');proposals=json.loads(proposal_path.read_text()) +fresh_path=O/'catalog-proposals.json';fresh=json.loads(fresh_path.read_text());assert fresh['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest() +proposals['glyphs']=fresh['glyphs'] +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +def poly(f):return shapely.force_2d(shape(f['geometry'])) +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking']) +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +views=SearchViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[] +def admit(p,subtype,kind,evidence,names,**extra): + global existing + if not uncovered(p,existing):return False + f=feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_tile=names[0],source_tiles=names,standard_compliance='not_assessed',**extra) + if f['id']in current:return False + current[f['id']]=f;existing=shapely.union_all([existing,p]);transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']],before=[],after=[f],bounds_xy=p.bounds,evidence=evidence,source_tiles=names,**extra));print('ADMIT',len(transactions),subtype,kind,flush=True);return True + +for i,r in enumerate(proposals['glyphs']): + p=shape(r['geometry']);fits=fit_bicycle(p,all_hypotheses=True) + if not fits:continue + for fit in fits: + diag={k:v for k,v in fit.items()if k!='polygon'};diag.update(kind='bicycle',proposal=i);diagnostics.append(diag) + if fit['score']=3 and r['W']<=POLICY['max_line_width_m']: + s=describe(r['polygon']) + if s is not None:seeds.append(s) +for rr in rows(records): + if len(rr['records'])<2:continue + u=rr['axis'];o=rr['origin'];ranges=sorted([[(r['center']-o)@u-r['L']/2,(r['center']-o)@u+r['L']/2]for r in rr['records']]);chunks=[] + for a,b in ranges: + if chunks and a-chunks[-1][1]<=.30:chunks[-1][1]=max(chunks[-1][1],b) + else:chunks.append([a,b]) + for a,b in chunks: + if 3.97:continue + if any(domain.intersection(q).area/domain.area>.85 for q in seen):continue + seen.append(domain);readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers,extension=.5) + if pv is None:stats['no_profile']+=1;continue + width=float(np.clip(np.median([v['width']for v in pv]),.075,.27));offset=float(np.mean([v['offset']for v in pv])) + for a,b in pv[0]['intervals']: + for c,d in pv[1]['intervals']: + lo=max(a,c,-seed['length']/2);hi=min(b,d,seed['length']/2) + if hi-lo=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']and e['contrast']>=POLICY['min_line_contrast']for e in ev):stats['weak_paint']+=1;continue + parent=rectangle(seed['origin'],seed['axis'],lo,hi,width,offset) + for section in missing_sections(parent,existing): + scores,names=glyph_views(section,views,None,None) + if len(scores)!=2 or not all(e['valid']>=POLICY['min_line_valid']and e['support']>=POLICY['min_line_support']for e in scores):stats['section_views_rejected']+=1;continue + admit(section,'linear_marking','observed-continuous-section',dict(profile=ev,section=scores,parent_geometry=mapping(parent)),names,line_kind='observed-continuous',endpoint_authority='observed_window_not_physical_end',width_m=width) + if i%50==0:print('LINES',i,'/',len(seeds),'ADMITTED',len(transactions),flush=True) +result={**old,'features':list(current.values()),'catalog_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'catalog-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'catalog-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),proposal_cache_sha256=hashlib.sha256(proposal_path.read_bytes()).hexdigest(),catalog_proposals_sha256=hashlib.sha256(fresh_path.read_bytes()).hexdigest(),proposal_cache_baseline_sha256=proposals['baseline_sha256'],changed_segments=len(transactions),added_objects=len(transactions),added_subtypes=dict(collections.Counter(r['after'][0]['properties']['subtype']for r in transactions)),stages=dict(collections.Counter(r['kind']for r in transactions)),diagnostics=dict(stats),profiled_axes=len(seen),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'catalog-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/catalog_pass/render_catalog.py b/simulation/urban-plan-research/catalog_pass/render_catalog.py new file mode 100644 index 00000000..631a4aae --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/render_catalog.py @@ -0,0 +1,33 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from search_views import SearchViews +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'catalog-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('catalog-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +views=SearchViews(tiles,None,None,None,None);tiles=views.tiles +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='catalog-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('catalog-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'catalog-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) diff --git a/simulation/urban-plan-research/catalog_pass/render_plan.py b/simulation/urban-plan-research/catalog_pass/render_plan.py new file mode 100644 index 00000000..49823699 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/render_plan.py @@ -0,0 +1,109 @@ +"""Evidence images from metric vectors, not AI-generated imagery.""" +from pathlib import Path +import json,os,shapely +from datetime import datetime,timezone +import shutil +import numpy as np +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape,box +from fit_scene import project +from search_views import SearchViews +from layer_common import B,O,S +D=json.loads((O/'full-map.json').read_text());v=json.loads((B/'viewer-data.json').read_text());low,high=np.asarray(v['bounds_xy']);res=v['resolution_m'];fontpath='/candidate/review-font.ttf' +from collections import Counter +(O/'catalog-inventory.json').write_text(json.dumps(dict(scene=os.environ['SCENE'],classes=dict(Counter(f['properties']['class']for f in D['features'])),marking_features=dict(Counter(f['properties'].get('subtype','unknown')for f in D['features']if f['properties']['class']=='road_marking')),crosswalk_count_unit='individual painted bars, not crossings',coverage_recall_measured=False),indent=2)) +prior=set(O.glob('bridge-*.jpg'))|{O/'glyph-proof.jpg'} +for p in prior: + if p.exists(): + history=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));history.mkdir(parents=True,exist_ok=True);shutil.move(p,history/p.name) +try:font=ImageFont.truetype(fontpath,20) +except OSError:font=ImageFont.load_default() +colors={'road_boundary':(236,124,25),'pedestrian_boundary':(18,165,92),'building_facade':(0,151,224),'road_marking':(241,195,0)} +def draw_plan(im,projector,features,width=3): + rgba=im.convert('RGBA');fill=Image.new('RGBA',im.size);df=ImageDraw.Draw(fill) + for f in features: + if f['properties']['class']!='pedestrian_area':continue + rings=f['geometry']['coordinates'] + df.polygon([tuple(q)for q in projector(rings[0])],fill=(25,193,120,58)) + for ring in rings[1:]:df.polygon([tuple(q)for q in projector(ring)],fill=(0,0,0,0)) + rgba=Image.alpha_composite(rgba,fill);draw=ImageDraw.Draw(rgba) + for cls in ['pedestrian_boundary','building_facade','road_marking','road_boundary']: + for f in features: + if f['properties']['class']!=cls:continue + rings=f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']] + for ring in rings: + pts=[tuple(q)for q in projector(ring)];draw.line(pts,fill=colors[cls],width=width,joint='curve') + return rgba.convert('RGB') +def title(im,name): + result=Image.new('RGB',(im.width,im.height+68),'white');result.paste(im,(0,68));d=ImageDraw.Draw(result);d.text((15,7),name,font=font,fill='#263640') + x=15 + for text,clr in [('Дороги',(236,124,25)),('Пешеходные зоны',(18,165,92)),('Фасады',(0,151,224)),('Разметка',(200,155,0))]: + d.rectangle((x,42,x+20,57),fill=clr);d.text((x+29,37),text,font=font,fill='#263640');x+=int(d.textlength(text,font=font))+64 + return result +world=lambda p:np.c_[(np.asarray(p)[:,0]-low[0])/res,(high[1]-np.asarray(p)[:,1])/res] +if (B/'whole-gaussians.jpg').exists():base=Image.open(B/'whole-gaussians.jpg').convert('RGB') +else: + width,height=v['size'];mosaic=np.full((height,width,3),255,np.uint8);weights=np.zeros((height,width),np.float32) + for tile in json.loads((S/'tile-index.json').read_text())['tiles']: + if tile['status']!='surveyed':continue + lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/res).astype(int);x,y=np.rint([(lo[0]-low[0])/res,(high[1]-hi[1])/res]).astype(int) + im=np.asarray(Image.open(S/tile['id']/'top.png').convert('RGB').resize((tw,th),Image.Resampling.LANCZOS));g=np.load(S/tile['id']/'top.geometry.npz');alpha=np.asarray(Image.fromarray(g['alpha'].astype('float32')).resize((tw,th),Image.Resampling.BILINEAR));g.close() + yy,xx=np.mgrid[:th,:tw];score=(.01+np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy])/max(tw,th))*np.clip(alpha,0,1);sl=np.s_[y:y+th,x:x+tw];take=score>weights[sl];mosaic[sl][take]=im[take];weights[sl][take]=score[take] + base=Image.fromarray(mosaic) +whole=draw_plan(base,world,D['features']);whole.save(O/'whole-overlay.jpg',quality=96) +plan=draw_plan(Image.new('RGB',base.size,'#f5f5f2'),world,D['features']);title(plan,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · инженерные слои').save(O/'whole-plan.jpg',quality=96) +preview=whole.copy();preview.thumbnail((2300,1500));title(preview,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · четыре слоя поверх гауссов').save(O/'overview.jpg',quality=96) +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];scores=[];records=[] +for tile in tiles: + name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);features=[f for f in D['features']if shape(f['geometry']).intersects(domain)];counts={c:sum(f['properties']['class']==c for f in features)for c in ['building_facade','road_marking','pedestrian_area','road_boundary']} + image=Image.open(S/name/'top.png').convert('RGB');overlay=draw_plan(image,lambda p:project(p,g),features) + overlay.save(O/(name+'.overlay.jpg'),quality=95);image.save(O/(name+'.source.jpg'),quality=95) + score=sum(v>0 for v in counts.values())*100+min(counts['building_facade'],10)*3+min(counts['road_marking'],20) + scores.append((score,name));records.append(dict(tile=name,counts=counts)) +chosen=[] +for score,name in sorted(scores,reverse=True): + if any(abs(int(name.split('-')[1])-int(n.split('-')[1]))<2 for n in chosen):continue + chosen.append(name) + if len(chosen)==3:break +sheet=Image.new('RGB',(1800,950*len(chosen)),'white');draw=ImageDraw.Draw(sheet) +for row,name in enumerate(chosen): + for col,suffix in enumerate(['source','overlay']): + im=Image.open(O/(name+'.'+suffix+'.jpg')).resize((900,900),Image.Resampling.LANCZOS);sheet.paste(im,(900*col,950*row+50));draw.text((900*col+12,950*row+12),name+' · '+('Гауссы'if col==0 else'Все слои'),font=font,fill='#263640') +sheet.save(O/'details.jpg',quality=96) +(O/'visual-manifest.json').write_text(json.dumps(dict(review_only_selection='automatic class diversity with spatial separation',selected=chosen,all_tiles=records,manual_processing_rois=[]),indent=2));print('PICTURES',chosen,flush=True) +# Whole-scene before/after comparison and an exhaustive glyph evidence sheet. +old=json.loads(Path('/fullplan/full-map.json').read_text()) +before=draw_plan(base,world,old['features']);before.thumbnail((2300,1500)) +after=whole.copy();after.thumbnail((2300,1500)) +rows=[title(before,os.environ['SCENE']+' · предыдущая сборка'),title(after,os.environ['SCENE']+' · уточнение')] +comparison=Image.new('RGB',(max(x.width for x in rows),sum(x.height for x in rows)+12),'white');y=0 +for row in rows:comparison.paste(row,(0,y));y+=row.height+12 +comparison.save(O/'comparison-full.jpg',quality=95) +search_views=SearchViews(tiles,None,None,None,None) +glyphs=[f for f in D['features']if f['properties'].get('subtype')not in [None,'linear_marking','crosswalk']] +if glyphs: + sheet=Image.new('RGB',(1600,270*int(np.ceil(len(glyphs)/4))),'white');d=ImageDraw.Draw(sheet) + for k,item in enumerate(glyphs): + prop=item['properties'];name=prop.get('source_tile') + if not name:continue + g=search_views.geometry(name);raw=Image.fromarray(search_views.inputs(name)[0]);factor=raw.width/1200 + xy=shapely.get_coordinates(shape(item['geometry']));uv=project(xy,g)*factor;lo=uv.min(0)-25;hi=uv.max(0)+25;center=(lo+hi)/2;extent=max(hi-lo);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int)) + overlay=draw_plan(raw,lambda p:project(p,g)*factor,[item],width=3) + for j,im in enumerate([raw,overlay]):sheet.paste(im.crop(bbox).resize((195,195),Image.Resampling.LANCZOS),((k%4)*400+j*200,(k//4)*270+65)) + d.text(((k%4)*400+5,(k//4)*270+8),str(k+1)+' '+prop['subtype'],font=font,fill='#263640');d.text(((k%4)*400+5,(k//4)*270+34),name,font=font,fill='#263640') + sheet.save(O/'glyph-proof.jpg',quality=96) +# Inspect every admitted road interpolation, not a hand-picked success crop. +spans=[(f,s)for f in D['features']if f['properties']['class']=='road_boundary'for s in f['properties'].get('inferred_spans',[])] +if spans: + sheet=Image.new('RGB',(1800,645*len(spans)),'white');d=ImageDraw.Draw(sheet) + for k,(owner,span)in enumerate(spans): + coords=np.array(span['coordinates']);center=coords[:,:2].mean(0) + tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz')) + raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + uv=project(coords,g)*factor;middle=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*8/60;extent=max(extent,raw.width*18/60) + bbox=tuple(np.r_[middle-extent/2,middle+extent/2].astype(int)) + for col,(fs,label)in enumerate([(None,'Гауссы'),(old['features'],'До'),(D['features'],'После')]): + im=raw if fs is None else draw_plan(raw,lambda p:project(p,g)*factor,fs,width=max(2,int(factor*2))) + patch=im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS);sheet.paste(patch,(col*600,k*645+45));d.text((col*600+10,k*645+10),str(k+1)+' · '+label,font=font,fill='#263640') + sheet.save(O/'bridge-proof.jpg',quality=95) + for k in range(len(spans)):sheet.crop((0,k*645,1800,(k+1)*645)).save(O/('bridge-%02d.jpg'%(k+1)),quality=96) diff --git a/simulation/urban-plan-research/catalog_pass/test_catalog.py b/simulation/urban-plan-research/catalog_pass/test_catalog.py new file mode 100644 index 00000000..a74ad066 --- /dev/null +++ b/simulation/urban-plan-research/catalog_pass/test_catalog.py @@ -0,0 +1,69 @@ +import runpy,json,numpy as np,cv2,shapely +from shapely.geometry import LineString,box +from shapely.affinity import rotate,translate,scale +from catalog_templates import bicycle,fit_bicycle,UNIT +from catalog_zigzag import fit_zigzag +from fragment_templates import template +from beta_profiles import profiles,section_evidence +from catalog_rules import POLICY +prior=runpy.run_path('/candidate/test_search.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +checks['bicycle_artwork_preserves_wheel_voids']=UNIT.is_valid and len(UNIT.interiors)>=3 +for name,angle,L,W in [('upright',0.,1.7,.9),('rotated',.8,2.3,1.1),('reverse',3.4,1.6,.75),('wider_than_long',.2,.9,1.7)]: + source=bicycle([12,-7,angle,L,W,0]);fit=fit_bicycle(source) + checks['bicycle_'+name+'_registration']=fit is not None and fit['score']>.85 and fit['polygon'].symmetric_difference(source).area/source.area<.30 +for kind in ['letter_A','straight_arrow','right_arrow','straight_left_arrow']: + p=template(kind,2.5,1.,.16);fit=fit_bicycle(p) + checks[kind+'_not_a_bicycle']=fit is None or fit['score']=4 and fit['fit_residual_m']<.16 +for name,p in [('straight',box(0,0,12,.15)),('rectangle',box(0,0,5,2).exterior.buffer(.06)),('erratic',LineString([(0,0),(2,1.8),(3,0),(7,1.8),(8,0)]).buffer(.06)),('single_v',LineString([(0,0),(2,2),(4,0)]).buffer(.06))]: + checks[name+'_not_regular_zigzag']=fit_zigzag(p)is None +seed=dict(origin=np.array([0.,0.]),axis=np.array([1.,0.]),length=8.,width=.12) +def read(points): + on=abs(points[:,1])<.07;gray=np.where(on,225,65).astype('uint8');return np.repeat(gray[:,None],3,axis=1),np.ones(len(points),bool) +pv=profiles(seed,[read,read],extension=.5) +checks['long_line_crossing_both_window_edges_measured']=pv is not None and all(section_evidence(v,-3.95,3.95)['support']>.99 for v in pv) +def missing(points): + rgb,valid=read(points);valid[abs(points[:,0])<1]=False;return rgb,valid +pv=profiles(seed,[read,missing],extension=.5) +checks['unknown_long_line_gap_not_filled']=pv is not None and section_evidence(pv[1],-3.95,3.95)['valid'].93 for e in ev) +ev,_=mosaic_views(stripe,FakeViews([15]));checks['one_camera_does_not_become_two']=ev[1]['paint_coverage']==0 +fv.labels[:,690:730]=0;ev,_=mosaic_views(stripe,fv);checks['road_unknown_veto_remains_in_mosaic']=all(e['paint_valid']<.97 for e in ev) +from catalog_rules import accept_bicycle,accept_zigzag +strong=dict(paint_coverage=1.,paint_valid=1.,support=.99,recall=.98,negative_paint=.02,observed_support=.99) +absent=dict(paint_coverage=0.,paint_valid=0.,support=0.,recall=0.,negative_paint=1.,observed_support=0.) +checks['strong_single_native_view_can_identify_bicycle']=accept_bicycle([strong,absent],.85)=='strong-complete-view-plus-available-consistency' +checks['weak_template_cannot_use_missing_view_fallback']=accept_bicycle([strong,absent],.68)is None +checks['conflicting_available_view_vetoes_bicycle']=accept_bicycle([strong,{**strong,'support':.5,'observed_support':.5}],.85)is None +checks['incomplete_primary_cannot_use_fallback']=accept_bicycle([{**strong,'paint_coverage':.9},absent],.85)is None +fit=dict(legs=4,fit_residual_m=.04,proposal_recall=.95);partial={**strong,'paint_coverage':.5,'paint_valid':.5,'support':.5} +checks['strong_zigzag_uses_available_partial_consistency']=accept_zigzag([strong,partial],[[strong,partial]]*4,fit)=='strong-complete-view-plus-available-consistency' +checks['single_bad_zigzag_leg_vetoes_pattern']=accept_zigzag([strong,partial],[[strong,partial]]*3+[[{**strong,'support':.4},partial]],fit)is None +checks['weak_zigzag_fit_cannot_use_missing_view']=accept_zigzag([strong,absent],[[strong,absent]]*4,{**fit,'fit_residual_m':.2})is None +from catalog_context import bicycle_context +def strip(a,b,y=2.,axis=(1.,0.)): + return dict(center=np.array([(a+b)/2,y]),L=b-a,W=.12,axis=np.array(axis),polygon=box(a,y-.06,b,y+.06),source_tile='synthetic') +p=box(0,0,1,.5);parameters=[0,0,0,1,.5,0] +whole=bicycle_context(p,parameters,[strip(-3,7)]) +split=bicycle_context(p,parameters,[strip(-3,0),strip(0,3),strip(3,7)]) +checks['one_continuous_lane_strip_is_context']=whole['passed'] +checks['lane_context_invariant_to_strip_fragmentation']=split['passed']and split['supporting_length_m']==whole['supporting_length_m'] +checks['duplicate_short_strips_cannot_inflate_context']=not bicycle_context(p,parameters,[strip(0,2)]*5)['passed'] +checks['perpendicular_strip_is_not_lane_context']=not bicycle_context(p,parameters,[strip(-3,7,axis=(0.,1.))])['passed'] +checks['isolated_symbol_has_no_lane_context']=not bicycle_context(p,parameters,[])['passed'] +checks['lane_context_is_json_serializable']=json.loads(json.dumps(whole))==whole +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/catalog-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed'] diff --git a/simulation/urban-plan-research/completion_pass/README.rst b/simulation/urban-plan-research/completion_pass/README.rst new file mode 100644 index 00000000..3e7c81c0 --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/README.rst @@ -0,0 +1,85 @@ +Mission Core: bounded completion of observed paint rows +====================================================== + +Offline qualification only. The input is discovery-pass-20261012. No live map +replacement, deployment, point-cloud input, per-scene threshold or manual ROI. + +The same frozen Python source and policy run on Maroseyka, Pokrovka and Smolensk. +All three scenes have been inspected during development; none is an untouched +holdout. Controlled tests and operation counts do not measure real-world recall +or metric accuracy. + +Pipeline +-------- + +1. Cluster compatible existing dashed vectors by metric direction, spacing, + phase and transverse residual. Huber fitting supplies a common row axis. +2. Reobserve at least three anchors in two geometrically selected Gaussian + mosaics. The source images represent one reconstruction, not independent + physical observations. Search bounded missing slots and row ends. Each new + stroke requires visible paint, observed edges, valid dark neighboring gaps, + compatible transverse width and agreement between the two mosaics. Period + alone never authorizes a stroke. Existing symbols and neighboring lines are + protected. No output fills an unobserved/occluded paint slot. +3. Reuse the qualified beta periodic fitter for existing axes. Avoid repeated + renormalization of already dashed rows without added strokes or an old + non-dashed overlap. Preserve geometry outside the proven longitudinal edit. +4. Reuse qualified full-corridor endpoint checks. A sideways bend is not proof + that paint ends. Blank masks and vehicle occlusion are not dark asphalt. +5. Reuse the qualified partial-duplicate classifier with continuous evidence + mosaics, retaining the observed keeper and exact XY outside the common span. + Two physical paint ridges veto removal. Reuse whole-row assembly at the end. + +OpenCV, SciPy, Shapely and existing research modules implement these stages. +No training, new model download or alternate per-location pipeline is required. +The output remains observation-only, route_permission unassigned, unreviewed. +Z comes from the existing Gaussian-derived field. Existing GOST dimensional +assessments remain soft checks; no legal compliance conclusion is made. + +Execution and evidence +---------------------- + +Use bundle.json to resolve canonical source. The private qualification retains +runner/collector/verifier, scene registry, execution receipts, input hashes, +replayable transactions, controlled checks, JPGs and visual review. A frozen +source ZIP accompanies delivery. Review font is external, hash-pinned and omitted +from that ZIP. Private scene caches are required to reproduce the run. + +Worker006 only: pinned image +sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0; +4 CPU, 20 GiB, network none, read-only root, 1800 seconds per stage. +Mac orchestration uses the canonical Observatory recorded-job reservation. +All output replacements are isolated in qualification; accepted input is read-only. + +Regression source contains attributed arrow artwork: MajorAlexey, +https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg, +CC BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/. +Adaptation: normalized parametric polygons; original source SHA-256 +b76f40ee8d1603ddfeb3cd430f397dcc509684f0a0aa38c61bbd8a2cba554ea8. +This pass does not modify glyphs, roads, pedestrian zones, facades or crosswalks. + +Additional acceptance details +----------------------------- + +Short strokes above a worn continuous underlay may use a bounded prominent peak. +The gap still needs a contrast drop of at least 22 and its 80th percentile must +stay below 60 percent of the stroke contrast in each view. Absolute dark-gap +acceptance remains available. A uniform stripe cannot pass this peak rule. +The generated common axis itself must stay within max(0.04 m, 0.3*width) of each +observed ridge. Local endpoint context is limited to the nearest four metres. + +A sixth stage checks a generic thin-line object parallel to an existing zebra +bar. Only a geometrically contained common span is eligible. Both full-object +renders must support the retained bar (valid >=0.98, support >=0.85). +Crossing longitudinal lane lines are ineligible. A 0.025 m boundary tolerance +accounts for pixel-scale geometry; it is not a standards tolerance. The zebra +feature is retained unchanged; only the duplicate linear span is removed. + +Novelty counts use the complete current paint map, including a 0.1 m clearance. +A shifted outline is not a newly discovered stroke. Existing periodic geometry +is rebuilt only for genuinely absent strokes or >=0.03 m2 of old vector paint +inside verified gaps. Candidates leaving tiny residual fragments are rejected. +These gates were added after visual review rejected ineffective re-fitting. + +Bar deduplication uses positive coverage of the retained bar. Paint outside that +bar is not edited and does not veto an internal duplicate through a recall test. diff --git a/simulation/urban-plan-research/completion_pass/audit_completion.py b/simulation/urban-plan-research/completion_pass/audit_completion.py new file mode 100644 index 00000000..ad9b0d8f --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/audit_completion.py @@ -0,0 +1,68 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +from completion_profiles import POLICY,VERSION,supported,gap_supported,bar_supported,bar_overlap +old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/completion-rows.json').read_text());current={f['id']:f for f in old['features']};checks={} +def poly(f):return shapely.force_2d(shape(f['geometry'])) +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +checks['transaction_replay']=True;checks['only_linear_objects_replaced']=True;checks['no_new_neighbor_overlap']=True;checks['protected_paint_preserved']=True;checks['evidence_passes']=True;checks['outside_edit_interval_preserved']=True +def duplicate_evidence(r): + if r['kind']=='confirmed_dash_gap':return all(v['valid']>=.95 and v['dark_fraction']>=.9 and v['q90']<8 and all(a['valid']>=.95 and a['support']>=.85 and a['median']>=22 for a in v['anchors'])for v in r['views']) + if not all(v['source_valid']>=.95 and v['target_valid']>=.95 and v['target_support']>=.85 and v['target_median']>=22 for v in r['views']):return False + if not all(x['valid_fraction']>=.95 and x['two_ridge_fraction']<=.1 and x['longest_two_ridge_m']<.25 for x in r['ridges']):return False + if r['kind']=='overlapping_duplicate':return r['geometry']['contained_fraction']>=.90 + if r['kind']=='unsupported_offset_duplicate':return all(v['source_support']<=.15 and v['source_q75']<8 for v in r['views']) + if r['kind']!='one_ridge_two_vectors':return False + xs=r['ridges'] + if not all(len(x['peaks'])==1 for x in xs):return False + ds=[x['peaks'][0]['offset']for x in xs] + return max(ds)-min(ds)<=.05 and all(abs(d)>=.10 and abs(d-x['target_offset'])<=.08 and abs(d)-abs(d-x['target_offset'])>=.06 for d,x in zip(ds,xs)) + +for r in rows: + before=r['before'];after=r['after'];ids=r['source_ids'] + checks['transaction_replay']&=all(current.get(f['id'])==f for f in before)and ids==[f['id']for f in before]and r['output_ids']==[f['id']for f in after] + checks['only_linear_objects_replaced']&=all(f['properties'].get('subtype')=='linear_marking'for f in before+after) + a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in after]);novel=b.difference(a) + checks['protected_paint_preserved']&=novel.intersection(protected).area<=POLICY['max_new_neighbor_overlap_m2'] + checks['no_new_neighbor_overlap']&=all(novel.intersection(poly(f)).area<=POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and f['properties'].get('subtype')=='linear_marking') + ev=r['evidence'];ok=len(r['source_views'])==2 and len(r['source_tiles'])>=2 + if r['kind']=='row-completion': + ok&=not before and len(ev['anchors'])>=POLICY['min_anchor_reobserved']and len(ev['slots'])==len(after) + ok&=all(len(q['views'])==2 and all(supported(v['paint'])and len(v['gaps'])==2 and all(e.get('full_corridor')and gap_supported(e,v['paint'])for e in v['gaps'])for v in q['views'])for q in ev['anchors']+ev['slots']) + ok&=all(max(abs(q['views'][0]['edges'][j]-q['views'][1]['edges'][j])for j in [0,1])<=POLICY['max_slot_edge_error_m']for q in ev['anchors']+ev['slots']) + elif r['kind']=='periodic-row': + ok&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint']) + ok&=len(ev['gaps'])==2*(len(ev['observations'])-1) + ok&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps']) + ok&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=POLICY['max_edge_disagreement_m']for e in ev['observations']) + ok&=all(e['padding']<=POLICY['max_family_edge_padding_m']and len(e['views'])==2 and all(v.get('full_corridor')and supported(v,False)for v in e['views'])for e in ev['edges']) + # The transverse replacement section is wider than the modeled stripe; + # the outside longitudinal old contours must nevertheless be exact. + from interval_profiles import rectangle + d=shape(r['edit_domain']);o=np.array(r['origin']);u=np.array(r['axis']);tt=(np.asarray(d.exterior.coords)-o)@u;domain=rectangle(o,u,float(tt.min()),float(tt.max()),2.) + checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7 + elif r['kind']=='solid-endpoints': + ok&=all(len(e['evidence'])==2 and POLICY['min_endpoint_change_m']<=abs(e['delta'])<=POLICY['max_endpoint_change_m']and all(supported(v['paint'])and supported(v['dark'],False)and supported(v['edit'],e['kind']=='extend-solid')for v in e['evidence'])for e in ev) + ok&=all(v['dark'].get('full_corridor')and(e['kind']=='extend-solid'or v['edit'].get('full_corridor'))for e in ev for v in e['evidence']) + domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain.buffer(1e-7)).symmetric_difference(b.difference(domain.buffer(1e-7))).area<1e-7 + elif r['kind']=='duplicate-section': + ok&=len(ev['views'])==2 and duplicate_evidence(ev) and r['keeper_id']in current and r['keeper_id']not in ids + domain=shape(r['edit_domain']);checks['outside_edit_interval_preserved']&=a.difference(domain).symmetric_difference(b).area<1e-7 + elif r['kind']=='crosswalk-line-duplicate': + keeper=current.get(r['keeper_id']);ok&=bool(keeper)and keeper['properties'].get('subtype')=='crosswalk'and bar_supported(ev) + domain=shape(r['edit_domain']);ok&=len(before)==1 and bar_overlap(poly(before[0]),poly(keeper)).symmetric_difference(domain).area<1e-8 + checks['outside_edit_interval_preserved']&=a.difference(domain).symmetric_difference(b).area<1e-7 + elif r['kind']=='assembled-row': + ok&=len(ev)==2 and r['max_axis_displacement_m']<=.065 and all(v['local_evidence_passed']for v in ev)and any(v['passed']for v in ev) + else:ok=False + checks['evidence_passes']&=ok + for i in ids:current.pop(i,None) + for f in after:current[f['id']]=f +features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features']) +checks['unchanged_other_layers']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('subtype')!='linear_marking') +checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']) +checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes() +report=json.loads(Path('/out/completion-report.json').read_text());checks['same_policy']=new['completion_refinement']==VERSION and report['policy']==POLICY +checks['every_operation_counted']=report['changed_segments']==len(rows)and sum(report['stages'].values())==len(rows) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/completion-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/completion_pass/bundle.json b/simulation/urban-plan-research/completion_pass/bundle.json new file mode 100644 index 00000000..b4687486 --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/bundle.json @@ -0,0 +1,126 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_completion.py": "completion_pass/audit_completion.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "completion_profiles.py": "completion_pass/completion_profiles.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_completion.py": "completion_pass/refine_completion.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_completion.py": "completion_pass/render_completion.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "continuation_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "rows_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_completion.py": "completion_pass/test_completion.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py" + }, + "reference_qualification": "completion-pass-20261012", + "source_snapshot": "9eed93a977bcb32571d4", + "source_sha256": { + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/completion_pass/completion_profiles.py b/simulation/urban-plan-research/completion_pass/completion_profiles.py new file mode 100644 index 00000000..f0bbf3d5 --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/completion_profiles.py @@ -0,0 +1,142 @@ +"""Existing periodic rows nominate bounded slots; two Gaussian mosaics decide. + +No phase-only fill: known anchors are re-observed, each new slot needs measured +paint edges and dark neighboring gaps. Missing/occluded slots remain unpainted. +Uses OpenCV Huber lines and the existing metric paint-profile components. +""" +import numpy as np,cv2 +from scipy.signal import find_peaks,peak_widths +from scipy.ndimage import gaussian_filter1d +from interval_profiles import rectangle,strip,runs +from section_profiles import POLICY as SECTION_POLICY +from beta_profiles import describe,profiles,discover,endpoints,POLICY as BASE,supported +VERSION='paint-row-completion-v1' +POLICY={**BASE,'min_family_anchors':3,'max_family_axis_deg':3.,'max_family_lateral_m':.15, + 'max_family_phase_m':.20,'max_slot_offset_m':.10,'max_slot_edge_error_m':.20, + 'max_extension_slots':6,'max_extension_distance_m':12.,'min_anchor_reobserved':3, + 'max_consecutive_unobserved_slots':2,'slot_length_relative_error':.25, + 'slot_length_absolute_error_m':.18,'min_slot_dark':.85,'min_slot_valid':.95,'min_gap_contrast_drop':22.,'max_gap_paint_ratio':.60,'duplicate_policy':SECTION_POLICY} + +def families(records): + """Deterministic clustering of compatible periodic vectors, not scene IDs.""" + recs=[] + for fid,p,prop in records: + if prop.get('line_kind')!='dashed':continue + P=prop.get('period_m');L=prop.get('dash_length_m');d=describe(p) + if not d or not P or not L or not .26max(.25,.3*L):continue + recs.append(dict(id=fid,period=float(P),dash=float(L),**d)) + groups=[];seen=set() + for a in sorted(recs,key=lambda r:r['id']): + o,u=a['origin'],a['axis'];n=np.array([-u[1],u[0]]);P=a['period'];L=a['dash'] + candidates=[b for b in recs if abs(b['axis']@u)>=np.cos(np.deg2rad(POLICY['max_family_axis_deg']))and abs((b['origin']-o)@n)<=POLICY['max_family_lateral_m']and abs(b['period']-P)<.15*P and abs(b['dash']-L)<.25*L and abs((b['origin']-o)@u)<70] + candidates.sort(key=lambda b:float((b['origin']-o)@u)) + chunks=[] + for b in candidates: + if not chunks or float((b['origin']-chunks[-1][-1]['origin'])@u)>3.2*P:chunks.append([]) + chunks[-1].append(b) + for c in chunks: + ids=tuple(sorted(r['id']for r in c)) + if len(c).10 or abs(v@u)70:continue + period=float(np.median([r['period']for r in c]));ix=np.rint((t-t.min())/period).astype(int) + if len(set(ix))!=len(ix):continue + fitted,phase=np.polyfit(ix,t,1) + if abs(fitted-period)>.10*period or max(abs(t-(phase+fitted*ix)))>POLICY['max_family_phase_m']:continue + groups.append(dict(origin=o+phase*v,axis=v,period=float(fitted),length=float(np.median([r['dash']for r in c])),width=float(np.median([r['width']for r in c])),indices=ix.tolist(),source_ids=list(ids),max_index=int(ix.max()))) + accepted=[] + for g in sorted(groups,key=lambda g:-len(g['source_ids'])): + if any(len(set(g['source_ids'])&set(q['source_ids']))>=2 for q in accepted):continue + accepted.append(g) + return accepted + +def gap_supported(g,paint): + return supported(g,False)or(g['valid']>=POLICY['min_slot_valid']and paint['contrast']-g['contrast']>=POLICY['min_gap_contrast_drop']and g['q80']cut)&valid + for a,b in runs(~paint): + if a>0 and b0 and b0 and b=center-.35*L)&(ts<=center+.35*L);positive=dict(valid=float(valid[inside].mean()),support=float((sig[inside]>cut).mean()),contrast=float(np.median(sig[inside]))) + gaps=[] + for left,right in [(c-ext,lo-.05),(hi+.05,c+ext)]: + sel=(ts>=left)&(ts<=right) + if sel.sum()<3:return None + # Full width surrounding the ridge, including the predicted vector. + corridor=abs(ns)<=max(.12,W/2+.06);vv=allowed[sel][:,corridor].all(1);ss=contrast[sel][:,corridor].max(1) + gaps.append(dict(valid=float(vv.mean()),support=float((ss.05 or max(abs(ev[0]['edges'][j]-ev[1]['edges'][j])for j in [0,1])>POLICY['max_slot_edge_error_m']:return None + # The predicted vector itself must intersect the ridge, not merely find + # some bright neighboring pixels in its search corridor. + if any(abs(e['offset'])>max(.04,.3*W)for e in ev): + if debug is not None:debug.update(reason='ridge-outside-output-axis',offsets=[e['offset']for e in ev]) + return None + # Keep the family's common axis/length/phase, subject to measured edge fit. + if any(max(abs(e['edges'][0]-(c-L/2)),abs(e['edges'][1]-(c+L/2)))>max(.20,.15*L)for e in ev):return None + p=rectangle(o,u,c-L/2,c+L/2,W) + return dict(polygon=p,evidence=ev,index=int(index)) + +def local_endpoints(seed,readers): + """Use bounded endpoint context so a far ridge cannot select the local axis.""" + if seed['length']<2.7:return [] + changes=[];window=min(4.,seed['length']) + for sign in [-1,1]: + local={**seed,'origin':seed['origin']+sign*(seed['length']-window)/2*seed['axis'],'length':window} + pv=profiles(local,readers,extension=2.5) + changes.extend(c for c in endpoints(local,pv)if c['sign']==sign) + return changes + +def bar_overlap(source,bar): + """Same-paint semantic overlap: a thin stripe follows an accepted zebra bar. + + A real longitudinal lane line crossing the bar is deliberately ineligible. + Only a parallel common span with strong geometric containment is nominated. + """ + from line_reconstruction import observation + if source.geom_type!='Polygon'or bar.geom_type!='Polygon':return None + a=observation(np.asarray(source.exterior.coords),'vector');b=observation(np.asarray(bar.exterior.coords),'bar') + if not .3<=b['W']<=1.2 or not 1.5<=b['L']<=20 or a['W']>.35 or a['L']<.6:return None + if abs(a['axis']@b['axis'])=.98 and e['support']>=.85 for e in evidence) diff --git a/simulation/urban-plan-research/completion_pass/refine_completion.py b/simulation/urban-plan-research/completion_pass/refine_completion.py new file mode 100644 index 00000000..9cc5f9e1 --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/refine_completion.py @@ -0,0 +1,205 @@ +from pathlib import Path +import os,json,time,hashlib,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping +from shapely.ops import transform +from layer_common import O,S,sample,feature,parts +from completion_profiles import POLICY,VERSION,describe,profiles,discover,endpoints +from discovery_evidence import DiscoveryViews as GaussianViews +from row_profiles import pair,fit_chain,check_chain +from transition_profiles import residual_sections +from gost_catalog import assess_dash + +cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']};current=dict(original) +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +protected=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +views=GaussianViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[];domains=[] +def poly(f):return shapely.force_2d(shape(f['geometry'])) +def linear(f):return f['properties'].get('subtype')=='linear_marking' +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +def make(p,kind,ids,**kw):return feature(lift(p),'road_marking',subtype='linear_marking',line_kind=kind,method=VERSION,source_ids=ids,standard_compliance='not_assessed',**kw) +def commit(kind,ids,new,domain,ev,used,extra=None): + before=[current[i]for i in ids];new=[f for f in new if not poly(f).is_empty];newids=[f['id']for f in new] + if len(set(newids))!=len(newids)or any(i in current and i not in ids for i in newids):return False + a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in new]);novel=b.difference(a) + if a.symmetric_difference(b).areaPOLICY['max_new_neighbor_overlap_m2']:return False + if any(novel.intersection(poly(f)).area>POLICY['max_new_neighbor_overlap_m2']for i,f in current.items()if i not in ids and linear(f)):return False + for i in ids:current.pop(i) + for f in new:current[f['id']]=f + rec=dict(kind=kind,source_ids=ids,output_ids=newids,before=before,after=new,bounds_xy=(shapely.union_all([a,b])if kind=='assembled-row'else domain).bounds,edit_domain=mapping(domain),evidence=ev,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),added_area_m2=float(novel.area),removed_area_m2=float(a.difference(b).area)) + if extra:rec.update(extra) + transactions.append(rec);print('EDIT',len(transactions),kind,len(ids),'->',len(new),flush=True);return True + +# Revalidate vector-derived periodic families before using them to nominate slots. +from completion_profiles import families,slot,local_endpoints +family_rows=families([(fid,poly(f),f['properties'])for fid,f in original.items()if linear(f)]) +for fi,g in enumerate(family_rows): + readers,used=views.readers(g['origin'],g['axis']);anchor_evidence=[] + for index in g['indices']: + ad={};r=slot(g,index,readers,ad) + diagnostics.append(dict(stage='anchor',family=fi,index=index,passed=r is not None,**ad)) + if r is not None:anchor_evidence.append(dict(index=index,views=r['evidence'])) + diagnostics.append(dict(stage='family',family=fi,anchors=len(g['indices']),observed=len(anchor_evidence))) + if len(anchor_evidence)=POLICY['max_consecutive_unobserved_slots']:break + continue + missed=0;p=r['polygon'] + from discovery_rules import uncovered + existing=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking']) + if not uncovered(p,existing):continue + additions.append(make(p,'dashed',g['source_ids'],period_m=g['period'],dash_length_m=g['length'],width_m=g['width'],standard_assessment=assess_dash(g['length'],g['period'],g['width']),observed_stroke=True)) + evidence.append(dict(index=index,views=r['evidence'])) + if additions: + domain=shapely.union_all([poly(f)for f in additions]);commit('row-completion',[],additions,domain,dict(anchors=anchor_evidence,slots=evidence),used,dict(family_source_ids=g['source_ids'],period_m=g['period'],dash_length_m=g['length'],newly_captured_strokes=len(additions))) + print('FAMILY',fi+1,'/',len(family_rows),'ADDITIONS',len(additions),flush=True) + +# Stage 1: every eligible existing axis seeds a 24m wider image search. Spatial +# neighborhoods already covered by an accepted periodic model are not reworked. +seeds=[] +for fid,f in original.items(): + if not linear(f):continue + rec=describe(poly(f)) + if rec is not None:seeds.append((fid,rec)) +proposals=[] +for index,(fid,seed)in enumerate(sorted(seeds,key=lambda x:(int(np.argmin(np.linalg.norm(views.centers-x[1]['origin'],axis=1))),-x[1]['length']))): + readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers) + found=discover(seed,pv);diagnostics.append(dict(seed_id=fid,stage='discover',profile_valid=pv is not None,proposals=len(found))) + for r in found:r.update(seed_id=fid,source_views=used);proposals.append(r) + if index%25==0:print('PROFILE',index+1,'/',len(seeds),'PROPOSALS',len(proposals),flush=True) + +# Stage 2: one normalized row replaces only its observed longitudinal section. +for r in sorted(proposals,key=lambda x:(-len(x['polygons']),-x['hi']+x['lo'])): + domain=r['domain'];u=r['axis'];o=r['origin'];n=np.array([-u[1],u[0]]);origin=o+r['offset']*n + if any(domain.intersection(d).area>.01 for d in domains):continue + ids=[];residual=[] + for fid,f in current.items(): + if not linear(f):continue + p=poly(f);d=describe(p) + if d is None or p.intersection(domain).area<.005 or abs(d['axis']@u).13:continue + # Old complete stroke centers must agree with the new ridge; crossings + # and a genuine neighboring stripe are not part of this row. + ids.append(fid) + for pp in parts(residual_sections(p,domain,o,u)): + if pp.area>.000001:residual.append(make(pp,f['properties'].get('line_kind','solid'),[fid],role='unchanged-section')) + if not ids:continue + generated=[make(p,'dashed',ids,period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']),observed_stroke=True)for p in r['polygons']] + before=shapely.union_all([poly(current[i])for i in ids]) + from discovery_rules import uncovered + all_paint=shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking']) + new_strokes=sum(uncovered(p,all_paint)for p in r['polygons']) + from interval_profiles import rectangle + centers=[e['center']for e in r['observations']] + gaps=shapely.union_all([rectangle(o,u,a+r['length']/2+.06,b-r['length']/2-.06,r['width'],r['offset'])for a,b in zip(centers,centers[1:])if b-a-r['length']>.12]) + false_gap_area=before.intersection(gaps).area + # Existing individual strokes are not 'new' merely because the latest fit + # shifted their outlines. Rebuild only actual missing paint or a proven + # vector connection across observed inter-stroke asphalt. + if not new_strokes and false_gap_area<.03:continue + if any(describe(poly(f))is None or describe(poly(f))['length']<.25 for f in residual):continue + ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode']) + if commit('periodic-row',ids,residual+generated,domain,ev,r['source_views'],dict(period_m=r['period'],dash_length_m=r['length'],newly_captured_strokes=new_strokes,normalized_strokes=len(generated),axis=u.tolist(),origin=o.tolist())):domains.append(domain) + +# Stage 3: false solid ends and missed tails. Each edit needs visible paint and +# the following dark interval in both mosaics, including at existing transitions. +for fid in list(current): + f=current.get(fid) + if f is None or not linear(f)or f['properties'].get('line_kind')=='dashed':continue + p=poly(f);seed=describe(p) + if seed is None or seed['length']<2.7:continue + readers,used=views.readers(seed['origin'],seed['axis']);changes=local_endpoints(seed,readers) + if not changes:continue + output=p;edit=[];ev=[] + for c in changes: + output=output.union(c['polygon'])if c['kind']=='extend-solid'else output.difference(c['domain']) + edit.append(c['domain']);ev.append({k:c[k]for k in ['kind','delta','evidence']}) + if output.geom_type!='Polygon' or not output.is_valid:continue + commit('solid-endpoints',[fid],[make(output,'solid',[fid])],shapely.union_all(edit),ev,used) + +# Reuse the qualified bounded duplicate detector with continuous mosaics. +# Only the common interval is removed; real twin paint ridges veto the cut. +from section_profiles import common_section,check_section +keepers=set();duplicate_candidates=0 +linear_ids=[fid for fid,f in current.items()if linear(f)] +for sid in sorted(linear_ids): + if sid not in current or sid in keepers:continue + for tid in sorted(linear_ids): + if sid==tid or sid not in current or tid not in current:continue + p,q=poly(current[sid]),poly(current[tid]) + if p.distance(q)>.66:continue + section=common_section(p,q) + if section is None:continue + duplicate_candidates+=1;readers,used=views.readers(section['origin'],section['axis']);kind,ev,ridges=check_section(section,readers) + diagnostics.append(dict(stage='duplicate',source_id=sid,target_id=tid,passed=kind is not None,kind=kind)) + if kind is None:continue + output=p.difference(section['cutter']);remaining=[make(pp,current[sid]['properties'].get('line_kind','solid'),[sid],role='unchanged-section')for pp in parts(output)if pp.area>1e-9] + proof=dict(kind=kind,views=ev,ridges=ridges,geometry=section['geometry']) + if commit('duplicate-section',[sid],remaining,section['cutter'],proof,used,dict(keeper_id=tid)): + keepers.add(tid);break + +# A zebra bar may also have been emitted as a narrow generic line. Reuse +# full-object two-view paint validation before removing its duplicate linear span. +from completion_profiles import bar_overlap,bar_supported +from discovery_evidence import glyph_views +bars={fid:f for fid,f in current.items()if f['properties'].get('subtype')=='crosswalk'} +bar_checks={};bar_candidates=0 +for sid in [fid for fid,f in current.items()if linear(f)]: + if sid not in current:continue + for bid,b in bars.items(): + p=poly(current[sid]);bp=poly(b) + if not p.intersects(bp):continue + cut=bar_overlap(p,bp) + if cut is None:continue + bar_candidates+=1 + if bid not in bar_checks:bar_checks[bid]=glyph_views(bp,views,None,None) + ev,names=bar_checks[bid];okay=bar_supported(ev) + diagnostics.append(dict(stage='bar-overlap',source_id=sid,bar_id=bid,passed=okay,views=ev)) + if not okay:continue + output=p.difference(cut);remaining=[make(pp,current[sid]['properties'].get('line_kind','solid'),[sid],role='unchanged-section')for pp in parts(output)if pp.area>1e-9] + if commit('crosswalk-line-duplicate',[sid],remaining,cut,ev,[{names[0]:1},{names[1]:1}],dict(keeper_id=bid)) :break + +# Stage 4: run the qualified whole-row assembly against the new graph. Known +# dashes and symbols remain barriers. All original fragments are fitted jointly. +barriers=shapely.union_all([protected]+[poly(f)for f in current.values()if linear(f)and f['properties'].get('line_kind')=='dashed']) +joinviews=GaussianViews(tiles,labels,low,high,barriers);initial={fid:poly(f)for fid,f in current.items()if linear(f)and f['properties'].get('line_kind')!='dashed'} +groups={fid:[fid]for fid in initial};considered=set() +while True: + choices=[];entries=sorted(groups) + for i,aid in enumerate(entries): + for bid in entries[:i]: + identity=tuple(sorted(groups[aid]+groups[bid])) + if identity in considered:continue + a,b=poly(current[aid]),poly(current[bid]) + if a.distance(b)>.56:continue + q=pair(a,b) + if q is not None:choices.append((abs(q['gap_m']),identity,aid,bid)) + accepted=False + for _,identity,aid,bid in sorted(choices): + considered.add(identity);r=fit_chain([initial[i]for i in identity]) + if r is None or r['polygon'].intersection(barriers).area>.005:continue + readers,used=joinviews.readers(r['origin'],r['axis']);okay,ev=check_chain(r,readers) + if not okay:continue + p=r['output_polygon'] + if p.intersection(barriers).area>.005:continue + f=make(p,'solid',[aid,bid],assembly_operation=r['operation']) + if commit('assembled-row',[aid,bid],[f],r['edit_domain'],ev,used,dict(assembly_operation=r['operation'],max_axis_displacement_m=r['max_axis_displacement_m'])): + groups.pop(aid);groups.pop(bid);groups[f['id']]=list(identity);accepted=True;break + if not accepted:break + if len(transactions)>1500:raise RuntimeError('Unbounded edits') + +result={**old,'features':list(current.values()),'completion_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False)) +(O/'completion-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'completion-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +counts=collections.Counter(r['kind']for r in transactions) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(counts),profiled_axes=len(seeds),periodic_families=len(family_rows),duplicate_candidates=duplicate_candidates,bar_candidates=bar_candidates,proposed_periodic_rows=len(proposals),newly_captured_strokes=sum(r.get('newly_captured_strokes',0)for r in transactions),normalized_strokes=sum(r.get('normalized_strokes',0)for r in transactions),endpoint_extensions=sum(e['kind']=='extend-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),endpoint_trims=sum(e['kind']=='trim-solid'for r in transactions if r['kind']=='solid-endpoints'for e in r['evidence']),before_linear_objects=sum(linear(f)for f in original.values()),after_linear_objects=sum(linear(f)for f in current.values()),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'completion-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/completion_pass/render_completion.py b/simulation/urban-plan-research/completion_pass/render_completion.py new file mode 100644 index 00000000..b516688d --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/render_completion.py @@ -0,0 +1,41 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'completion-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('completion-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='completion-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('completion-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'completion-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) +# Revisit every short-dash family shown in the prior delivery, using its stored +# bounds only for review framing; these bounds never enter the detector. +references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[] +for gi,rec in enumerate(references): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]): + frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640') + fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only')) +(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2)) diff --git a/simulation/urban-plan-research/completion_pass/test_completion.py b/simulation/urban-plan-research/completion_pass/test_completion.py new file mode 100644 index 00000000..e479aa4a --- /dev/null +++ b/simulation/urban-plan-research/completion_pass/test_completion.py @@ -0,0 +1,48 @@ +import runpy,json,numpy as np +from completion_profiles import families,slot,local_endpoints,describe,bar_overlap,bar_supported +from interval_profiles import rectangle +prior=runpy.run_path('/candidate/test_discovery.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +o=np.zeros(2);u=np.array([1.,0.]);seed=dict(origin=o,axis=u,period=1.,length=.5,width=.12) +def reader(centers,missing=None,offset=0,solid=False,underlay=0): + def read(xy): + x,y=xy.T;on=np.ones(len(x),bool)if solid else np.zeros(len(x),bool) + for c in centers:on|=abs(x-c)<=.25 + sig=(underlay+140*on)*np.exp(-.5*((y-offset)/.045)**2);rgb=np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8');valid=np.ones(len(x),bool) + if missing is not None:valid[(x>missing[0])&(x=0)&(x<=19.3);sig=140*on*np.exp(-.5*((y-center)/.045)**2) + return np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8'),np.ones(len(x),bool) +checks['local_end_ignores_distant_ridge']=any(c['sign']==1 and c['kind']=='trim-solid'for c in local_endpoints(long,[tail,tail])) +checks['local_endpoint_single_view_not_enough']=not local_endpoints(long,[tail]) +bar=rectangle(o,u,0,5,.5);line=rectangle(o,u,-2,7,.12);cut=bar_overlap(line,bar) +checks['same_paint_bar_duplicate_nominated']=cut is not None +checks['bar_cleanup_keeps_outer_line']=cut is not None and abs(line.difference(cut).area-(4-.05)*.12)<1e-8 +checks['crossing_lane_not_bar_duplicate']=bar_overlap(rectangle(np.array([2.,0]),np.array([0.,1.]),-2,2,.12),bar)is None +checks['adjacent_parallel_lane_not_bar_duplicate']=bar_overlap(rectangle(np.array([0.,.5]),u,0,5,.12),bar)is None +checks['uncertain_bar_cannot_remove_line']=not bar_supported([dict(valid=.9,support=1.,recall=1.)]*2) +checks['unpainted_bar_cannot_remove_line']=not bar_supported([dict(valid=1.,support=.3,recall=1.)]*2) +checks['single_bar_render_insufficient']=not bar_supported([dict(valid=1.,support=1.,recall=1.)]) +checks['outside_bar_paint_does_not_veto_internal_dedup']=bar_supported([dict(valid=1.,support=1.,recall=.3)]*2) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/completion-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed'] diff --git a/simulation/urban-plan-research/component_pass/README.md b/simulation/urban-plan-research/component_pass/README.md new file mode 100644 index 00000000..90e253ca --- /dev/null +++ b/simulation/urban-plan-research/component_pass/README.md @@ -0,0 +1,83 @@ +# Whole-symbol component pass + +Offline Gaussian-only refinement of bicycles, arrow symbols and yellow zigzags. +This module adds evidence-supported presets to an accepted full-map artifact. +It does not replace the road, pedestrian, façade, crosswalk or linear-marking +passes. Input review decisions remain part of the baseline provenance. + +## Method + +1. Reuse the hashed, whole-scene SAM3 symbol masks and registered Gaussian + orthophoto patches from `symbol_pass`. Model masks supply a class and search + region; they are not the final outline. +2. Extract white-paint components at two metric scales with OpenCV morphology. + Fit the existing licensed SVG presets with SciPy multistart optimization; + evaluate straight, turning and compound arrows and bicycle symbols. +3. Check the complete preset against two mosaics whose source tiles are selected + geometrically, never by favorable paint score. Test positive paint, negative + space, head/tail/branch support and continuation beyond both ends. Every + completely observed view must explain the connected paint object: a head + detached by weak contrast in one view cannot pass if another view shows the + remaining curved arrow. Missing coverage is explicitly unknown. +4. For bicycle paint only, a vehicle segmentation label can be overridden when + the original context render agrees with its matching ground render in + expected depth (0.12 m tolerance), with strong alpha in both. This is Gaussian + surface evidence; no point cloud supplies observations or geometry. +5. Fit zigzags from the cached whole-scene chromatic proposals. Verify yellow + paint separately from white arrows. A finite three-leg pattern requires + strong support on every leg, low background paint and consistent available + views. Extend a pattern only where additional legs have image support. +6. Lift accepted clean presets onto the Gaussian-derived height field. Replay + every transaction, retain input hashes, and verify all unreplaced features + byte-for-byte as JSON records. A fully verified arrow can replace old linear + fragments contained in its outline (98% within a 0.12 m tolerance, at least + 50% actual overlap). A crossing line, neighboring stripe or other symbol + vetoes replacement; every removed fragment is recorded and replayed. Preserve prior observation-review provenance. + +`component_rules.py` and `component_zigzag_rules.py` hold shared thresholds. +The refinement code accepts no scene-specific polygon, coordinate exemption, +manual ROI or geographic identity. Scene identity in reports is descriptive. +Parameters were developed and regression-tested on three available scenes; +performance on an unseen scan is not yet established. + +## Execution and dependencies + +`bundle.json` maps the complete flat execution directory back to canonical +source files and pins their SHA-256 values, inherited wheels and the reference +execution snapshot. Existing runtime libraries include NumPy, OpenCV, SciPy, +Shapely, Pillow and scikit-image. Existing SAM3 outputs and model provenance +come from `symbol_pass`; no additional model weights are introduced here. +`bicycle_artwork.py` and `road_glyph_presets.py` retain their original artwork +attribution and licence metadata (MajorAlexey, CC BY-SA 4.0). + +Execute on Worker 006, using the existing simulation resource reservation and +bounded container runner. This is an offline refinement package; the default +interactive recalculation button does not yet reproduce this entire research +chain. The qualified resulting maps are imported through the canonical +`publish_qualified_urban_maps.py` plan/apply/readback path. + +Required mounts follow the preceding research passes: `/candidate`, `/out`, +`/fullplan` (current accepted baseline), `/symbolplan`, `/assemblyplan`, +`/catalogplan`, `/searchplan`, `/coverage_base`, `/evidence_plan`, `/ortho`, +`/survey`, `/input` and `/multiview`. Read the qualification runner for exact +input paths and receipts. Do not substitute a historical baseline when a later +review has rejected a feature. + +Order: `test_components.py`, `refine_components.py`, `refine_zigzags.py`, +`audit_components.py`, `render_components.py`, `render_plan.py`. Freeze the +entire bundle once before processing all scenes. Human visual review is an +acceptance gate, not a coordinate-dependent processing input. Review every +addition before publication, including rejected intermediate versions. + +Private receipts, raw inputs and visual evidence are under +`.runtime/simulation-qualifications/component-pass-20261014/operator`. +The final `verification.json` and publication receipts define delivered counts; +intermediate hypotheses must not be presented as accepted results. + +## Limits + +The class catalogue and cached semantic proposals still limit recall. Strongly +worn paint, occlusion and incomplete Gaussian coverage can leave symbols +unresolved. Presets regularize shape; neither this fit nor its support scores +establish survey accuracy or GOST compliance. Published objects remain +`observation-only`, with route permission unassigned and confidence unassessed. diff --git a/simulation/urban-plan-research/component_pass/audit_components.py b/simulation/urban-plan-research/component_pass/audit_components.py new file mode 100644 index 00000000..e45739db --- /dev/null +++ b/simulation/urban-plan-research/component_pass/audit_components.py @@ -0,0 +1,34 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape,LineString +from shapely.affinity import rotate,translate +from catalog_templates import bicycle +from fragment_templates import template +from component_rules import VERSION,POLICY,accept_symbol +from component_conflicts import symbol_replacements,FRAGMENT_POLICY +from component_zigzag_rules import accept_zigzag +from discovery_rules import uncovered +O=Path('/out');I=Path('/symbolplan');sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest();base=Path('/fullplan/full-map.json');old=json.loads(base.read_text());new=json.loads((O/'full-map.json').read_text());rows=json.loads((O/'component-rows.json').read_text());report=json.loads((O/'component-report.json').read_text());semantic=json.loads((I/'symbol-semantics.json').read_text());patches=json.loads((I/'symbol-patches.json').read_text());current={f['id']:f for f in old['features']} +poly=lambda f:shapely.force_2d(shape(f['geometry'])) +checks=dict(transaction_replay=True,semantic_trace=True,image_support=True,clean_preset_geometry=True,no_foreign_overlap=True,contained_fragment_replacement=True) +for r in rows: + checks['transaction_replay']&=r['source_ids']==[f['id']for f in r['before']]and len(r['after'])==1 and r['output_ids']==[r['after'][0]['id']] + for f in r['before']:checks['transaction_replay']&=current.pop(f['id'],None)==f + f=r['after'][0];p=f['properties'];q=poly(f);kind=p['subtype'];checks['transaction_replay']&=f['id']not in current and p['class']=='road_marking'and p['method']==VERSION + if r['kind']=='assembled-symbol': + replacements=symbol_replacements(q,kind,[*current.values(),*r['before']]) + checks['contained_fragment_replacement']&=replacements is not None and {v['id']for v in replacements}==set(r['source_ids']) + x=p['template_parameters'];sem=next(s for s in semantic['records']if s['id']==r['patch']);path=I/'symbol-masks'/(r['patch']+'.npz');checks['semantic_trace']&=sha(path)==sem['sha256'] + with np.load(path)as z:score=max(float(z['scores'][i])for i in r['masks']);classes={int(z['classes'][i])for i in r['masks']} + checks['semantic_trace']&=score==r['semantic_score']==p['semantic_score']and classes==({0}if kind=='bicycle'else{1}) + checks['image_support']&=accept_symbol(r['evidence'],score,r['semantic_containment'],r['fit_score'],kind)and p['lane_context']['passed'] + expected=bicycle(x)if kind=='bicycle'else translate(rotate(template(kind,x[3],x[4],x[5]),x[2],origin=(0,0),use_radians=True),x[0],x[1]) + else: + checks['transaction_replay']&=r['kind']=='assembled-zigzag'and all(v['properties'].get('subtype')=='zigzag'for v in r['before']) + checks['image_support']&=bool(accept_zigzag(r['evidence']['whole'],r['evidence']['legs'],r['fit'])) + expected=LineString(p['vertices']).buffer(p['width_m']/2,cap_style=2,join_style=2) + checks['clean_preset_geometry']&=q.symmetric_difference(expected).area<1e-7 + existing=shapely.union_all([poly(v)for v in current.values()if v['properties']['class']=='road_marking']);checks['no_foreign_overlap']&=q.intersection(existing).area<=.005;current[f['id']]=f +features={f['id']:f for f in new['features']};removed={i for row in rows for i in row['source_ids']};checks['unreplaced_features_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed);checks['replay_matches_map']=features==current;checks['unique_ids']=len(features)==len(new['features']);checks['finite_valid_geometry']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']);checks['same_policy']=report['fragment_policy']==FRAGMENT_POLICY and report['policy']==POLICY and report['policy_version']==new['component_refinement']==VERSION;checks['all_operations_counted']=len(rows)==report['changed_segments'];checks['baseline_pinned']=sha(base)==report['baseline_sha256'];checks['semantic_inputs_pinned']=sha(I/'symbol-patches.json')==semantic['patch_manifest_sha256']==report['patch_manifest_sha256']and sha(I/'symbol-semantics.json')==report['semantic_sha256'];checks['crosswalk_audit_preserved']=(O/'crosswalk-standard-check.json').read_bytes()==(I/'crosswalk-standard-check.json').read_bytes();checks['prior_observation_review_preserved']=old.get('observation_review')==new.get('observation_review') +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=sha(O/'full-map.json'),complete_recall_measured=False,metric_accuracy_measured=False) +(O/'component-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/component_pass/bundle.json b/simulation/urban-plan-research/component_pass/bundle.json new file mode 100644 index 00000000..d8a3c324 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/bundle.json @@ -0,0 +1,422 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "files": { + "assembly_evidence.py": "assembly_pass/assembly_evidence.py", + "assembly_rules.py": "assembly_pass/assembly_rules.py", + "assembly_templates.py": "assembly_pass/assembly_templates.py", + "assembly_zigzag.py": "assembly_pass/assembly_zigzag.py", + "audit_assembly.py": "assembly_pass/audit_assembly.py", + "audit_assembly_joins.py": "assembly_pass/audit_assembly_joins.py", + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_catalog.py": "catalog_pass/audit_catalog.py", + "audit_completion.py": "completion_pass/audit_completion.py", + "audit_components.py": "component_pass/audit_components.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_corridor.py": "corridor_pass/audit_corridor.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_search.py": "search_pass/audit_search.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_symbols.py": "symbol_pass/audit_symbols.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "bicycle_artwork.py": "catalog_pass/bicycle_artwork.py", + "catalog_context.py": "catalog_pass/catalog_context.py", + "catalog_dependencies.py": "catalog_pass/catalog_dependencies.py", + "catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py", + "catalog_evidence.py": "symbol_pass/catalog_evidence.py", + "catalog_rules.py": "catalog_pass/catalog_rules.py", + "catalog_templates.py": "catalog_pass/catalog_templates.py", + "catalog_zigzag.py": "catalog_pass/catalog_zigzag.py", + "completion_profiles.py": "completion_pass/completion_profiles.py", + "component_arrows.py": "component_pass/component_arrows.py", + "component_bicycle.py": "component_pass/component_bicycle.py", + "component_conflicts.py": "component_pass/component_conflicts.py", + "component_evidence.py": "component_pass/component_evidence.py", + "component_mosaics.py": "component_pass/component_mosaics.py", + "component_rules.py": "component_pass/component_rules.py", + "component_surface.py": "component_pass/component_surface.py", + "component_targets.py": "component_pass/component_targets.py", + "component_zigzag_rules.py": "component_pass/component_zigzag_rules.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "coordinate_cache.py": "orthophoto/coordinate_cache.py", + "corridor_profiles.py": "search_pass/corridor_profiles.py", + "coverage_evidence.py": "corridor_pass/coverage_evidence.py", + "coverage_plan.py": "corridor_pass/coverage_plan.py", + "diagnose_assembly.py": "assembly_pass/diagnose_assembly.py", + "diagnose_components.py": "component_pass/diagnose_components.py", + "diagnose_corridor.py": "corridor_pass/diagnose_corridor.py", + "diagnose_coverage.py": "corridor_pass/diagnose_coverage.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_assembly.py": "assembly_pass/extract_assembly.py", + "extract_catalog.py": "catalog_pass/extract_catalog.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "extract_search.py": "search_pass/extract_search.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "inspect_bicycles.py": "catalog_pass/inspect_bicycles.py", + "inspect_catalog.py": "catalog_pass/inspect_catalog.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "join_assembly.py": "assembly_pass/join_assembly.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "mapping.py": "corridor_pass/mapping.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "ortho_terrain.py": "orthophoto/ortho_terrain.py", + "paint_channels.py": "component_pass/paint_channels.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "prepare_symbols.py": "symbol_pass/prepare_symbols.py", + "refine_assembly.py": "assembly_pass/refine_assembly.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_catalog.py": "catalog_pass/refine_catalog.py", + "refine_completion.py": "completion_pass/refine_completion.py", + "refine_components.py": "component_pass/refine_components.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_corridor.py": "corridor_pass/refine_corridor.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_search.py": "search_pass/refine_search.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_symbols.py": "symbol_pass/refine_symbols.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "refine_zigzags.py": "component_pass/refine_zigzags.py", + "render_assembly.py": "assembly_pass/render_assembly.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_catalog.py": "catalog_pass/render_catalog.py", + "render_completion.py": "completion_pass/render_completion.py", + "render_components.py": "component_pass/render_components.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_corridor.py": "corridor_pass/render_corridor.py", + "render_coverage.py": "corridor_pass/render_coverage.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_hypotheses.py": "component_pass/render_hypotheses.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "catalog_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_search.py": "search_pass/render_search.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_symbols.py": "symbol_pass/render_symbols.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "review_symbols.py": "symbol_pass/review_symbols.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "corridor_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "search_rules.py": "search_pass/search_rules.py", + "search_views.py": "search_pass/search_views.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "semantic_symbols.py": "symbol_pass/semantic_symbols.py", + "symbol_evidence.py": "symbol_pass/symbol_evidence.py", + "symbol_rules.py": "symbol_pass/symbol_rules.py", + "test_assembly.py": "assembly_pass/test_assembly.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_catalog.py": "catalog_pass/test_catalog.py", + "test_completion.py": "completion_pass/test_completion.py", + "test_components.py": "component_pass/test_components.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_corridor.py": "corridor_pass/test_corridor.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_search.py": "search_pass/test_search.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_symbols.py": "symbol_pass/test_symbols.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py", + "validation.py": "corridor_pass/validation.py", + "zigzag_evidence.py": "component_pass/zigzag_evidence.py", + "zigzag_mosaics.py": "component_pass/zigzag_mosaics.py" + }, + "reference_qualification": "component-pass-20261014", + "source_snapshot": "702597dcd1d61ecbb53d", + "source_sha256": { + "assembly_evidence.py": "0fda82c403f9734ea0b0267504ac82437092d410882dc21417a492de9509c09b", + "assembly_rules.py": "04798c28e0daccc8be5fb045cc736160721308f7c41189f287b97a509999ddbf", + "assembly_templates.py": "41ec0428032ae328d5f46c34702d5b0be43f724e5821278e745554c72326d402", + "assembly_zigzag.py": "dbee99c505381fbdccbecec0817e0ec4e028ac1eb475124829cd58811251b9ca", + "audit_assembly.py": "8defc22e391c330962c503b27c49b9d13cecee90b0170dab1b8372858bda3638", + "audit_assembly_joins.py": "e8a3ded181b69961c8a0a5f88e171ff5ada82f0a43e55c217bb40734e411c094", + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2", + "audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d", + "audit_components.py": "b472856305839483fcf806eb76a29b46650f2188b1e0cf0f94afdc250eb1fa28", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_symbols.py": "105c7a7939c43643299e071d94f5b1e4acc45a29d8b45482a3d7fabc9508ecea", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f", + "catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80", + "catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca", + "catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a", + "catalog_evidence.py": "7f9fb171776faf1181705826bec206882aea13eded8664d8e3e6dfd09031ec95", + "catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb", + "catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092", + "catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f", + "completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786", + "component_arrows.py": "cb6cfe2f2007e5de430352138d8973959bc2d903a3cd74a984d9f4a10adbb5be", + "component_bicycle.py": "854388ce45520abb82d8f61d1195a50525e6326c315feee5bcb84b66163dc2fe", + "component_conflicts.py": "dccc333197b47bbbf211212b38d5a0018c8bae5f403fed1cbe3e22be0a81967e", + "component_evidence.py": "cd2360a061fd340f257da917d4c9d16c95a188604f72a347ea25b5cbc6e76566", + "component_mosaics.py": "06140a2682448b14cebd30989944537c2412cffa3ae5fae5c0549e4baf11dd53", + "component_rules.py": "910be55c56c3b406e1727339b1054ee0693a5d7c4ec46cb3cfa8015a34eb0553", + "component_surface.py": "e425be65d184d474c5485160547f122291529622244da73ca484469ffd994d69", + "component_targets.py": "1719de92d38ff15377276e7b471501cf5ed21392a14113d90537eafea735e6c2", + "component_zigzag_rules.py": "76566a1ec3b90c7d3abe7dd96054351e3fbb41ac1117f2b1eb09ce33c716da98", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4", + "corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672", + "coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497", + "coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda", + "diagnose_assembly.py": "44ef17e6bdecc9285ae8150ccb5c4dd397006381b34b013ebd3e2ed6c2b34bbc", + "diagnose_components.py": "b9653a2b642c1399dd3b6388cd40a148cb4cb81f665fad3bf993d950a64579f8", + "diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6", + "diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "extract_assembly.py": "d2f1cd5a1fc03b95496b32e024452c3e8ba489a06299a6cba967d4d18a5c3b33", + "extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb", + "inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "join_assembly.py": "293fd78d10f0ba13b1339a69d737c3f96ef003ea3f6dd63fdf02d14c40fa324f", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213", + "paint_channels.py": "95895f19638835c9e9564633fc0dacdd6aeae12a5786d6a44f046c91c2d16917", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "prepare_symbols.py": "59d0f7da37f4f119b0bfa996dfe4638999bf1bce575415db087fdb55d64a144a", + "refine_assembly.py": "0da00d12e4bda06760a3fc78fcddb6875012edc046e9f83a00074846031b4939", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb", + "refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1", + "refine_components.py": "57eeb116e3c61ee42d30d3d6bc557e33d2b2d8ee24910584487bec5d34b69ef5", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_symbols.py": "c210c825edb1d2469b27afac6292f911df8351e92c8f47d0b5d05f99a229a95a", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "refine_zigzags.py": "8fad49227ca4fdaf72fa46a9050aaa39d699aa2620ffc765ea829e2ecb77d967", + "render_assembly.py": "b8471dceb42be102eeb1918eb7950e038d3fc9e0ebab0a3b01b3aaea8be710fa", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b", + "render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7", + "render_components.py": "2115f348228ffcbb21ac1a80c1e8c37b082af8be09ca2a182028aa1ea0a7a222", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f", + "render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "render_hypotheses.py": "d7ea4b19409a7b5c78c8a01ed9c190069cc109e4bfa854c77672ed1d1e64ba56", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_symbols.py": "ae3bd83870aa435d2051282b65fd3015eee8c11e92831062328e39482de76d5b", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "review_symbols.py": "264c92625648cf1930753add51496c28ef645a481e5cf13993ae0cf758d5df30", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41", + "search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "semantic_symbols.py": "0665fa1ba0dd08bd29b762a09fb2d03b31a1894ff0731353c2f847fb170c5658", + "symbol_evidence.py": "2d643c9756660bd33ad208ffbe960283feb3aa12352399b6df6f81c0b507e3a2", + "symbol_rules.py": "c349ee11f5c33da7310dcf6e530d988858243c5e99ad8072818d78802ea59527", + "test_assembly.py": "80510625a71ea9fc04add883d9a7e40a3bfdcac4251bd702b5507ce76f9bba8f", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4", + "test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1", + "test_components.py": "71c48f0b6afda80713aef4ee6547acc1995f0dd07d901ee84a4254bee0cc1168", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_symbols.py": "63a429e8d3324b87075bcb2a2c9902f35c45f1aceff5b46c260aec9bed666481", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e", + "validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c", + "zigzag_evidence.py": "978bda848dc7dc85268e2696b918eb6f86c7377c7e9da7c5e4b875815daefa0d", + "zigzag_mosaics.py": "b2703eb159e92680df15d4ed80cd47e55a9168ab3f1703f50faf843eca5262b5" + }, + "external_dependencies": { + "packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759", + "scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660", + "imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf", + "networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", + "lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc", + "tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd" + }, + "external_evidence_assets": { + "review-font.ttf": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9" + }, + "execution_snapshot_sha256": { + "audit_components.py": "b472856305839483fcf806eb76a29b46650f2188b1e0cf0f94afdc250eb1fa28", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "packaging-24.2-py3-none-any.whl": "09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759", + "catalog_dependency_pins.py": "93ed9007288440620b8339043f1d5ae74684e39e7c3bd50d94d24f6cf29c9f3a", + "assembly_rules.py": "04798c28e0daccc8be5fb045cc736160721308f7c41189f287b97a509999ddbf", + "test_components.py": "71c48f0b6afda80713aef4ee6547acc1995f0dd07d901ee84a4254bee0cc1168", + "catalog_rules.py": "ed0f8e838908bcea9ac1ee15fe13d1b23ac29981428ea6a4bdc097c0226db3cb", + "render_hypotheses.py": "d7ea4b19409a7b5c78c8a01ed9c190069cc109e4bfa854c77672ed1d1e64ba56", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "search_rules.py": "ca3cab6d24f31460d9912c351c166d89fb1c3b21df620ba1d847543bd7a71f41", + "component_zigzag_rules.py": "76566a1ec3b90c7d3abe7dd96054351e3fbb41ac1117f2b1eb09ce33c716da98", + "render_catalog.py": "58ecb30ac8ddffd1489c93361dc6678c82e4dbbfbe8a6e851a1be395ee40db1b", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "prepare_symbols.py": "59d0f7da37f4f119b0bfa996dfe4638999bf1bce575415db087fdb55d64a144a", + "test_catalog.py": "91a8fdbc330cecd5bc354406012852cc46245baf99ba8befdaac164f6b79c1c4", + "render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "audit_symbols.py": "105c7a7939c43643299e071d94f5b1e4acc45a29d8b45482a3d7fabc9508ecea", + "catalog_zigzag.py": "2e6a804cd14440afaf27bd0f0c2123afc7bf3ea1c58cd0d49293049f1f3b498f", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_symbols.py": "c210c825edb1d2469b27afac6292f911df8351e92c8f47d0b5d05f99a229a95a", + "coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497", + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "component_targets.py": "1719de92d38ff15377276e7b471501cf5ed21392a14113d90537eafea735e6c2", + "refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1", + "zigzag_mosaics.py": "b2703eb159e92680df15d4ed80cd47e55a9168ab3f1703f50faf843eca5262b5", + "test_search.py": "fc3d874c8a6639bfa007eb8fa4a869e270bddafe317868bed29450c6024f8756", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "scikit_image-0.24.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl": "8579bda9c3f78cb3b3ed8b9425213c53a25fa7e994b7ac01f2440b395babf660", + "render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f", + "bicycle_artwork.py": "2e5220e6e82024c683b65c81695b53fa3070d58eed89d61f5cbda41f6c3c554f", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "component_mosaics.py": "06140a2682448b14cebd30989944537c2412cffa3ae5fae5c0549e4baf11dd53", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703", + "render_components.py": "2115f348228ffcbb21ac1a80c1e8c37b082af8be09ca2a182028aa1ea0a7a222", + "audit_search.py": "0de9929d983c97045444131b9255ec4c256ae652b6adb82551e42b94c4bec0eb", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "imageio-2.36.1-py3-none-any.whl": "20abd2cae58e55ca1af8a8dcf43293336a59adf0391f1917bf8518633cfc2cdf", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "refine_assembly.py": "0da00d12e4bda06760a3fc78fcddb6875012edc046e9f83a00074846031b4939", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e", + "component_rules.py": "910be55c56c3b406e1727339b1054ee0693a5d7c4ec46cb3cfa8015a34eb0553", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "semantic_symbols.py": "0665fa1ba0dd08bd29b762a09fb2d03b31a1894ff0731353c2f847fb170c5658", + "audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "audit_assembly_joins.py": "e8a3ded181b69961c8a0a5f88e171ff5ada82f0a43e55c217bb40734e411c094", + "diagnose_assembly.py": "44ef17e6bdecc9285ae8150ccb5c4dd397006381b34b013ebd3e2ed6c2b34bbc", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "extract_search.py": "09b3c0c65d33fdd5025e3436fb1bd5df67d1e359b507f4fae74a7e61754fc92c", + "refine_zigzags.py": "8fad49227ca4fdaf72fa46a9050aaa39d699aa2620ffc765ea829e2ecb77d967", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "assembly_evidence.py": "0fda82c403f9734ea0b0267504ac82437092d410882dc21417a492de9509c09b", + "search_views.py": "8a123558dbef184fc85a92c9547c19644d14681329dbbd0cfeac0032bbd102be", + "inspect_bicycles.py": "e12964f244645b7a4b2bdb0da5d2bb90e7d49dc35bf2f66c4a8466fabc6836bb", + "paint_channels.py": "95895f19638835c9e9564633fc0dacdd6aeae12a5786d6a44f046c91c2d16917", + "completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786", + "diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "component_conflicts.py": "dccc333197b47bbbf211212b38d5a0018c8bae5f403fed1cbe3e22be0a81967e", + "component_arrows.py": "cb6cfe2f2007e5de430352138d8973959bc2d903a3cd74a984d9f4a10adbb5be", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "symbol_rules.py": "c349ee11f5c33da7310dcf6e530d988858243c5e99ad8072818d78802ea59527", + "catalog_dependencies.py": "d6407445db28f6f15201f4ec09e3401141fca90e11a9cef52392f88175634fca", + "render_search.py": "5655641df20c2e4f0849bb35ff4029d806554cc7d3b696d26378ad9d880d0491", + "component_evidence.py": "cd2360a061fd340f257da917d4c9d16c95a188604f72a347ea25b5cbc6e76566", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "networkx-3.4.2-py3-none-any.whl": "df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5f", + "coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4", + "refine_catalog.py": "eeeee4d59066579c1fa8708a1be9d999a481f8f8daf05ec01704897252cc66cb", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "review_symbols.py": "264c92625648cf1930753add51496c28ef645a481e5cf13993ae0cf758d5df30", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "catalog_templates.py": "05577c611ce5ffa2c21d0f608e728eca13009c994e26913b29f39fdcf584c092", + "render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7", + "render_symbols.py": "ae3bd83870aa435d2051282b65fd3015eee8c11e92831062328e39482de76d5b", + "test_symbols.py": "63a429e8d3324b87075bcb2a2c9902f35c45f1aceff5b46c260aec9bed666481", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "render_plan.py": "9e702d51c6be09caa456d8e528bd62bc9ec238ca3689a99f38b414dafc193f66", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "audit_catalog.py": "19d5f0f156c0f90d2e1e2548fee99eee521b76e7152f0b53ae12b43ed48553b2", + "extract_assembly.py": "d2f1cd5a1fc03b95496b32e024452c3e8ba489a06299a6cba967d4d18a5c3b33", + "inspect_catalog.py": "322aec8f233009eb42703132b220e1e216f8dc8b59aa6bbd27244067e651727d", + "refine_components.py": "57eeb116e3c61ee42d30d3d6bc557e33d2b2d8ee24910584487bec5d34b69ef5", + "zigzag_evidence.py": "978bda848dc7dc85268e2696b918eb6f86c7377c7e9da7c5e4b875815daefa0d", + "assembly_templates.py": "41ec0428032ae328d5f46c34702d5b0be43f724e5821278e745554c72326d402", + "assembly_zigzag.py": "dbee99c505381fbdccbecec0817e0ec4e028ac1eb475124829cd58811251b9ca", + "ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "test_assembly.py": "80510625a71ea9fc04add883d9a7e40a3bfdcac4251bd702b5507ce76f9bba8f", + "refine_search.py": "113e8cee4f26d1f6b0bcce516388d046ced0523598ddf7f6f4e4dc365a0d9859", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "catalog_evidence.py": "7f9fb171776faf1181705826bec206882aea13eded8664d8e3e6dfd09031ec95", + "render_assembly.py": "b8471dceb42be102eeb1918eb7950e038d3fc9e0ebab0a3b01b3aaea8be710fa", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "review-font.ttf": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "extract_catalog.py": "7c3b7de0291f52d9f37590b438d1abb7e37b36665cfb5e9ba4698b78a8f42574", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "lazy_loader-0.4-py3-none-any.whl": "342aa8e14d543a154047afb4ba8ef17f5563baad3fc610d7b15b213b0f119efc", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1", + "diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6", + "diagnose_components.py": "b9653a2b642c1399dd3b6388cd40a148cb4cb81f665fad3bf993d950a64579f8", + "catalog_context.py": "f2e654ea068a758be1f929299786559f02672898047893cdc20e6f1cb204bb80", + "join_assembly.py": "293fd78d10f0ba13b1339a69d737c3f96ef003ea3f6dd63fdf02d14c40fa324f", + "component_surface.py": "e425be65d184d474c5485160547f122291529622244da73ca484469ffd994d69", + "corridor_profiles.py": "967902dae9137ceddb05708acbb6a7cc1e06977c6d064787a1a651422d2e5672", + "audit_assembly.py": "8defc22e391c330962c503b27c49b9d13cecee90b0170dab1b8372858bda3638", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "symbol_evidence.py": "2d643c9756660bd33ad208ffbe960283feb3aa12352399b6df6f81c0b507e3a2", + "component_bicycle.py": "854388ce45520abb82d8f61d1195a50525e6326c315feee5bcb84b66163dc2fe", + "audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d", + "tifffile-2024.9.20-py3-none-any.whl": "c54dc85bc1065d972cb8a6ffb3181389d597876aa80177933459733e4ed243dd", + "validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c", + "refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f" + } +} diff --git a/simulation/urban-plan-research/component_pass/component_arrows.py b/simulation/urban-plan-research/component_pass/component_arrows.py new file mode 100644 index 00000000..5f810893 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_arrows.py @@ -0,0 +1,41 @@ +"""Multi-start registration of existing arrow artwork, with whole-object fit.""" +import numpy as np,cv2,shapely +from shapely.affinity import rotate,translate +from scipy.optimize import minimize +from fragment_templates import template + +def fit_arrows(p, *, kinds=None, template_fn=template): + if p.is_empty or p.area<.25:return [] + xy=shapely.get_coordinates(p);rect=cv2.minAreaRect(xy.astype('float32'));L,W=sorted(rect[1],reverse=True) + if not(1.2=quality(x)[2]else x;q=quality(z) + if q[0]>=.80 and q[1]>=.80 and q[2]>=.76:fits.append(dict(polygon=polygon(z),kind=kind,parameters=from_center(z).tolist(),support=q[0],recall=q[1],score=q[2])) + return sorted(fits,key=lambda x:-x['score']) diff --git a/simulation/urban-plan-research/component_pass/component_bicycle.py b/simulation/urban-plan-research/component_pass/component_bicycle.py new file mode 100644 index 00000000..3d74bc09 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_bicycle.py @@ -0,0 +1,52 @@ +"""OpenCV raster / SciPy registration with global orientation initialization.""" +import numpy as np, cv2, shapely +from shapely.geometry import Polygon +from scipy.optimize import minimize +from catalog_templates import bicycle + +def fit_bicycle(p,all_hypotheses=False): + if p.is_empty or p.area<.10:return None + rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6) + if not(1.=quality(from_center(x))[2]else x);q=quality(z) + hypothesis=dict(polygon=bicycle(z),score=q[2],support=q[0],recall=q[1],parameters=z.tolist());hypotheses.append(hypothesis) + return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else max(hypotheses,key=lambda x:x['score'],default=None) diff --git a/simulation/urban-plan-research/component_pass/component_conflicts.py b/simulation/urban-plan-research/component_pass/component_conflicts.py new file mode 100644 index 00000000..92d17962 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_conflicts.py @@ -0,0 +1,30 @@ +"""Whole symbols may replace their own previously extracted linear fragments. + +A neighboring line, crossing stripe or existing symbol must never be consumed. +This rule is applied only after the complete symbol passed image evidence. +""" +import shapely +from shapely.geometry import shape + +FRAGMENT_POLICY = dict(min_inside_fraction=.98, min_overlap_fraction=.50, + containment_tolerance_m=.12, overlap_area_tolerance_m2=.005) + +def symbol_replacements(polygon, kind, features): + replacements = [] + for feature in features: + props = feature['properties'] + if props['class'] != 'road_marking': + continue + geometry = shapely.force_2d(shape(feature['geometry'])) + intersection = polygon.intersection(geometry).area + if intersection <= FRAGMENT_POLICY['overlap_area_tolerance_m2']: + continue + if kind == 'bicycle' or props.get('subtype') != 'linear_marking': + return None + if geometry.area <= 0 or intersection / geometry.area < FRAGMENT_POLICY['min_overlap_fraction']: + return None + inside = polygon.buffer(FRAGMENT_POLICY['containment_tolerance_m']).intersection(geometry).area / geometry.area + if inside < FRAGMENT_POLICY['min_inside_fraction']: + return None + replacements.append(feature) + return replacements diff --git a/simulation/urban-plan-research/component_pass/component_evidence.py b/simulation/urban-plan-research/component_pass/component_evidence.py new file mode 100644 index 00000000..810f906e --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_evidence.py @@ -0,0 +1,61 @@ +from paint_channels import paint_mask +import numpy as np,cv2,shapely +from discovery_rules import POLICY +def glyph_score(rgb,allowed,points,polygon,cell=.04,kind=None,parameters=None,observed=None,paint_override=None,connectivity_open_m=0.): + """Check positive paint, unpainted negative space, and unexplained pixels.""" + h,w=allowed.shape;observed=np.ones((h,w),bool)if observed is None else observed;gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY) + bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19))) + hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV) + paint=paint_mask(rgb,channel='white',observed=observed)if paint_override is None else paint_override + target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w) + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0 + wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0 + region=shapely.contains_xy(polygon.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(h,w) + negative=region&~wide + result=dict(valid=float(allowed[region&observed].mean())if (region&observed).any()else 0., + support=float(near[target&observed].mean())if (target&observed).any()else 0., + recall=float(wide[paint®ion&allowed].mean())if (paint®ion&allowed).any()else 0., + negative_paint=float(paint[negative&allowed].mean())if (negative&allowed).any()else 1.) + # A complete template must explain the connected paint object, not just + # one head cut out of a longer curved arrow. Unfinished image edges veto it. + connectivity=paint.astype('uint8') + if connectivity_open_m>0: + k=max(3,int(round(connectivity_open_m/cell))//2*2+1) + connectivity=cv2.morphologyEx(connectivity,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k))) + count,components=cv2.connectedComponents(connectivity,8) + touching=set(np.unique(components[target&near]))-{0} + connected=np.isin(components,list(touching))&observed + result['connected_recall']=float(wide[connected].mean())if connected.any()else 0. + result['connected_at_window_edge']=bool(connected[0].any()or connected[-1].any()or connected[:,0].any()or connected[:,-1].any()) + if kind is not None and parameters is not None: + px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w) + regions=[('head',t>L*.80),('tail',tW*.24)) + result['parts']=[] + for name,where in regions: + select=target&where;coverage=float(observed[select].mean())if select.any()else 0.;select=select&observed + result['parts'].append(dict(part=name,coverage=coverage,valid=float(allowed[select].mean())if select.any()else 0.,support=float(near[select].mean())if select.any()else 0.)) + result['ends']=[] + for name,interior,exterior in [('tail',t-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t0 + px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w) + flank=(t>L*.80)&(t=20)&(uv.max(1)<1180) + planar=planar_vehicle_clearance(points,views)if allow_pedestrian else np.zeros(len(points),bool) + owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1]) + for rank in [0,1]: + colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={};alpha_good=np.zeros(len(points),bool);vehicle_good=alpha_good.copy();surface_good=alpha_good.copy() + for i in np.unique(owners[:,rank]): + if i<0:continue + select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5 + def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]) + colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&((read(vehicle,uv).ravel()<.2)|planar[select])&(np.isin(sample(views.labels,points[select],views.low,views.high),[1,2]if allow_pedestrian else[1]));covered[select]=True;alpha_good[select]=read(g['alpha'].astype('float32'),uv).ravel()>=.65;vehicle_good[select]=read(vehicle,uv).ravel()<.2;surface_good[select]=np.isin(sample(views.labels,points[select],views.low,views.high),[1,2]if allow_pedestrian else[1]) + if target[select].any():names.add(name);source_counts[name]=int(target[select].sum()) + rgb=colors.reshape(len(yy),len(xx),3) + paint=paint_mask(rgb,channel='white',observed=covered.reshape(len(yy),len(xx)),calibration=allowed.reshape(len(yy),len(xx))if calibrate_ground else None) + score=glyph_score(rgb,allowed.reshape(len(yy),len(xx)),points,p,kind=kind,parameters=parameters,observed=covered.reshape(len(yy),len(xx)),paint_override=paint,connectivity_open_m=connectivity_open_m) + rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV) + bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19))) + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0 + known=target&allowed&covered + score['observed_support']=float(near[known].mean())if known.any()else 0. + score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank) + score['planar_vehicle_override']=float((planar&~vehicle_good)[target].mean())if target.any()else 0.;score['surface_checks']={key:float(a[target].mean())if target.any()else 0. for key,a in [('alpha',alpha_good),('vehicle',vehicle_good),('paved',surface_good)]};ev.append(score) + return ev,sorted(names) diff --git a/simulation/urban-plan-research/component_pass/component_rules.py b/simulation/urban-plan-research/component_pass/component_rules.py new file mode 100644 index 00000000..0a91c2e6 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_rules.py @@ -0,0 +1,29 @@ +from discovery_rules import glyph_pass +VERSION='whole-symbol-components-v8' +POLICY=dict(bicycle_semantic_score=.30,arrow_semantic_score=.50,min_semantic_fraction=.55, + bicycle_fit_score=.80,arrow_fit_score=.78,min_observed_support=.90,min_recall=.85, + min_valid=.97,max_negative_paint=.12,max_head_flank_paint=.10, + max_fragment_gap_m=.18,semantic_join_gap_m=.35,point_cloud_input=False,paint_threshold="observed-local-otsu-contrast",proposal_windows_m=[.72,3.0],paint_window_m=3.0,zigzag_paint_window_m=.72,bicycle_surface_classes=[1,2],manual_rois=[],vehicle_flatness_tolerance_m=.12,min_connected_recall=.85,compound_support=.80,compound_branch_support=.85,compound_head_support=.85,compound_tail_support=.50) +def accept_symbol(ev,score,containment,fit,kind): + if scorePOLICY['max_negative_paint']:return False + if rank==0 and e['recall'].25:return False + if kind=='straight_arrow'and e.get('head_flank_paint',1)>POLICY['max_head_flank_paint']:return False + return True diff --git a/simulation/urban-plan-research/component_pass/component_surface.py b/simulation/urban-plan-research/component_pass/component_surface.py new file mode 100644 index 00000000..7843413f --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_surface.py @@ -0,0 +1,22 @@ +"""A 2-D vehicle label cannot veto paint when Gaussian depth proves flatness.""" +from pathlib import Path +from functools import lru_cache +import numpy as np,cv2 +from fit_scene import project +@lru_cache(maxsize=12) +def ground_geometry(name): + with np.load(Path('/ortho/evidence')/(name+'.ground-dc.geometry.npz'))as z:return dict(z) +def depth_agrees(context_depth,ground_depth,context_alpha,ground_alpha): + return np.isfinite(context_depth)&np.isfinite(ground_depth)&(context_alpha>=.85)&(ground_alpha>=.85)&(abs(context_depth-ground_depth)<=.12) +def planar_vehicle_clearance(points,views): + centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in views.original]);dist=np.linalg.norm(points[:,None,:]-centers[None,:,:],axis=2);eligible=np.zeros(dist.shape,bool) + for i,t in enumerate(views.original): + uv=project(points,views.geometry(t['id']));eligible[:,i]=(uv.min(1)>=20)&(uv.max(1)<1180) + owners=np.argmin(np.where(eligible,dist,np.inf),axis=1);okay=np.zeros(len(points),bool) + for i in np.unique(owners): + ids=np.flatnonzero((owners==i)&eligible[:,i]);name=views.original[i]['id'];a=views.geometry(name);b=ground_geometry(name);uv=project(points[ids],a).astype('float32') + if not len(ids):continue + assert np.allclose(a['view'],b['view'])and np.allclose(a['intrinsics'],b['intrinsics']) + def read(x):return np.concatenate([cv2.remap(x.astype('float32'),q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,max(1,int(np.ceil(len(uv)/20000))))]) + okay[ids]=depth_agrees(read(a['depth']),read(b['depth']),read(a['alpha']),read(b['alpha'])) + return okay diff --git a/simulation/urban-plan-research/component_pass/component_targets.py b/simulation/urban-plan-research/component_pass/component_targets.py new file mode 100644 index 00000000..70a81001 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_targets.py @@ -0,0 +1,55 @@ +"""Bounded component assembly, using semantic seeds and observed paint only.""" +import numpy as np,cv2,shapely +from shapely.geometry import Polygon +from layer_common import parts +from paint_channels import paint_mask + +def vector(binary,p): + corners=np.asarray(p['world_corners']);H=cv2.getPerspectiveTransform(np.array([[0,0],[p['width_px'],0],[p['width_px'],p['height_px']],[0,p['height_px']]],'float32'),corners.astype('float32')) + def xy(c):return cv2.perspectiveTransform(c.astype('float32'),H)[:,0] + cc,hier=cv2.findContours(binary.astype('uint8'),cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);pp=[] + if hier is None:return Polygon() + for i,c in enumerate(cc): + if hier[0,i,3]>=0 or len(c)<3 or cv2.contourArea(c)*p['mpp']**2<.002:continue + holes=[];j=hier[0,i,2] + while j>=0: + if len(cc[j])>=3 and cv2.contourArea(cc[j])*p['mpp']**2>.002:holes.append(xy(cc[j])) + j=hier[0,j,0] + pp.extend(parts(shapely.make_valid(Polygon(xy(c),holes)))) + return shapely.union_all(pp) + +def _targets(image,p,masks,scores,classes,scale): + gray=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(image,cv2.COLOR_RGB2HSV);radius=int(scale/p['mpp'])//2*2+1 + ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(radius,radius))) + yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>65) + white=(ridge>12)&(gray>100)&(hsv[:,:,1]<100)&~yellow + components=parts(vector(white,p));result=[] + for ci in [0,1]: + seeds=[dict(region=vector(m,p),score=float(s),masks=[i])for i,(m,s,c)in enumerate(zip(masks,scores,classes))if c==ci and s>=(.30 if ci==0 else .50)] + groups=list(seeds) + for seed in seeds: + nearby=[s for s in seeds if s['region'].distance(seed['region'])<.35] + if len(nearby)>1:groups.append(dict(region=shapely.union_all([s['region']for s in nearby]),score=max(s['score']for s in nearby),masks=sorted({i for s in nearby for i in s['masks']}))) + for seed in groups: + region=seed['region'];limit=region.convex_hull.buffer(.45) + # Keep entire connected paint pieces intersecting the semantic seed; do + # not truncate them at a model's arbitrary instance boundary. + selected=[c for c in components if c.intersection(region.buffer(.10)).area>.01 and c.intersection(limit).area/c.area>.80] + if not selected:continue + whole=shapely.union_all(selected) + for _ in range(2): + near=[c for c in components if c.distance(whole)<.18 and c.intersection(limit).area/c.area>.85] + whole=shapely.union_all([whole]+near) + for target in [whole,vector(white & (cv2.dilate(masks[seed['masks'][0]].astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7)))>0),p)]: + if target.is_empty or target.area<.08:continue + if any(ci==r['ci']and target.symmetric_difference(r['target']).area<.02 for r in result):continue + result.append(dict(target=target,ci=ci,**seed)) + return result + +def targets(image,p,masks,scores,classes): + result=[] + for scale in [.72,3.0]: + for r in _targets(image,p,masks,scores,classes,scale): + if any(r['ci']==s['ci']and r['target'].symmetric_difference(s['target']).area<.02 for s in result):continue + result.append(dict(r,paint_scale_m=scale)) + return result diff --git a/simulation/urban-plan-research/component_pass/component_zigzag_rules.py b/simulation/urban-plan-research/component_pass/component_zigzag_rules.py new file mode 100644 index 00000000..60ff0fbe --- /dev/null +++ b/simulation/urban-plan-research/component_pass/component_zigzag_rules.py @@ -0,0 +1,16 @@ +"""Color-specific admission for finite zigzag sequences, including 3 legs.""" +from catalog_rules import accept_zigzag as legacy_accept +POLICY=dict(short_legs=3,max_residual_m=.06,min_proposal_recall=.90, + min_valid=.97,min_support=.98,max_negative=.04,secondary_support=.95) +def accept_zigzag(ev,legs,fit): + mode=legacy_accept(ev,legs,fit) + if mode:return mode + if fit['legs']!=POLICY['short_legs']or fit['fit_residual_m']>POLICY['max_residual_m']or fit['proposal_recall']POLICY['max_negative']:return None + c=b['paint_coverage'] + if c and(b['paint_valid']/c<.95 or b['observed_support'].12):return None + return 'three-observed-yellow-legs' diff --git a/simulation/urban-plan-research/component_pass/diagnose_components.py b/simulation/urban-plan-research/component_pass/diagnose_components.py new file mode 100644 index 00000000..068ec0ec --- /dev/null +++ b/simulation/urban-plan-research/component_pass/diagnose_components.py @@ -0,0 +1,26 @@ +from pathlib import Path +import json,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape +from PIL import Image,ImageDraw,ImageFont +O=Path('/out');I=Path('/symbolplan');font=ImageFont.truetype('/candidate/review-font.ttf',16) +patches={p['id']:p for p in json.loads((I/'symbol-patches.json').read_text())['patches']} +sem=json.loads((I/'symbol-semantics.json').read_text());diag=json.loads((I/'symbol-diagnostics.json').read_text()) +baseline=json.loads(Path('/fullplan/full-map.json').read_text());existing=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in baseline['features']if f['properties'].get('subtype')in ['bicycle','straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow']]) +selection={r['id'] for r in sem['records']if 0 in r['classes']} +selection.update(d['patch']for d in diag if d.get('fits')and not d.get('covered_by_baseline')and max(x['score']for x in d['fits'])>.78) +panels=[] +for pid in sorted(selection): + p=patches[pid];im=Image.open(I/'symbol-patches'/(pid+'.png')).convert('RGB');rec=next(r for r in sem['records']if r['id']==pid) + frame=Image.new('RGB',(800,450),'white');im.thumbnail((400,400));frame.paste(im,(0,50));overlay=im.copy();d=ImageDraw.Draw(overlay) + corners=np.array(p['world_corners']);H=cv2.getPerspectiveTransform(corners.astype('float32'),np.array([[0,0],[im.width,0],[im.width,im.height],[0,im.height]],'float32')) + for f in baseline['features']: + if f['properties']['class']!='road_marking':continue + for ring in f['geometry']['coordinates']: + xy=cv2.perspectiveTransform(np.array(ring,'float32')[:,:2,None].transpose(0,2,1),H)[:,0];d.line([tuple(x)for x in xy],fill='#f1c300',width=2) + frame.paste(overlay,(400,50));d=ImageDraw.Draw(frame);d.text((4,4),pid+' '+p['source_tile'],font=font,fill='black');d.text((4,26),str([(int(c),round(s,2))for c,s in zip(rec['classes'],rec['scores'])]),font=font,fill='black');panels.append(frame) +for i in range(0,len(panels),8): + group=panels[i:i+8];sheet=Image.new('RGB',(1600,450*((len(group)+1)//2)),'white') + for j,f in enumerate(group):sheet.paste(f,((j%2)*800,(j//2)*450)) + sheet.save(O/('diagnostic-%02d.jpg'%(i//8)),quality=94) +print('DIAGNOSTIC PATCHES',len(panels)) diff --git a/simulation/urban-plan-research/component_pass/paint_channels.py b/simulation/urban-plan-research/component_pass/paint_channels.py new file mode 100644 index 00000000..62772e02 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/paint_channels.py @@ -0,0 +1,16 @@ +"""Local Otsu contrast threshold in a metric window, OpenCV only.""" +import cv2,numpy as np +def paint_mask(rgb,channel='white',cell=.04,observed=None,calibration=None): + if observed is not None and not observed.all(): + rgb=rgb.copy();rgb[~observed]=np.median(rgb[observed],axis=0).astype('uint8')if observed.any()else 0 + gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);k=int((.72 if channel=='yellow'else 3.0)/cell)//2*2+1 + ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k))) + sample=ridge if observed is None else ridge[cv2.erode(observed.astype('uint8'),np.ones((k,k),np.uint8))>0] + # Calibrate on observed ground, never on the fitted symbol or white void. + if calibration is not None: + known=np.asarray(calibration,bool)&(np.ones(gray.shape,bool)if observed is None else observed) + sample=ridge[known] + threshold,_=cv2.threshold(sample,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)if sample.size else(15.,None) + yellow=(hsv[:,:,0]>10)&(hsv[:,:,0]<38)&(hsv[:,:,1]>35) + color=yellow if channel=='yellow'else((hsv[:,:,1]<100)&~((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>65))) + return (True if observed is None else observed)&(ridge>max(15.,threshold))&(gray>100)&color diff --git a/simulation/urban-plan-research/component_pass/refine_components.py b/simulation/urban-plan-research/component_pass/refine_components.py new file mode 100644 index 00000000..f3a4ef5d --- /dev/null +++ b/simulation/urban-plan-research/component_pass/refine_components.py @@ -0,0 +1,57 @@ +from pathlib import Path +import json,time,hashlib,os,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping +from shapely.ops import transform +from PIL import Image +from layer_common import O,S,sample,parts,feature +from search_views import SearchViews +from discovery_rules import uncovered,unpack +from catalog_context import bicycle_context +from component_mosaics import mosaic_views +from component_bicycle import fit_bicycle +from component_arrows import fit_arrows +from component_targets import targets +from component_rules import VERSION,POLICY,accept_symbol +from component_conflicts import symbol_replacements,FRAGMENT_POLICY +sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() +start=time.monotonic();cv2.setNumThreads(3);baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']} +I=Path('/symbolplan');patch_file=I/'symbol-patches.json';patch_doc=json.loads(patch_file.read_text());semantic_file=I/'symbol-semantics.json';semantic=json.loads(semantic_file.read_text()) +assert semantic['patch_manifest_sha256']==sha(patch_file) +patches={p['id']:p for p in patch_doc['patches']} +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None) +lines=[unpack(r)for r in json.loads(Path('/searchplan/search-proposals.json').read_text())['lines']] +poly=lambda f:shapely.force_2d(shape(f['geometry'])) +existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking']);transactions=[];diagnostics=[];seen=[] +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +for rec in semantic['records']: + if not rec['detections']:continue + p=patches[rec['id']];path=I/'symbol-patches'/(p['id']+'.png');assert sha(path)==p['sha256'];image=np.asarray(Image.open(path).convert('RGB'));npz=I/'symbol-masks'/(p['id']+'.npz');assert sha(npz)==rec['sha256'] + with np.load(npz)as z:proposals=targets(image,p,z['masks'],z['scores'],z['classes']) + for proposal in proposals: + target=proposal['target'];region=proposal['region'];ci=proposal['ci'];score=proposal['score'] + if target.intersection(existing.buffer(.1)).area/target.area>.50:continue + if any(ci==c and target.symmetric_difference(q).area/max(target.area,q.area)<.08 for c,q in seen):continue + seen.append((ci,target));diag=dict(patch=p['id'],masks=proposal['masks'],semantic_score=score,semantic_class=ci,target=mapping(target));diagnostics.append(diag) + fits=fit_bicycle(target,all_hypotheses=True)or[] if ci==0 else fit_arrows(target) + if ci==0:fits=[dict(f,kind='bicycle')for f in fits] + diag['fits']=[{k:v for k,v in f.items()if k!='polygon'}for f in fits];diag['evaluated']=[] + for f in fits: + kind=f['kind'];q=f['polygon'];containment=q.intersection(region.buffer(.20)).area/max(q.area,1e-9) + if f['score'].85 for x in seen):continue + seen.append(q);ev,names=mosaic_views(q,views);legs=[] + for a,b in zip(fit['vertices'],fit['vertices'][1:]): + ee,nn=mosaic_views(LineString([a,b]).buffer(fit['width_m']/2,cap_style=2),views,negative_context=q);legs.append(ee) + mode=accept_zigzag(ev,legs,fit);diag=dict(group=gi,evidence=ev,leg_evidence=legs,passed=bool(mode),**{k:v for k,v in fit.items()if k!='polygon'});diagnostics.append(diag) + if not mode:continue + # Whole-pattern replacement is allowed only for the same existing zigzag; + # other kinds, including prior reviewed strips, are not edited here. + overlaps=[f for f in current.values()if f['properties']['class']=='road_marking'and poly(f).intersection(q).area>.005] + if any(f['properties'].get('subtype')!='zigzag'for f in overlaps):continue + if overlaps and (any(poly(f).difference(q.buffer(.12)).area/poly(f).area>.10 for f in overlaps)or q.area<1.15*sum(poly(f).area for f in overlaps)):continue + f=feature(lift(q),'road_marking',subtype='zigzag',method=VERSION,source_tile=names[0],source_tiles=names,vertices=fit['vertices'],leg_count=fit['legs'],width_m=fit['width_m'],fit_residual_m=fit['fit_residual_m'],standard_compliance='not_assessed',source_ids=[v['id']for v in overlaps]) + for v in overlaps:del current[v['id']] + current[f['id']]=f;transactions.append(dict(kind='assembled-zigzag',source_ids=[v['id']for v in overlaps],output_ids=[f['id']],before=overlaps,after=[f],bounds_xy=q.bounds,source_tiles=names,evidence=dict(whole=ev,legs=legs),fit=diag));print('ADMIT ZIGZAG',gi,fit['legs'],flush=True) +new['features']=list(current.values());(O/'full-map.json').write_text(json.dumps(new,allow_nan=False));(O/'component-rows.json').write_text(json.dumps(transactions,indent=2));(O/'zigzag-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));report=json.loads((O/'component-report.json').read_text());report.update(changed_segments=len(transactions),added_objects=sum(not t['before']for t in transactions),added_subtypes=dict(collections.Counter(t['after'][0]['properties']['subtype']for t in transactions if not t['before'])),zigzag_proposals_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),zigzag_seconds=time.monotonic()-start,zigzag_policy=ZIGZAG_POLICY,reconstructed_subtypes=dict(collections.Counter(t['after'][0]['properties']['subtype']for t in transactions)),replaced_fragments=sum(len(t['before'])for t in transactions));(O/'component-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report)) diff --git a/simulation/urban-plan-research/component_pass/render_components.py b/simulation/urban-plan-research/component_pass/render_components.py new file mode 100644 index 00000000..d8516608 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/render_components.py @@ -0,0 +1,33 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from search_views import SearchViews +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'component-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('component-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +views=SearchViews(tiles,None,None,None,None);tiles=views.tiles +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='component-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('component-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'component-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) diff --git a/simulation/urban-plan-research/component_pass/render_hypotheses.py b/simulation/urban-plan-research/component_pass/render_hypotheses.py new file mode 100644 index 00000000..f22a7736 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/render_hypotheses.py @@ -0,0 +1,43 @@ +from pathlib import Path +import json,shapely +from shapely.affinity import rotate,translate +from shapely.geometry import mapping +from fragment_templates import template +from catalog_templates import bicycle +O=Path('/out');debug_groups=[];debug_features=[];seen=set() +for d in json.loads((O/'component-diagnostics.json').read_text()): + if not d['evaluated'] or d['patch']in seen:continue + seen.add(d['patch']);e=d['evaluated'][0];x=e['parameters'];kind=e['kind'];q=bicycle(x)if kind=='bicycle'else translate(rotate(template(kind,*x[3:]),x[2],origin=(0,0),use_radians=True),x[0],x[1]);f=dict(id=d['patch'],properties=dict(**{'class':'road_marking'},subtype=kind),geometry=mapping(q));debug_features.append(f);debug_groups.append(dict(bounds_xy=q.bounds,kind=kind,baseline_objects=0,output_objects=1)) +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from search_views import SearchViews +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new={'features':debug_features};groups=debug_groups;tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('hypothesis-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +views=SearchViews(tiles,None,None,None,None);tiles=views.tiles +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='hypothesis-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('hypothesis-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'hypothesis-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) diff --git a/simulation/urban-plan-research/component_pass/test_components.py b/simulation/urban-plan-research/component_pass/test_components.py new file mode 100644 index 00000000..d07f816b --- /dev/null +++ b/simulation/urban-plan-research/component_pass/test_components.py @@ -0,0 +1,77 @@ +import json,runpy +import numpy as np,cv2,shapely +from shapely.geometry import Polygon,LineString +from shapely.affinity import rotate,translate +from component_rules import accept_symbol +from component_evidence import directional_score +from component_targets import targets +from component_arrows import fit_arrows +from component_bicycle import fit_bicycle +from paint_channels import paint_mask +from road_glyph_presets import arrow +from catalog_zigzag import fit_zigzag +prior=runpy.run_path('/candidate/test_symbols.py')['result'];checks={} +e=dict(connected_recall=.98,connected_at_window_edge=False,paint_coverage=1.,paint_valid=1.,observed_support=.98,negative_paint=.01,recall=.95) +checks['weak_model_requires_strong_bicycle_shape']=accept_symbol([e,e],.35,.95,.86,'bicycle')and not accept_symbol([e,e],.35,.95,.70,'bicycle') +checks['class_absence_rejected']=not accept_symbol([e,e],.2,.95,.99,'bicycle') +checks['missing_primary_rejected']=not accept_symbol([{**e,'paint_coverage':.5},e],.9,.95,.99,'bicycle') +checks['contradicting_second_view_rejected']=not accept_symbol([e,{**e,'observed_support':.1}],.9,.95,.99,'bicycle') +checks['unknown_surface_rejected']=not accept_symbol([{**e,'paint_valid':.1},e],.9,.95,.99,'bicycle') +checks['noisy_negative_space_rejected']=not accept_symbol([{**e,'negative_paint':.5},e],.9,.95,.99,'bicycle') +checks['foreign_class_seed_rejected']=not accept_symbol([e,e],.9,.2,.99,'bicycle') +cell=.04;x,y=np.meshgrid(np.arange(-1,7,cell),np.arange(-2,2,cell));points=np.c_[x.ravel(),y.ravel()];valid=np.ones(x.shape,bool) +def picture(p):return np.repeat(np.where(shapely.contains_xy(p,points[:,0],points[:,1]).reshape(x.shape),220,65)[:,:,None],3,axis=2).astype('uint8') +p=arrow('straight_arrow',4,1.2,.16);rgb=picture(p);g=directional_score(rgb,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]);g.update(paint_coverage=1.,paint_valid=1.,observed_support=g['support']) +checks['whole_arrow_supported']=accept_symbol([g,g],.95,.99,.95,'straight_arrow') +through=rgb.copy();through[abs(y)<.08]=220;bad=directional_score(through,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]);bad.update(paint_coverage=1.,paint_valid=1.,observed_support=bad['support']) +checks['continued_stripe_cannot_be_arrow']=not accept_symbol([bad,bad],.99,.99,.99,'straight_arrow') +tri=Polygon([(4,-.6),(4,.6),(6,0)]);reverse=translate(rotate(arrow('straight_arrow',2,1.2,.16),180,origin=(0,0)),6,0);bad=directional_score(picture(tri),valid,points,reverse,kind='straight_arrow',parameters=[6,0,np.pi,2,1.2,.16]);bad.update(paint_coverage=1.,paint_valid=1.,observed_support=bad['support']) +checks['reversed_head_cannot_be_arrow']=not accept_symbol([bad,bad],.99,.99,.99,'straight_arrow') +checks['line_cannot_be_bicycle']=not fit_bicycle(LineString([(0,0),(4,0)]).buffer(.08),all_hypotheses=True) +checks['bent_strip_cannot_be_zigzag']=fit_zigzag(LineString([(0,0),(2,.2),(3,0),(4,.1)]).buffer(.05))is None +checks['one_corner_cannot_be_zigzag']=fit_zigzag(LineString([(0,0),(2,1),(4,0)]).buffer(.06))is None +# A clean complex arrow is recoverable after a rotation and translation, with +# the same fitter and no geographic identity supplied. +q=translate(rotate(arrow('straight_left_arrow',5,1.7,.16),33,origin=(0,0)),12,-7);fits=fit_arrows(q) +checks['rotated_complex_preset_recognized']=bool(fits)and fits[0]['kind']=='straight_left_arrow'and fits[0]['score']>.85 +# Color channels must not turn an adjacent pattern into support for a symbol. +yellow=rgb.copy();yellow[(rgb[:,:,0]>200)]=[220,170,30] +checks['white_evidence_excludes_yellow']=paint_mask(yellow,'white').sum()==0 +checks['yellow_channel_retains_yellow']=paint_mask(yellow,'yellow').sum()>50 +checks['blank_surface_has_no_paint']=not paint_mask(np.full_like(rgb,130)).any() +from component_zigzag_rules import accept_zigzag as accept_short +ze=dict(recall=1.,connected_recall=.98,connected_at_window_edge=False,paint_coverage=1.,paint_valid=1.,support=1.,observed_support=1.,negative_paint=0.) +unknown=dict(recall=0.,paint_coverage=0.,paint_valid=0.,support=0.,observed_support=0.,negative_paint=1.) +zz=dict(legs=3,fit_residual_m=.02,proposal_recall=.96) +checks['three_yellow_legs_with_clear_background'] = bool(accept_short([ze,unknown],[[ze,unknown]]*3,zz)) +checks['short_zigzag_missing_leg_rejected'] = not accept_short([ze,unknown],[[ze,unknown]]*2,zz) +checks['short_zigzag_partial_observation_rejected'] = not accept_short([{**ze,'paint_coverage':.9},unknown],[[ze,unknown]]*3,zz) +checks['short_zigzag_noise_rejected'] = not accept_short([{**ze,'negative_paint':.2},unknown],[[ze,unknown]]*3,zz) +checks['short_zigzag_conflicting_view_rejected'] = not accept_short([ze,{**ze,'observed_support':.3}],[[ze,unknown]]*3,zz) +checks['short_zigzag_bad_geometry_rejected'] = not accept_short([ze,unknown],[[ze,unknown]]*3,{**zz,'fit_residual_m':.3}) +from component_surface import depth_agrees +checks['flat_vehicle_label_can_be_overridden']=bool(depth_agrees(np.array([10.]),np.array([10.02]),np.array([1.]),np.array([1.]))[0]) +checks['raised_vehicle_stays_excluded']=not bool(depth_agrees(np.array([9.]),np.array([10.]),np.array([1.]),np.array([1.]))[0]) +checks['unknown_depth_stays_excluded']=not bool(depth_agrees(np.array([float('nan')]),np.array([10.]),np.array([1.]),np.array([1.]))[0]) +checks['weak_alpha_cannot_override_vehicle']=not bool(depth_agrees(np.array([10.]),np.array([10.]),np.array([.3]),np.array([1.]))[0]) +checks['partial_connected_object_rejected']=not accept_symbol([{**e,'connected_recall':.4},e],.99,.99,.99,'bicycle') +checks['truncated_at_image_edge_rejected']=not accept_symbol([{**e,'connected_at_window_edge':True},e],.99,.99,.99,'bicycle') +# A second complete view can reveal a continuation missing in the first. +checks['second_view_partial_connected_object_rejected']=not accept_symbol([e,{**e,'connected_recall':.6}],.99,.99,.99,'bicycle') +checks['second_view_truncated_object_rejected']=not accept_symbol([g,{**g,'connected_at_window_edge':True}],.99,.99,.99,'straight_arrow') +compound={**g,'parts':[dict(part='head',coverage=1.,valid=1.,support=.87),dict(part='tail',coverage=1.,valid=1.,support=.7),dict(part='branch',coverage=1.,valid=1.,support=.95)]} +checks['worn_compound_head_with_supported_branch']=accept_symbol([compound,compound],.95,.99,.95,'straight_left_arrow') +checks['compound_without_branch_rejected']=not accept_symbol([{**compound,'parts':[dict(part='branch',coverage=1.,valid=1.,support=.2)]},compound],.95,.99,.95,'straight_left_arrow') +from component_conflicts import symbol_replacements +from shapely.geometry import mapping + +def fragment(geometry,subtype='linear_marking'): + return dict(id='synthetic',geometry=mapping(geometry),properties=dict(class_name='road_marking',**{'class':'road_marking'},subtype=subtype)) +inside=fragment(LineString([(0.5,0),(2.,0)]).buffer(.06)) +checks['arrow_owns_contained_stem_fragment']=symbol_replacements(p,'straight_arrow',[inside])==[inside] +checks['arrow_does_not_consume_crossing_line']=symbol_replacements(p,'straight_arrow',[fragment(LineString([(1,-2),(1,2)]).buffer(.06))])is None +checks['arrow_does_not_consume_adjacent_line']=symbol_replacements(p,'straight_arrow',[fragment(LineString([(0,1),(4,1)]).buffer(.06))])==[] +checks['arrow_does_not_consume_another_symbol']=symbol_replacements(p,'straight_arrow',[fragment(p,'straight_arrow')])is None +checks['bicycle_does_not_replace_lane_line']=symbol_replacements(p,'bicycle',[inside])is None +result=dict(passed=all(checks.values())and prior['passed'],checks={k:bool(v)for k,v in checks.items()},prior_checks=len(prior['checks']),prior_passed=prior['passed']) +open('/out/component-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/component_pass/zigzag_evidence.py b/simulation/urban-plan-research/component_pass/zigzag_evidence.py new file mode 100644 index 00000000..7ca65cb5 --- /dev/null +++ b/simulation/urban-plan-research/component_pass/zigzag_evidence.py @@ -0,0 +1,33 @@ +from paint_channels import paint_mask +import numpy as np,cv2,shapely +from discovery_rules import POLICY +def glyph_score(rgb,allowed,points,polygon,cell=.04,kind=None,parameters=None): + """Check positive paint, unpainted negative space, and unexplained pixels.""" + h,w=allowed.shape;gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY) + bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19))) + hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV) + paint=paint_mask(rgb,channel='yellow') + target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w) + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0 + wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0 + region=shapely.contains_xy(polygon.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(h,w) + negative=region&~wide + result=dict(valid=float(allowed[region].mean())if region.any()else 0., + support=float(near[target].mean())if target.any()else 0., + recall=float(wide[paint®ion&allowed].mean())if (paint®ion&allowed).any()else 0., + negative_paint=float(paint[negative&allowed].mean())if (negative&allowed).any()else 1.) + if kind is not None and parameters is not None: + px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w) + regions=[('head',t>L*.80),('tail',tW*.24)) + result['parts']=[] + for name,where in regions: + select=target&where + result['parts'].append(dict(part=name,valid=float(allowed[select].mean())if select.any()else 0.,support=float(near[select].mean())if select.any()else 0.)) + result['ends']=[] + for name,interior,exterior in [('tail',t-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t=20)&(uv.max(1)<1180) + owners=choose_owners(distance,coverage);ev=[];names=set();target=shapely.contains_xy(p,points[:,0],points[:,1]) + for rank in [0,1]: + colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool);covered=np.zeros(len(points),bool);source_counts={} + for i in np.unique(owners[:,rank]): + if i<0:continue + select=np.flatnonzero(owners[:,rank]==i);name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points[select],g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5 + def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]) + colors[select]=read(rgb,native);allowed[select]=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points[select],views.low,views.high)==1);covered[select]=True + if target[select].any():names.add(name);source_counts[name]=int(target[select].sum()) + score=glyph_score(colors.reshape(len(yy),len(xx),3),allowed.reshape(len(yy),len(xx)),points,p,kind=None,parameters=None) + rgb=colors.reshape(len(yy),len(xx),3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV) + bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(19,19))) + paint=paint_mask(rgb,channel='yellow') + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))).ravel()>0 + if negative_context is not None: + # Adjacent legs belong to the same known pattern; they are not + # unexplained paint in this leg's background. The whole pattern + # still receives its original negative-space check. + context=shapely.contains_xy(negative_context.buffer(.08),points[:,0],points[:,1]) + region=shapely.contains_xy(p.convex_hull.buffer(.15),points[:,0],points[:,1]) + negative=region&~context&allowed&covered + score['negative_paint']=float(paint.ravel()[negative].mean())if negative.any()else 0. + score['negative_space_scope']='exclude-other-legs-of-same-pattern' + known=target&allowed&covered + score['observed_support']=float(near[known].mean())if known.any()else 0. + score.update(paint_valid=float(allowed[target].mean())if target.any()else 0.,paint_coverage=float(covered[target].mean())if target.any()else 0.,source_counts=source_counts,ownership='nearest-covering-geometry-per-pixel',rank=rank) + ev.append(score) + return ev,sorted(names) diff --git a/simulation/urban-plan-research/consensus_pass/README.rst b/simulation/urban-plan-research/consensus_pass/README.rst new file mode 100644 index 00000000..4e907c43 --- /dev/null +++ b/simulation/urban-plan-research/consensus_pass/README.rst @@ -0,0 +1,80 @@ +Two-view verification of redundant road-marking vectors +====================================================== + +Scope +----- +Offline Gaussian-only increment over transitions-pass-20261012. One immutable +source and one policy across Maroseyka, Pokrovka and Smolensk. The code never +branches on scene names, world coordinates, manually chosen regions or IDs. +Worker006 performs all computation, tests and rendering. Mac operations are +limited to orchestration, source/document editing, hashes, copies and viewing. + +Reusable components and policy +------------------------------ +OpenCV minAreaRect/remap/morphology measure metric image strips; SciPy filtering +and find_peaks/peak_widths resolve paint ridges; Shapely handles overlap. The new +wrapper expresses acceptance and preservation rules, not a map-specific model. +POLICY is saved in each scene report. Parameters have metric or photometric +meaning and are identical for all maps; none are selected from street identity. + +Candidate pairs are thin linear-marking polygons with compatible directions +(<=4 degrees), lateral distance <=0.65 m and >=75% longitudinal overlap of the +source. Each candidate is evaluated in two nearest render tiles that fully +cover both polygons with an image margin. Render views share the same Gaussian +reconstruction: agreement is not independent ground-truth evidence. + +Valid samples require actual image coverage, top-view alpha >=0.65, road surface, +vehicle score <0.20 and exclusion of protected symbols/crosswalks. Both objects +need >=95% valid samples in both views. The retained stroke needs >=85% bright +support and median local contrast >=22. Unknown or masked pixels cannot justify +removal. Neighboring rows are not duplicates merely because they are close. + +Deletion can be justified by: +* >=90% geometric containment in an image-supported keeper; +* <=15% bright support and source contrast q75 <8, beside a supported keeper; +* one common physical paint ridge represented by two vectors. The keeper must + be <=8 cm from the ridge, the rejected vector >=10 cm away and at least 6 cm + farther from it. Both views must agree on the ridge within 5 cm. + +For every reason, an observed second ridge vetoes deletion. Transverse profiles +are inspected both as a median and along individual stations. A second ridge +present at >10% of stations or continuously for >=0.25 m protects intermittent +parallel paint, even if it disappears from the median profile. The transverse +corridor also needs >=95% valid evidence. All these are reconstruction rules, +not GOST application tolerances. Earlier normative dimensional checks remain. + +The deterministic selection keeps each named keeper and prevents deletion cycles. +No vector coordinates are moved or newly drawn by this pass; all surviving +features are byte-for-byte identical JSON objects. Each removal records source, +keeper, views, profiles and acceptance metrics. Old anchor/source IDs remain +historical provenance; consumers needing current IDs can resolve the explicit +source_id -> target_id records in consensus-rows.json. + +Verification and limits +----------------------- +The controlled suite reuses all preceding 57 checks and adds tests for visible +parallel lines, faint paint, occlusion, missing/disagreeing views, overlap, +perpendicular/distant neighbors, rotation/translation, one blurred ridge, +real double ridges, intermittent short paint and invalid transverse coverage. +Each accepted edit has an exhaustive source/before/after frame. Existing short +punctuation reference frames and whole-map overviews support visual regression +review; unchanged-feature audits cover all unmodified objects. + +This pass removes only evidence-confirmed whole-object duplicates. It does not +repair false solid continuations lacking a suitable neighboring keeper, perform +partial duplicate trimming, resolve single-view cases, redraw curved rows or +find missing symbols. Some pairs that look duplicated at overview scale are +actual double paint ridges and intentionally remain. Whole-map recall/precision, +geodetic accuracy and legal marking compliance are not established. Unchanged +scenes are regression controls, not proof of universal performance on all scans. + +Replay +------ +Pinned image sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0. +4 CPU, 20 GiB RAM, 1 GiB tmpfs, read-only root, no network, 1800s per stage. +Stages: test_consensus, refine_consensus, audit_consensus, render_consensus, +render_plan. Private scene caches, canonical queue and SSH configuration are +required external inputs. Qualified hashes and execution receipts accompany +outputs. bundle.json resolves unchanged canonical modules; review-font.ttf is +separately pinned and omitted from source ZIP. No live deployment, Ops post or +commit. Technical artifacts and intermediate attempts stay in qualification. diff --git a/simulation/urban-plan-research/consensus_pass/audit_consensus.py b/simulation/urban-plan-research/consensus_pass/audit_consensus.py new file mode 100644 index 00000000..19db664c --- /dev/null +++ b/simulation/urban-plan-research/consensus_pass/audit_consensus.py @@ -0,0 +1,30 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/consensus-rows.json').read_text()) +removed=set(json.loads(Path('/out/consensus-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']};checks={} +checks['unique_ids']=len(features)==len(new['features']) +checks['all_surviving_features_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed) +checks['only_linear_removed']=all(f['properties'].get('subtype')=='linear_marking'for f in old['features']if f['id']in removed) +checks['no_new_or_moved_geometry']=len(features)+len(removed)==len(old['features'])and all(f['id']in {x['id']for x in old['features']}for f in new['features']) +checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']) +checks['keeper_survives']=all(r['target_id']in features and r['source_id']not in features for r in rows) +checks['each_removal_traced']=removed==set(r['source_id']for r in rows) +checks['two_distinct_views']=all(len(set(r['source_tiles']))>=2 and len(r['views'])>=2 for r in rows) +checks['image_supported_keepers']=all(all(v['source_valid']>=.95 and v['target_valid']>=.95 and v['target_support']>=.85 and v['target_median']>=22 for v in r['views'])for r in rows) +def reason_supported(r): + if r['kind']=='overlapping_duplicate':return r['geometry']['contained_fraction']>=.9 + if r['kind']=='unsupported_offset_duplicate':return all(v['source_support']<=.15 and v['source_q75']<8 for v in r['views']) + if r['kind']!='one_ridge_two_vectors':return False + offsets=[] + for x in r['ridges']: + if len(x['peaks'])!=1 or x['valid_fraction']<.95 or x['two_ridge_fraction']>.1 or x['longest_two_ridge_m']>=.25:return False + d=x['peaks'][0]['offset'];offsets.append(d) + if abs(d)<.10 or abs(d-x['target_offset'])>.08 or abs(d)-abs(d-x['target_offset'])<.06:return False + return len(offsets)>=2 and max(offsets)-min(offsets)<=.05 +checks['no_observed_second_ridge_removed']=all(all(x['valid_fraction']>=.95 and x['two_ridge_fraction']<=.1 and x['longest_two_ridge_m']<.25 for x in r['ridges'])for r in rows) +checks['each_reason_has_evidence']=all(reason_supported(r)for r in rows) +checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes() +checks['same_policy']=new['consensus_refinement']=='two-view-redundant-paint-v1' +result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/consensus-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/consensus_pass/bundle.json b/simulation/urban-plan-research/consensus_pass/bundle.json new file mode 100644 index 00000000..c60b4c46 --- /dev/null +++ b/simulation/urban-plan-research/consensus_pass/bundle.json @@ -0,0 +1,64 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "fit_scene.py": "full_plan/fit_scene.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "continuation_pass/render_plan.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py" + }, + "reference_qualification": "consensus-pass-20261012", + "source_snapshot": "430fd320ec10ad4ea212", + "source_sha256": { + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/consensus_pass/consensus_profiles.py b/simulation/urban-plan-research/consensus_pass/consensus_profiles.py new file mode 100644 index 00000000..c3398544 --- /dev/null +++ b/simulation/urban-plan-research/consensus_pass/consensus_profiles.py @@ -0,0 +1,97 @@ +"""Image-supported suppression of redundant thin vector paint objects. + +Nearby vectors nominate pairs only. Two render views must independently pass +the same evidence gates; they are views of the same reconstruction, not two +independent measurements of the real road. +""" +import numpy as np +from scipy.signal import find_peaks,peak_widths +from interval_profiles import strip,runs +from line_reconstruction import observation + +POLICY=dict(max_angle_deg=4.,max_lateral_m=.65,min_overlap=.75, + min_valid=.95,min_keeper_support=.85,min_keeper_median=22., + max_ghost_support=.15,max_ghost_q75=8.,min_views=2, + max_keeper_ridge_offset_m=.08,min_source_ridge_offset_m=.10, + min_ridge_offset_advantage_m=.06,max_two_ridge_fraction=.10, + max_two_ridge_run_m=.25,max_view_ridge_disagreement_m=.05) + +def pair_geometry(source,target): + a,b=[observation(np.asarray(p.exterior.coords),'vector')for p in [source,target]] + if not (1.45POLICY['max_lateral_m']:return None + tt=(np.asarray(target.exterior.coords)-a['center'])@u + overlap=max(0.,min(a['L']/2,tt.max())-max(-a['L']/2,tt.min()))/a['L'] + if overlap=min(0,offset)-.12)&(ns<=max(0,offset)+.12) + pk,_=find_peaks(profile,height=18,prominence=max(8.,float(profile.max())*.20),distance=4) + pw=peak_widths(profile,pk,rel_height=.5)[0]*.025 + peaks=[dict(offset=float(ns[k]),width=float(w),height=float(profile[k]))for k,w in zip(pk,pw)if corridor[k]and .05=.10 for i in left for j in right)) + longest=max([(b-a)*.05 for a,b in runs(np.array(two))]or[0.]) + return dict(peaks=peaks,target_offset=offset,valid_fraction=float(allowed[:,corridor].mean()), + two_ridge_fraction=float(np.mean(two)),longest_two_ridge_m=longest, + offsets=ns.tolist(),profile=profile.tolist()) + +def observe_track(poly,sampler): + o=observation(np.asarray(poly.exterior.coords),'vector');u=o['axis'].astype(float);u/=np.linalg.norm(u) + trim=min(.15,o['L']*.08);ts=np.arange(-o['L']/2+trim,o['L']/2-trim,.05);ns=np.arange(-.80,.801,.025) + contrast,allowed=strip(o['center'],u,ts,ns,sampler) + band=abs(ns)<=max(.025,min(.05,o['W']*.25)) + signal=np.median(contrast[:,band],axis=1);valid=allowed[:,band].mean(1)>.85 + return dict(signal=signal,valid=valid) + +def decision(geometry,views,ridges=None): + records=[] + for source,target in views: + s,v=source['signal'],source['valid'];t,w=target['signal'],target['valid'] + if not len(s)or not len(t):return None,records + level=float(np.median(t[w]))if w.any()else 0.;cut=max(15.,.35*level) + rec=dict(source_valid=float(v.mean()),target_valid=float(w.mean()), + source_support=float(((s>cut)&v).mean()),target_support=float(((t>cut)&w).mean()), + source_q75=float(np.quantile(s[v],.75))if v.any()else 0.,target_median=level,cut=cut) + records.append(rec) + if len(records)POLICY['max_two_ridge_fraction'] or + r['longest_two_ridge_m']>=POLICY['max_two_ridge_run_m']for r in ridges):return None,records + # Strong containment is a geometric duplicate even if both sample paint. + # The retained full stroke must itself be image-supported in every view. + if geometry['contained_fraction']>=.90:return 'overlapping_duplicate',records + if ridges and len(ridges)>=POLICY['min_views']: + single=all(len(r['peaks'])==1 and r['valid_fraction']>=POLICY['min_valid']and + r['two_ridge_fraction']<=POLICY['max_two_ridge_fraction']and + r['longest_two_ridge_m']=POLICY['min_source_ridge_offset_m']and + abs(r['peaks'][0]['offset'])-abs(r['peaks'][0]['offset']-r['target_offset'])>=POLICY['min_ridge_offset_advantage_m']for r in ridges) + if aligned and max(offsets)-min(offsets)<=POLICY['max_view_ridge_disagreement_m']: + return 'one_ridge_two_vectors',records + if all(r['source_support']<=POLICY['max_ghost_support']and r['source_q75']=0)&(uv[:,1]>=0)&(uv[:,0]<1199)&(uv[:,1]<1199) + allowed=valid&(alpha>=.65)&(sample(labels,points,low,high)==1)&(veh<.20)&~shapely.contains_xy(protected,points[:,0],points[:,1]) + return colors,allowed + return read +linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['geometry']['type']=='Polygon'} +@lru_cache(maxsize=1500) +def observed(fid,name):return observe_track(linear[fid],sampler(name)) +pairs=[] +for sid,p in linear.items(): + for tid,q in linear.items(): + if sid==tid:continue + geom=pair_geometry(p,q) + if geom is not None:pairs.append((sid,tid,geom)) +# Nearby pairs share decoded tile images. Stable tie-breaking does not depend +# on street names, route distance or hard-coded coordinates. +pairs.sort(key=lambda x:(tuple(linear[x[0]].centroid.coords[0]),x[0],x[1])) +proposals=[];diagnostics=[] +for k,(sid,tid,geom)in enumerate(pairs): + center=np.array(linear[sid].centroid.coords[0]);ranked=sorted(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center)) + names=[];vertices=np.concatenate([np.asarray(linear[fid].exterior.coords)for fid in [sid,tid]]) + for tile in ranked: + uv=project(vertices,geometry(tile['id'])) + if uv.min()>=20 and uv.max()<1180:names.append(tile['id']) + if len(names)==2:break + views=[(observed(sid,name),observed(tid,name))for name in names] + ridges=[shared_ridge(linear[sid],linear[tid],sampler(name))for name in names] + kind,evidence=decision(geom,views,ridges);rec=dict(source_id=sid,target_id=tid,source_tiles=names,geometry=geom,views=evidence,ridges=ridges,kind=kind) + diagnostics.append(rec) + if kind:proposals.append(rec) + if k%50==0:print('PAIR',k,len(pairs),'CANDIDATES',len(proposals),flush=True) +# Greedy selection keeps every nominated keeper. A keeper can never later be +# removed, which avoids deletion cycles for coincident copies. +removed=set();keepers=set();accepted=[] +for rec in sorted(proposals,key=lambda r:(r['kind']!='unsupported_offset_duplicate',max(v['source_support']for v in r['views']),-min(v['target_support']for v in r['views']),r['source_id'])): + sid,tid=rec['source_id'],rec['target_id'] + if sid in removed or sid in keepers or tid in removed:continue + removed.add(sid);keepers.add(tid);p=linear[sid].union(linear[tid]);accepted.append({**rec,'bounds_xy':p.bounds,'source_ids':[sid],'output_ids':[tid],'source_tile':rec['source_tiles'][0]}) +result={**old,'features':[f for f in old['features']if f['id']not in removed],'consensus_refinement':'two-view-redundant-paint-v1'} +(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'consensus-rows.json').write_text(json.dumps(accepted,indent=2));(O/'consensus-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'consensus-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed)))) +(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(accepted),removed_duplicates=len(removed),offset_duplicates=sum(r['kind']=='unsupported_offset_duplicate'for r in accepted),overlapping_duplicates=sum(r['kind']=='overlapping_duplicate'for r in accepted),single_ridge_duplicates=sum(r['kind']=='one_ridge_two_vectors'for r in accepted),candidate_pairs=len(pairs),before_linear_objects=len(linear),after_linear_objects=len(linear)-len(removed),policy=POLICY,policy_version='two-view-redundant-paint-v1',manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'consensus-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/consensus_pass/render_consensus.py b/simulation/urban-plan-research/consensus_pass/render_consensus.py new file mode 100644 index 00000000..702a8a42 --- /dev/null +++ b/simulation/urban-plan-research/consensus_pass/render_consensus.py @@ -0,0 +1,41 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'consensus-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('rows-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='rows-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('rows-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'rows-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) +# Revisit every short-dash family shown in the prior delivery, using its stored +# bounds only for review framing; these bounds never enter the detector. +references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[] +for gi,rec in enumerate(references): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]): + frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640') + fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only')) +(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2)) diff --git a/simulation/urban-plan-research/consensus_pass/test_consensus.py b/simulation/urban-plan-research/consensus_pass/test_consensus.py new file mode 100644 index 00000000..8086e825 --- /dev/null +++ b/simulation/urban-plan-research/consensus_pass/test_consensus.py @@ -0,0 +1,54 @@ +import json,runpy,numpy as np +from consensus_profiles import pair_geometry,observe_track,decision,shared_ridge +from interval_profiles import rectangle +from shapely.geometry import Polygon +prior=runpy.run_path('/candidate/test_transitions.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +def obs(signal=80.,valid=True):return dict(signal=np.full(80,signal),valid=np.full(80,valid)) +g=dict(contained_fraction=0.,overlap_fraction=1.,lateral_m=.3) +checks['ghost_requires_supported_keeper']=decision(g,[(obs(0),obs())]*2)[0]=='unsupported_offset_duplicate' +checks['true_parallel_pair_retained']=decision(g,[(obs(),obs())]*2)[0]is None +checks['worn_parallel_paint_retained']=decision(g,[(obs(12),obs())]*2)[0]is None +checks['occluded_source_retained']=decision(g,[(obs(0,False),obs())]*2)[0]is None +checks['occluded_keeper_no_deletion']=decision(g,[(obs(0),obs(80,False))]*2)[0]is None +checks['disagreeing_views_no_deletion']=decision(g,[(obs(0),obs()),(obs(),obs())])[0]is None +checks['missing_second_view_no_deletion']=decision(g,[(obs(0),obs())])[0]is None +checks['blank_pair_retained']=decision(g,[(obs(0),obs(0))]*2)[0]is None +checks['overlapping_copies_resolved']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2)[0]=='overlapping_duplicate' +checks['overlap_alone_not_evidence']=decision({**g,'contained_fraction':.97},[(obs(0),obs(0))]*2)[0]is None +o=np.array([0.,0.]);u=np.array([1.,0.]);a=rectangle(o,u,0,6,.15,.35);b=rectangle(o,u,0,6,.15) +checks['parallel_geometry_candidate']=pair_geometry(a,b)is not None +checks['perpendicular_not_duplicate']=pair_geometry(a,rectangle(o,np.array([0.,1.]),0,6,.15))is None +checks['neighbor_lane_not_duplicate']=pair_geometry(a,rectangle(o,u,0,6,.15,3.5))is None +checks['short_overlap_not_duplicate']=pair_geometry(a,rectangle(o,u,5,11,.15))is None +def sampler(xy): + paint=(abs(xy[:,1])<.075)&(xy[:,0]>-.1)&(xy[:,0]<6.1) + return np.repeat(np.where(paint,210,65)[:,None],3,1).astype('uint8'),np.ones(len(xy),bool) +s,t=observe_track(a,sampler),observe_track(b,sampler);reason,_=decision(pair_geometry(a,b),[(s,t)]*2) +checks['image_profile_rejects_offset_ghost']=reason=='unsupported_offset_duplicate' +theta=.87;rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([125.,-71.]);ar=Polygon(np.asarray(a.exterior.coords)@rot.T+shift);br=Polygon(np.asarray(b.exterior.coords)@rot.T+shift) +read=lambda xy:sampler((xy-shift)@rot);sr,tr=observe_track(ar,read),observe_track(br,read) +checks['rigid_transform_invariance']=decision(pair_geometry(ar,br),[(sr,tr)]*2)[0]==reason +def blurred_sampler(xy): + value=65+140*np.exp(-.5*(xy[:,1]/.085)**2) + return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool) +a=rectangle(o,u,0,6,.15,.15);b=rectangle(o,u,0,6,.15) +s,t=observe_track(a,blurred_sampler),observe_track(b,blurred_sampler);ridge=shared_ridge(a,b,blurred_sampler) +checks['one_blurred_ridge_not_two_lines']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]=='one_ridge_two_vectors' +def dual_sampler(xy): + value=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.20)/.028)**2) + return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool) +a=rectangle(o,u,0,6,.10,.20);b=rectangle(o,u,0,6,.10) +s,t=observe_track(a,dual_sampler),observe_track(b,dual_sampler);ridge=shared_ridge(a,b,dual_sampler) +checks['two_physical_ridges_preserved']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]is None +checks['transverse_profile_resolves_two_ridges']=len(ridge['peaks'])==2 +# Intermittent neighbor paint must survive even if it vanishes in the median. +def intermittent(xy): + value=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.20)/.028)**2)*((xy[:,0]%1.5)<.4) + return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool) +s,t=observe_track(a,intermittent),observe_track(b,intermittent);ridge=shared_ridge(a,b,intermittent) +checks['intermittent_second_ridge_preserved']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]is None +checks['short_parallel_runs_detected']=ridge['longest_two_ridge_m']>=.25 +checks['real_second_ridge_vetoes_containment']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2,[ridge]*2)[0]is None +invalid={**ridge,'valid_fraction':.4,'two_ridge_fraction':0.,'longest_two_ridge_m':0.} +checks['unknown_transverse_corridor_preserved']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2,[invalid]*2)[0]is None +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/consensus-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/continuation_pass/README.rst b/simulation/urban-plan-research/continuation_pass/README.rst new file mode 100644 index 00000000..8c62ae10 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/README.rst @@ -0,0 +1,108 @@ +Urban infrastructure continuation pass — offline research +========================================================= + +This increment consumes the Gaussian-only v8 seed stage and the four-layer +Gaussian evidence bundle. It is a reusable downstream stage; it does not replace +or re-train the upstream Gaussian renderer, SAM3 paint proposals, Mapillary class +fusion or covariance-based first-floor facade observations. + +Uniform pipeline +---------------- + +1. Retain v8 object chains. Propose bounded line/arc simplification with a 0.45 m + maximum change from the seed, not a ground-truth accuracy claim. +2. Generate endpoint and trimmed-terminal alternatives. SciPy Hermite splines + interpolate candidate curves; HiGHS selects mutually exclusive continuations. + Explicit survey exits and known openings remain open. Scan support, road caps, + opposite surface sides, intersections and inferred loops are guarded. + A locally visible, unoccluded transport corridor vetoes a proposed cap even + when it occupies a small fraction of a long connection. Vehicle occlusion + is treated separately from observed open road. A 0.7 m morphological closing + removes sub-metre semantic pinholes for this veto only; it never draws curves. +3. Re-anchor the neighborhoods of selected connections. The existing normal-strip + dynamic program and weighted minimum-curvature fit use Gaussian appearance, + height, opacity, vehicle occlusion and sidewalk-side context. Missing evidence + receives zero observation weight. Other chain sections and scan terminals + remain fixed before the bounded final primitive fit. + Exterior road support is required for new curb anchors; a sidewalk/building + interface cannot attract a road curb. + Each automatic gap neighbourhood is admitted independently, even where + neighbourhoods overlap. A correction must improve its own evidence. Under + substantial vehicle occlusion it must not introduce extra curb turning. + Rejected corrections retain the joined parent geometry. Accepted corrections + fade over 3 m at their boundaries to avoid a seam with unchanged neighbours. +4. Diagnostic experiment only (not included in the selected result): propose + missing interfaces from one-sided observed sidewalk support. Exclude + measured facades, terrain, existing edges and crossing geometry. These carry + inferred-road-adjacency status and are not ground-truth road classifications. Cross-scene review found false plaza edges; + the same global decision excludes this addition on every scene. +5. Join measured frontage planes using OpenCV Huber fits, bounded gap/offset and + a veto for connecting through observed road surfaces. Short vertical planes + substantially supported by vehicle masks are rejected with their source IDs. + Hidden backs remain + unknown; the result is frontage lines, not closed building footprints. +6. Extract appearance components from native Gaussian ground renders. Semantic + proposals nominate objects, then whole components are tested. Counter topology + distinguishes A from arrows; arrow direction is conditioned on nearby road + orientation. OpenCV/SciPy fit reusable attributed SVG arrow presets and an + original parametric A. Unsupported candidates stay in a rejection record. + Object NMS after fitting removes duplicate glyphs from overlapping fragments; + nearby distinct glyphs remain separate. +7. Fit collinear paint as continuous or periodic families with common width and + period. Only bounded interior gaps are filled. Crosswalks and road-domain + checks constrain reconstruction. Previous admitted paint is retained unless + replaced. The pedestrian coverage layer is retained with refreshed curb IDs. + +Run contract +------------ + +All geometry/rendering/tests run in a reserved Worker006 container. Read-only +mounts: /base, /fullplan, /ortho, /survey, /multiview, /input; writable: /out. +The selected road variant is reanchored; recovered.json is rejected diagnostic +output. Run test_refine.py, refine_scene.py, assemble_plan.py, render_scene.py, +render_plan.py and audit_scene.py. The operator qualification harness records +an immutable source snapshot, image digest, timestamps, hashes and cleanup. +There are no scene-specific parameters, processing ROIs, station coordinates or +manual vector patches. Scene names only label the review images. + +The flat replay bundle is described by bundle.json. Review-font.ttf is a separate +optional Cyrillic-capable font used only by image rendering. Private scans and +renders are not included in source. No point cloud or collider is used. + +Evidence and limits +------------------- + +The independent audit checks finite valid XYZ, unique IDs, simple road chains, +road-chain crossings, new inferred intervals on the final geometry, protected open +ends, retained sidewalk coverage, curb references and accounting for every retained/rejected facade parent. +New inferred_spans describe this pass only. Inherited v8 inference and uncertainty +remain in the referenced source IDs and immutable seed/full-plan bundles; the +rest of a line is not certified as wholly observed. + +Controlled tests include known occlusions, real openings, sharp/rounded shapes, +rigid-coordinate transfer, repeated paint, symbol ambiguity and physical-edge +re-anchoring. These checks do not establish survey accuracy or detection recall. + +Whole-scene before/after images, all surveyed tiles, automatically chosen details, +every accepted road interpolation and every accepted glyph are retained for +visual review. Successful geometry checks alone are not visual acceptance. +The three existing development scenes are regression tests, not a new blind +holdout. A single common policy is an implementation property, not proof of +universal quality on arbitrary future scans. + +Known omissions: closed hidden building footprints; complete bicycle/parking +symbol vocabulary; guaranteed recovery of every line or crossing; independent +position-accuracy measurements. Retained pedestrian coverage silhouettes are +not resnapped to the engineering curves. Gaussian covariance candidates may also +include walls/fences rather than independently verified building identities. +No navigation permission or product/live-map publication is assigned. + +Artwork attribution +------------------- + +road_glyph_presets.py contains adapted arrow artwork by Major Alexey, 2015: +https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg +License: CC BY-SA 4.0, https://creativecommons.org/licenses/by-sa/4.0/ +Changes: SVG curve sampling, coordinate normalization, metric scaling and stroke +fitting. The attribution and share-alike license apply to this arrow artwork; +the normalized geometry and source strings are kept together in that module. diff --git a/simulation/urban-plan-research/continuation_pass/assemble_plan.py b/simulation/urban-plan-research/continuation_pass/assemble_plan.py new file mode 100644 index 00000000..d45c778b --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/assemble_plan.py @@ -0,0 +1,157 @@ +from pathlib import Path +from collections import Counter +import json,os,time,hashlib +import numpy as np,cv2,shapely +from shapely.geometry import shape,Polygon,LineString,mapping +from shapely.ops import transform +from scipy.ndimage import distance_transform_edt +from layer_common import O,S,B,feature,parts,sample +from fit_scene import world +from plan_primitives import regularize_paint +from frontage_chains import join_planes +from paint_templates import fit_symbol +from crosswalk_family import rectangle_info,joint_rectangles +cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text());base=json.loads((O/'whole-map.json').read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +with np.load('/fullplan/fields.npz')as f:labels=f['labels'];height=f['z'];low,high=f['bounds'];cell=float(f['cell']) +road=labels==1 +# Reuse measured pedestrian coverage. Shared curb references are refreshed. +walk=[f for f in old['features']if f['properties']['class']in ['pedestrian_area','pedestrian_boundary']] +for item in walk: + if item['properties']['class']=='pedestrian_area':item['properties']['physical_boundary_ids']=[f['id']for f in base['features']if shape(f['geometry']).distance(shape(item['geometry']))<.6] +def lift(g): + def project(x,y,z=None):return x,y,sample(height,np.c_[x,y],low,high) + return transform(project,g) +allfacades=[f for f in old['features']if f['properties']['class']=='building_facade'];rawfacades=[];rejected_facades=[] +with np.load(O/'occluder-field.npz')as occ:vehicle_field=occ['vehicle'] +for item in allfacades: + line=shapely.force_2d(shape(item['geometry']));p=np.array([line.interpolate(t).coords[0]for t in np.linspace(0,line.length,max(3,int(line.length/.2)))]) + fraction=float(np.mean(sample(vehicle_field,p,low,high)>.5)) + if line.length<12 and fraction>.35:rejected_facades.append(dict(source_id=item['id'],reason='vehicle-supported-vertical-plane',vehicle_fraction=fraction));continue + rawfacades.append(item) +(O/'rejected-facades.json').write_text(json.dumps(rejected_facades,indent=2)) +planes=[shapely.force_2d(shape(f['geometry']))for f in rawfacades] +def facade_bridge_allowed(line,sources): + novel=line.difference(shapely.union_all(sources).buffer(.2)) + for segment in parts(novel,'LineString'): + if segment.length<.4:continue + p=np.array([segment.interpolate(t).coords[0]for t in np.linspace(0,segment.length,max(3,int(segment.length/.2)))]) + if np.mean(sample(labels,p,low,high)==1)>.2:return False + return True +joined=join_planes(planes,offset=.45,gap=8.,bridge_validator=facade_bridge_allowed);facades=[] +for p,ids in joined: + facades.append(feature(lift(LineString(p)),'building_facade',method='huber-frontage-chain-with-bounded-infill',source_ids=[rawfacades[i]['id']for i in ids],closed_footprint=False,hidden_backs_invented=False,schematic_join=True)) +# Detect paint in the detailed Gaussian ground image, then fit reusable geometry. +paint_candidates=[];rejected=[];cross_candidates=[] +road_dist=distance_transform_edt(~road)*cell +for tile in tiles: + name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));m=np.load(Path('/fullplan/evidence')/(name+'.npz'));veh=np.load(Path('/ortho/evidence')/(name+'.normal.npz'))['vehicle'];path=Path('/ortho/evidence')/(name+'.ground.png') + from PIL import Image + im=np.asarray(Image.open(path).convert('RGB'));size=im.shape[0];mpp=60/size;small=lambda a:cv2.resize(a.astype('float32'),(size,size),interpolation=cv2.INTER_LINEAR) + marking=small(m['road marking']);cross=small(m['crosswalk']);vehicles=cv2.dilate((small(veh)>.25).astype('uint8'),np.ones((max(3,int(.25/mpp)),)*2,np.uint8))>0 + hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV);gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY);contrast=gray.astype('float32')-cv2.GaussianBlur(gray.astype('float32'),(0,0),.35/mpp) + paint=((hsv[:,:,1]<85)&(gray>115)&(contrast>9))|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>55)&(gray>100)&(contrast>5)) + yy,xx=np.mgrid[:size,:size];lo,hi=np.asarray(tile['bounds_xy']) + road_patch=cv2.resize(road[max(0,int(round((high[1]-hi[1])/.1))):int(round((high[1]-lo[1])/.1)),max(0,int(round((lo[0]-low[0])/.1))):int(round((hi[0]-low[0])/.1))].astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0 + candidate=paint&road_patch&~vehicles + candidate=cv2.morphologyEx(candidate.astype('uint8'),cv2.MORPH_CLOSE,np.ones((max(3,int(.04/mpp)),)*2,np.uint8)) + contours,hier=cv2.findContours(candidate,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE) + if hier is None:continue + def xy_native(p):return world((np.asarray(p)+.5)*1200/size-.5,g) + for i,c in enumerate(contours): + if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.06:continue + rect=cv2.minAreaRect(c);short,long=sorted(rect[1]);short*=mpp;long*=mpp + if short<.045 or long<.35 or short>5:continue + ring=cv2.approxPolyDP(c,.035/mpp,True)[:,0];holes=[];j=hier[0,i,2] + while j>=0: + if cv2.contourArea(contours[j])*mpp*mpp>.03:holes.append(xy_native(cv2.approxPolyDP(contours[j],.035/mpp,True)[:,0])) + j=hier[0,j,0] + poly=shapely.make_valid(Polygon(xy_native(ring),holes)) + if poly.geom_type!='Polygon':continue + coords=np.array(poly.exterior.coords);supported=np.mean(sample(road_dist,coords,low,high)<.75) + if supported<.5:continue + rxy=np.rint(rect[0]).astype(int);rxy=np.clip(rxy,0,size-1);is_cross=cross[rxy[1],rxy[0]]>.3 + if is_cross and .182 and poly.area/(short*long)>.55: + box=Polygon(xy_native(cv2.boxPoints(rect)));cross_candidates.append((box,dict(source_tile=name,subtype='crosswalk',method='parametric-rectangle'))) + else: + x,y,bw,bh=cv2.boundingRect(c);patch=np.zeros((bh,bw),np.uint8);cv2.drawContours(patch,[c-np.array([[[x,y]]])],-1,1,-1) + values=marking[y:y+bh,x:x+bw][patch>0] + paint_candidates.append((poly,dict(source_tile=name,semantic_support=float(np.mean(values)),semantic_peak=float(np.quantile(values,.9))))) + m.close();print('PAINT',name,len(paint_candidates),len(cross_candidates),flush=True) +def dedup(records): + result=[] + for p,props in sorted(records,key=lambda x:-x[0].area): + if any(p.intersection(q).area/min(p.area,q.area)>.5 for q,_ in result):continue + result.append((p,props)) + return result +cross_candidates=dedup(cross_candidates);paint_candidates=dedup(paint_candidates);paint=[] +# Group neighboring parallel stripes without fixture coordinates, then run existing joint fit. +obs=[] +for i,(p,props)in enumerate(cross_candidates): + points=np.asarray(p.exterior.coords);box,center,u,v=rectangle_info(points);obs.append(dict(id=str(i),points=points,box=box,center=center,u=u,v=v)) +parent=list(range(len(obs))) +def root(i): + while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i] + return i +for i,a in enumerate(obs): + for j,b in enumerate(obs[:i]): + delta=a['center']-b['center'] + if abs(a['u']@b['u'])>np.cos(np.deg2rad(12))and abs(delta@a['u'])<1 and abs(delta@a['v'])<2:parent[root(i)]=root(j) +groups={} +for i in range(len(obs)):groups.setdefault(root(i),[]).append(i) +for ids in groups.values(): + if len(ids)<3:rejected.extend(dict(kind='crosswalk',reason='insufficient-family-support')for i in ids);continue + fitted,rec=joint_rectangles([obs[i]for i in ids]) + if not rec['optimizer_success']or rec['boundary_residual_p95_m']>.15:rejected.append(dict(kind='crosswalk',reason='joint-fit-disagreement',stripes=len(ids)));continue + for f,i in zip(fitted,ids):paint.append(feature(lift(Polygon(f['points'])),'road_marking',**cross_candidates[i][1],family_size=len(ids),fit_p95_m=f['fit_p95_m'])) +for p,props in paint_candidates: + if any(p.intersection(q).area>.2*p.area for q,_ in cross_candidates):continue + if props.get('semantic_support',0)<.10 or props.get('semantic_peak',0)<.3: + rejected.append(dict(kind='paint',reason='appearance-without-object-support',geometry=mapping(p),**props));continue + fitted,method=regularize_paint(p) + if method=='parametric-paint-strip': + paint.append(feature(lift(fitted),'road_marking',subtype='linear_marking',method=method,**props));continue + rect=cv2.minAreaRect(np.asarray(p.exterior.coords,np.float32));a,b=sorted(rect[1]);iou=p.area/max(a*b,1e-8) + if a>.045 and a<.5 and b>.5 and b/a>3 and iou>.72 and not p.interiors: + paint.append(feature(lift(Polygon(cv2.boxPoints(rect))),'road_marking',subtype='linear_marking',method='rectangle-template',**props));continue + # Recognize a whole appearance component; model support may cover only part + # of a worn glyph. It must still locate the object, preventing symbols on noise. + if props.get('semantic_support',0)<.14 or props.get('semantic_peak',0)<.35: + rejected.append(dict(kind='symbol',reason='no-object-semantic-support',geometry=mapping(p),**props));continue + center=p.centroid;nearest=min((shapely.force_2d(shape(x['geometry']))for x in base['features']),key=lambda x:x.distance(center)) + station=nearest.project(center);head=np.asarray(nearest.interpolate(min(nearest.length,station+5)).coords[0])-np.asarray(nearest.interpolate(max(0,station-5)).coords[0]) + f=fit_symbol(p,heading=head if np.linalg.norm(head)>1 else None) + if f is not None: + fitted,iou,kind,recall,params=f + axis=np.array([np.cos(params[2]),np.sin(params[2])]);center=fitted.centroid;aligned=False + for boundary in base['features']: + line=shapely.force_2d(shape(boundary['geometry'])) + if line.distance(center)>12:continue + station=line.project(center);a=np.asarray(line.interpolate(max(0,station-3)).coords[0]);b=np.asarray(line.interpolate(min(line.length,station+3)).coords[0]);t=b-a;t/=max(np.linalg.norm(t),1e-8) + if abs(t@axis)>.88:aligned=True;break + if aligned:paint.append(feature(lift(fitted),'road_marking',subtype=kind,method='symbol-template',template_fit_score=iou,fit_recall=recall,template_parameters=params,**props)) + else:rejected.append(dict(kind='symbol',reason='incompatible-street-direction',geometry=mapping(p),**props)) + else:rejected.append(dict(kind='symbol',reason='no-template-admitted',geometry=mapping(p),**props)) + +from paint_dedup import deduplicate_glyphs +paint,glyph_dedup_audit=deduplicate_glyphs(paint) +(O/'glyph-dedup.json').write_text(json.dumps(glyph_dedup_audit,allow_nan=False)) +# Preserve previous admitted paint if the new appearance pass has no replacement. +oldpaint=[f for f in old['features']if f['properties']['class']=='road_marking'] +newpaint=list(paint) +for prior in oldpaint: + p=shape(prior['geometry']) + if not any(p.intersection(shape(f['geometry'])).area/max(min(p.area,shape(f['geometry']).area),1e-8)>.45 for f in paint):newpaint.append(prior) +from paint_families import normalize +crossing_geometry=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in newpaint if f['properties'].get('subtype')=='crosswalk']) +def admit_family(poly): + if poly.intersection(crossing_geometry).area>.04:return False + line=LineString(np.asarray(poly.exterior.coords)[:,:2]);p=np.array([line.interpolate(s).coords[0]for s in np.linspace(0,line.length,max(5,int(line.length/.3)))]) + return np.mean(sample(labels,p,low,high)==1)>.8 +retained_old_paint=len(newpaint)-len(paint) +newpaint,family_audit=normalize(newpaint,lift,admit_family) +(O/'paint-families.json').write_text(json.dumps(family_audit,allow_nan=False)) +result={**base,'schema_version':'missioncore.refined-full-plan-research/v1','features':base['features']+walk+facades+newpaint,'logical_layers':['roads','pedestrian_zones','buildings','road_markings'],'review_status':'unreviewed'} +assert all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in result['features']) +(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'unresolved-markings.json').write_text(json.dumps(rejected,allow_nan=False)) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,counts=dict(Counter(f['properties']['class']for f in result['features'])),paint_subtypes=dict(Counter(f['properties'].get('subtype')for f in newpaint)),old_counts=dict(Counter(f['properties']['class']for f in old['features'])),new_detected_paint=len(paint),retained_old_paint=retained_old_paint,normalized_paint_count=len(newpaint),facade_parents=len(planes),rejected_vehicle_facades=len(rejected_facades),facade_chains=len(facades),manual_geometry=False,metric_accuracy_measured=False,source_fullplan_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest()) +(O/'full-plan-report.json').write_text(json.dumps(report,indent=2));print('FULL-PLAN',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/continuation_pass/audit_scene.py b/simulation/urban-plan-research/continuation_pass/audit_scene.py new file mode 100644 index 00000000..de247684 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/audit_scene.py @@ -0,0 +1,49 @@ +"""Independent geometry/provenance audit. Not a substitute for labelled truth.""" +from pathlib import Path +from collections import Counter +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape,LineString,Point +from scipy.spatial import cKDTree +O=Path('/out') +doc=json.loads((O/'full-map.json').read_text());old=json.loads(Path('/fullplan/full-map.json').read_text()) +features=doc['features'];checks={};warnings=[] +checks['unique_feature_ids']=len({f['id']for f in features})==len(features) +checks['finite_valid_3d']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in features) +roads=[f for f in features if f['properties']['class']=='road_boundary'];geom=[shapely.force_2d(shape(f['geometry']))for f in roads] +checks['all_road_chains_simple']=all(g.is_simple for g in geom) +crossings=[[roads[i]['id'],roads[j]['id']]for i,a in enumerate(geom)for j,b in enumerate(geom[:i])if a.crosses(b)] +checks['no_road_chain_crossings']=not crossings +span_lengths=[] +for f,g in zip(roads,geom): + for span in f['properties'].get('inferred_spans',[]): + a,b=span['station_interval_m'];h=LineString(np.array(span['coordinates'])[:,:2]) + assert 0<=a<=b<=g.length+1e-5 + assert h.difference(g.buffer(.0001)).length<.001 + span_lengths.append(b-a) +checks['inferred_spans_on_final_geometry']=True +base=json.loads(Path('/base/whole-map.json').read_text()) +protected=[] +for f in base['features']: + if f['properties']['class']!='road_boundary':continue + for key,idx in [('start_reason',0),('end_reason',-1)]: + if f['properties'].get(key)in ['scan-limit','known-opening','survey-exterior']:protected.append(f['geometry']['coordinates'][idx][:2]) +endpoints=np.array([p for g in geom for p in [g.coords[0],g.coords[-1]]]) +checks['explicit_open_ends_preserved']=not protected or bool(np.max(cKDTree(endpoints).query(protected)[0])<.001) +oldwalk={f['id']:f['geometry']for f in old['features']if f['properties']['class'].startswith('pedestrian_')} +newwalk={f['id']:f['geometry']for f in features if f['properties']['class'].startswith('pedestrian_')} +checks['pedestrian_coverage_retained']=oldwalk==newwalk +roadids={f['id']for f in roads} +checks['pedestrian_curb_references_exist']=all(set(f['properties'].get('physical_boundary_ids',[]))<=roadids for f in features if f['properties']['class']=='pedestrian_area') +facades=[f for f in features if f['properties']['class']=='building_facade'] +parents={f['id']for f in old['features']if f['properties']['class']=='building_facade'} +rejected_facades=json.loads((O/'rejected-facades.json').read_text());rejected_ids={r['source_id']for r in rejected_facades} +retained_ids=set(p for f in facades for p in f['properties']['source_ids']) +checks['every_facade_parent_accounted']=retained_ids|rejected_ids==parents and not(retained_ids&rejected_ids) +checks['no_invented_closed_building_backs']=all(f['properties']['closed_footprint']is False for f in facades) +glyphs=[shapely.force_2d(shape(f['geometry'])).convex_hull for f in features if f['properties'].get('method')=='symbol-template'] +checks['no_duplicate_fitted_symbols']=not any(a.intersection(b).area/max(a.union(b).area,1e-9)>.6 for i,a in enumerate(glyphs)for b in glyphs[:i]) +families=json.loads((O/'paint-families.json').read_text()) +stats=dict(road_chains=len(roads),inferred_road_span_m=sum(span_lengths),recovered_interface_chains=sum(f['properties'].get('class_status')=='inferred-road-adjacency'for f in roads),facade_chains=len(facades),facade_parents=len(parents),paint_family_count=len(families),filled_dash_slots=sum(x['added_internal_m_or_slots']for x in families if x['method']=='periodic-dash-family'),filled_continuous_paint_m=sum(x['added_internal_m_or_slots']for x in families if x['method']=='continuous-paint-family'),counts=dict(Counter(f['properties']['class']for f in features))) +report=dict(passed=all(checks.values()),checks=checks,stats=stats,road_crossings=crossings,full_map_sha256=hashlib.sha256((O/'full-map.json').read_bytes()).hexdigest(),accuracy_measured=False,completeness_measured=False,warnings=['Reference scenes are regression cases, not independent unseen acceptance scenes.','Schematic facade lines do not reconstruct unseen building backs.','Object counts are not precision or recall.']) +(O/'geometry-audit.json').write_text(json.dumps(report,indent=2));print(json.dumps(report),flush=True) +assert report['passed'],checks diff --git a/simulation/urban-plan-research/continuation_pass/bundle.json b/simulation/urban-plan-research/continuation_pass/bundle.json new file mode 100644 index 00000000..6a3496fc --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/bundle.json @@ -0,0 +1,57 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "assemble_plan.py": "continuation_pass/assemble_plan.py", + "audit_scene.py": "continuation_pass/audit_scene.py", + "boundary_anchors.py": "boundary_anchors.py", + "continuations.py": "continuation_pass/continuations.py", + "crosswalk_family.py": "full_plan/crosswalk_family.py", + "evidence_fields.py": "continuation_pass/evidence_fields.py", + "fit_scene.py": "full_plan/fit_scene.py", + "frontage_chains.py": "continuation_pass/frontage_chains.py", + "layer_common.py": "full_plan/layer_common.py", + "object_solver.py": "continuation_pass/object_solver.py", + "paint_dedup.py": "continuation_pass/paint_dedup.py", + "paint_families.py": "continuation_pass/paint_families.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "plan_continuity.py": "plan_continuity.py", + "plan_primitives.py": "plan_primitives.py", + "plan_shapes.py": "plan_shapes.py", + "reanchor.py": "continuation_pass/reanchor.py", + "recover_interfaces.py": "continuation_pass/recover_interfaces.py", + "refine_scene.py": "continuation_pass/refine_scene.py", + "render_plan.py": "continuation_pass/render_plan.py", + "render_scene.py": "continuation_pass/render_scene.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "test_refine.py": "continuation_pass/test_refine.py" + }, + "reference_qualification": "continuation-pass-20261012", + "source_sha256": { + "assemble_plan.py": "779623e96ef76e9342bfff4bd65d6c82374a86596fe2d24189545d78d5262da1", + "audit_scene.py": "68606475be2906b0636db510f5016d8e7a2eb2d067d606351e266b98273a77e7", + "boundary_anchors.py": "312a5501efaacc166df291dff6146f71d29a7745c6192db0d06233ed4f11c8de", + "continuations.py": "d4637fc054b8bec765892659a252380abb903bc49c0b829add168babbc42aa7f", + "crosswalk_family.py": "68ee6327a7a24ab74e77bdbbc9c504562f6997cfb7f0e6082095b3e2eb32fc2d", + "evidence_fields.py": "66b5e019e386bcedabf64c62e0346dc7cd181b127d41eebdbfeb63a0e1d8a61e", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "frontage_chains.py": "e1be517d92686b36489dd7fe2f2448ad8274a07a1be069d166dd7218d2c9d4ad", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "object_solver.py": "b7969ce51887642c844a60e2ffc178a6b7cb0b5aa8d0a286a540e912c1ce197d", + "paint_dedup.py": "eb943e240f3077639f6dc9a4f4fa00646bb4ddf9a0630360516f5880fc8787a1", + "paint_families.py": "71bc387773377b7029acd092bbd7f705e73a61e8d1aa9ae17c10974cd754b16d", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "plan_continuity.py": "f4b2754e84b7d2d9ffe670cc9f069cb3e889061c7dd883bf01def4b921dc24be", + "plan_primitives.py": "7dbf29048a095cc8378e0f07817222b670009bb82018bbaa85f8aa80ab9a67b8", + "plan_shapes.py": "3b7a6b4520e8efc8afbdb44158eb7a74478f9c586dea63fd0af46e50894d6d4f", + "reanchor.py": "0836d631a1b04d2663d7a14bfa5e75bc69d9f737a41764338c4bd9f94ff1b695", + "recover_interfaces.py": "e743844b5f3b4484df2b7f4e244b955c7ecd13d610143c0f694a31419b53ceff", + "refine_scene.py": "d98595a6f4becea37790130498543df862d7369601fcdf440db55f1e24aac946", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "render_scene.py": "c03dd6d2fdcfa0ab4cd71cd4e457531558bae2d4f008e0682e7467e036364c86", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "test_refine.py": "fa5a9470a1782e621b686be34b7c7454503410b97f5584cfa785da8041066b46" + }, + "external_review_font": "review-font.ttf (Cyrillic-capable; rendering only)", + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/continuation_pass/continuations.py b/simulation/urban-plan-research/continuation_pass/continuations.py new file mode 100644 index 00000000..1163b7dc --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/continuations.py @@ -0,0 +1,187 @@ +"""Conservative primitive fitting and endpoint-graph completion of accepted seeds. + +All distances are metric. SciPy splines/HiGHS and GEOS implement interpolation, +joint endpoint assignment and geometric checks. No scene-specific coordinates. +""" +from dataclasses import dataclass,asdict,replace +import numpy as np,shapely +from shapely.geometry import LineString +from scipy.spatial import cKDTree +from scipy.interpolate import CubicHermiteSpline +from scipy.optimize import milp,Bounds,LinearConstraint +from scipy.sparse import coo_matrix +from object_solver import fit_chain,sample_chain,Policy,stations + +@dataclass(frozen=True) +class ContinuationPolicy: + sample_m:float=.4 + max_gap_m:float=18. + max_heading_degrees:float=65. + min_support_m:float=2. + fit_max_deviation_m:float=.45 + fit_residual_m:float=.24 + unresolved_cost:float=2.5 + maximum_terminal_revision_m:float=6. + +def observed_crossing_length(curve,road_at,alpha_at,vehicle_at,step=.2): + """Longest unoccluded road strip crossed by a proposed boundary. + + An absolute local run matters: a narrow side street must not be diluted by + the length of a much longer proposed bridge. Vehicle occlusion is unknown, + not evidence for an open transport corridor. + """ + p=sample_chain(np.asarray(curve)[:,:2],step) + t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8) + n=np.c_[-t[:,1],t[:,0]] + exposed=np.ones(len(p),bool) + for offset in [-1.,0.,1.]: + q=p+offset*n + exposed&=(road_at(q)>.65)&(alpha_at(q)>.7)&(vehicle_at(q)<.25) + longest=run=0. + for visible in exposed: + run=run+step if visible else 0. + longest=max(longest,run) + return float(longest) + +def regularize(points,policy=ContinuationPolicy()): + raw=np.asarray(points,float);p=sample_chain(raw[:,:2],policy.sample_m) + if len(p)<5 or LineString(p).is_ring:return raw,None + fit=fit_chain(p,np.ones(len(p)),replace(Policy(),residual_scale_m=policy.fit_residual_m,reliable_residual_limit_m=policy.fit_max_deviation_m),complexity_scale=1.3) + if fit is None:return raw,None + q=fit['points'].copy();q[[0,-1]]=raw[[0,-1],:2] + g=LineString(q);old=LineString(raw[:,:2]);deviation=float(shapely.hausdorff_distance(g,old,densify=.2)) + if not g.is_simple or deviation>policy.fit_max_deviation_m or g.length>old.length*1.01:return raw,None + # Preserve Z only by the source station; this is schematic XY regularization. + if raw.shape[1]>2: + st=np.array(shapely.line_locate_point(old,shapely.points(q)));old_s=stations(raw[:,:2]);q=np.c_[q,np.interp(st,old_s,raw[:,2])] + return q,dict(primitives=fit['primitives'],maximum_change_m=deviation) + +def endpoint_tangents(p,end): + q=sample_chain(np.asarray(p)[::1 if end==0 else -1,:2],.25) + s=stations(q);result=[] + for reach in [1.5,3.,6.]: + sub=q[s<=reach] + if len(sub)<5:continue + origin=sub.mean(0);_,_,v=np.linalg.svd(sub-origin,full_matrices=False);u=v[0] + if u@(sub[0]-sub[-1])<0:u=-u + n=np.array([-u[1],u[0]]);error=float(np.quantile(abs((sub-origin)@n),.9)) + if error>.25:continue + if not any(u@x[0]>.995 for x in result):result.append((u,error,reach)) + return result + +def connect(records,evaluate=None,policy=ContinuationPolicy()): + """Return joined chains plus all admissible/rejected endpoint alternatives. + + evaluate(curve, left_arm, right_arm) provides observation evidence and rejection. + Endpoint membership is globally optimized; no assumed contour walk is used. + """ + ends=[];checks=[];options=[] + for i,r in enumerate(records): + p=np.asarray(r['points']) + if LineString(p[:,:2]).is_ring:continue + for e in [0,1]: + if r.get('reasons',[None,None])[e]in ['scan-limit','known-opening','survey-exterior']:continue + # A seam may end in an erroneous hook. Propose alternatives from + # earlier supported stations, with an explicit cost for removed tail. + s=stations(p[:,:2]);length=s[-1] + for trim in [0.,1.,2.,4.,6.]: + if trim>policy.maximum_terminal_revision_m or length-trim2 and abs(pa[2]-pb[2])>.5+.12*gap:continue + for factor in [.35,.7,1.]: + t=np.linspace(0,1,max(5,int(gap/.2)+1)) + xy=CubicHermiteSpline([0,1],np.stack([pa[:2],pb[:2]]),np.stack([ta,-tb])*gap*factor)(t) + curve=np.c_[xy,pa[2]+t*(pb[2]-pa[2])]if len(pa)>2 else xy + line=LineString(xy);check['status']='shape' + if not line.is_simple or line.length>gap*1.2:continue + if not LineString(np.vstack([left[:,:2],xy[1:],right[1:,:2]])).is_simple:continue + if any(line.intersects(g)for k,g in enumerate(geometries)if k not in [i,j]):continue + check['status']='evidence' + ev=evaluate(curve,left,right)if evaluate else dict(allowed=True,reward=0.) + if not ev['allowed']: + check['rejection']=ev.get('reason');continue + bend=float(np.sum(np.linalg.norm(np.diff(np.diff(xy,axis=0),axis=0),axis=1))) + cost=gap/policy.max_gap_m+1.3*(2-ta@direction+tb@direction)+.2*bend-.7*ev.get('reward',0.)+.18*(ea['trim_m']+eb['trim_m']) + curve_options.append(dict(a=a,b=b,i=i,j=j,slots=[ea['slot'],eb['slot']],curve=curve,cost=float(cost),gap_m=float(gap),evidence=ev,tangent_reaches=[reach_a,reach_b])) + if not curve_options:continue + # Keep genuinely different geometric options, with the same data objective. + kept=[] + for c in sorted(curve_options,key=lambda x:x['cost']): + if any(LineString(c['curve'][:,:2]).hausdorff_distance(LineString(k['curve'][:,:2]))<.12 for k in kept):continue + kept.append(c) + if len(kept)==3:break + check.update(status='candidate',alternatives=len(kept));options.extend(kept) + if not options:return records,dict(candidates=checks,selected=[],reason='no-admissible-continuation') + rows=[];cols=[];vals=[];lb=[];ub=[] + slots=sorted(set(e['slot']for e in ends)) + for slot_index,endpoint in enumerate(slots): + row=len(lb);lb.append(1);ub.append(1) + for k,o in enumerate(options): + if endpoint in o['slots']:rows.append(row);cols.append(k);vals.append(1) + rows.append(row);cols.append(len(options)+slot_index);vals.append(1) + for i,a in enumerate(options): + ga=LineString(a['curve'][:,:2]) + for j,b in enumerate(options[:i]): + if set(a['slots'])&set(b['slots']):continue + if ga.intersects(LineString(b['curve'][:,:2])): + row=len(lb);lb.append(-np.inf);ub.append(1);rows.extend([row,row]);cols.extend([i,j]);vals.extend([1,1]) + costs=[x['cost']for x in options]+[policy.unresolved_cost]*len(slots) + A=coo_matrix((vals,(rows,cols)),shape=(len(lb),len(costs))).tocsc() + fit=milp(costs,integrality=np.ones(len(costs)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options={'time_limit':30,'mip_rel_gap':.001}) + if fit.x is None:raise RuntimeError(fit.message) + chosen=[options[i]for i in np.flatnonzero(fit.x[:len(options)]>.5)] + # No inferred road loop closure. Preserve the lowest cost forest explicitly. + parent=list(range(len(records)));links={};selected=[];cycles=[];trimmed={} + def root(i): + while parent[i]!=i:i=parent[i] + return i + for c in sorted(chosen,key=lambda x:x['cost']): + i,j=c['i'],c['j'] + if root(i)==root(j):cycles.append([records[i]['id'],records[j]['id']]);continue + parent[root(i)]=root(j);ea,eb=ends[c['a']],ends[c['b']] + links[i,ea['end']]=(j,eb['end'],c['curve']);links[j,eb['end']]=(i,ea['end'],c['curve'][::-1]);selected.append(c) + trimmed[i,ea['end']]=ea['point'];trimmed[j,eb['end']]=eb['point'] + out=[];seen=set();reverted=set() + for seed in range(len(records)): + if seed in seen:continue + members=[i for i in range(len(records))if root(i)==root(seed)] + start=next(((i,e)for i in members for e in [0,1]if(i,e)not in links),None) + if start is None: + out.extend(records[i]for i in members);seen.update(members);continue + i,entry=start;pts=[];source_ids=[];spans=[] + while i not in seen: + seen.add(i);rec=records[i];p=rec['points'] + lo=int(np.argmin(np.linalg.norm(p[:,:2]-trimmed[i,0][:2],axis=1)))if(i,0)in trimmed else 0 + hi=int(np.argmin(np.linalg.norm(p[:,:2]-trimmed[i,1][:2],axis=1)))if(i,1)in trimmed else len(p)-1 + assert lo.5;low,high=f['bounds'];h,w=side.shape +with np.load('/multiview/mapillary/atlas-sparse.npz')as f: + assert np.allclose(f['bounds'],[low,high]);assert np.isclose(f['cell_m'],cell) + rows,cols=f['rows'],f['cols'];post=f['posterior'];raw=[] + for i in range(6): + a=np.zeros((h,w),np.float32);a[rows,cols]=post[i].astype('float32');raw.append(a) + del rows,cols,post +road,walk,occ,structure,terrain,other=raw +# Close only sub-metre class-mask pinholes, such as paint and rail artefacts. +# This stable transport support is a topology veto, never generated road geometry. +transport=cv2.morphologyEx((road>.5).astype('uint8'),cv2.MORPH_CLOSE,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))).astype('float32') +rgb=np.full((h,w,3),255,np.uint8);z=np.full((h,w),np.nan,np.float32);alpha=np.zeros((h,w),np.float32);best=alpha.copy();vehicle=alpha.copy() +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +for tile in tiles: + name=tile['id'];lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/cell).astype(int) + x,y=np.rint([(lo[0]-low[0])/cell,(high[1]-hi[1])/cell]).astype(int);sl=np.s_[y:y+th,x:x+tw] + small=lambda a:cv2.resize(a.astype('float32'),(tw,th),interpolation=cv2.INTER_AREA) + with np.load(E/(name+'.ground-dc.geometry.npz'))as g: + aa=small(g['alpha']);zz=small(g['view'][2,3]-g['depth']) + with np.load(E/(name+'.normal.npz'))as g:vehicle[sl]=np.maximum(vehicle[sl],small(g['vehicle'])) + im=np.asarray(Image.open(E/(name+'.ground.png')).convert('RGB').resize((tw,th),Image.Resampling.LANCZOS)) + yy,xx=np.mgrid[:th,:tw];central=np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy]);score=(.05+central/max(tw,th))*aa + take=score>best[sl];rgb[sl][take]=im[take];z[sl][take]=zz[take];alpha[sl][take]=aa[take];best[sl][take]=score[take] + inputs[str(E/(name+'.ground.png'))]=digest(E/(name+'.ground.png')) + inputs[str(E/(name+'.ground-dc.geometry.npz'))]=digest(E/(name+'.ground-dc.geometry.npz')) + inputs[str(E/(name+'.normal.npz'))]=digest(E/(name+'.normal.npz')) +print('OBSERVATIONS',h,w,len(tiles),'seconds',round(time.monotonic()-T,1),flush=True) +fields=PhysicalFields(rgb,z,alpha,np.maximum(vehicle,occ),road,walk,cell,AnchorPolicy()) diff --git a/simulation/urban-plan-research/continuation_pass/frontage_chains.py b/simulation/urban-plan-research/continuation_pass/frontage_chains.py new file mode 100644 index 00000000..8fa4e54a --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/frontage_chains.py @@ -0,0 +1,41 @@ +"""Joint frontage-plane fitting. No footprint, area fill or hidden building back.""" +import numpy as np,cv2 +from shapely.geometry import LineString,Point + +def join_planes(lines,offset=.3,gap=2.,bridge_validator=None): + records=[(np.asarray(x.coords)[:,:2],[i]) for i,x in enumerate(lines)];changed=True + while changed: + changed=False + for i,(a,ids) in enumerate(records): + u=a[-1]-a[0];u/=np.linalg.norm(u);n=np.array([-u[1],u[0]]) + for j in range(i+1,len(records)): + b,jds=records[j];v=b[-1]-b[0];v/=np.linalg.norm(v) + if abs(u@v)offset:continue + tb=(b-a[0])@u;span=max(0,float(tb.min())-np.linalg.norm(a[-1]-a[0]),-float(tb.max())) + if span>gap:continue + samples=[] + for idx in ids+jds: + old=lines[idx];samples.extend([old.interpolate(t).coords[0][:2] for t in np.linspace(0,old.length,max(2,int(old.length/.2)))]) + p=np.asarray(samples);fit=cv2.fitLine(p.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();axis=fit[:2];o=fit[2:];normal=np.array([-axis[1],axis[0]]) + if abs((p-o)@normal).max()>offset:continue + t=(p-o)@axis;q=o+np.array([t.min(),t.max()])[:,None]*axis;l=LineString(q) + if bridge_validator is not None and not bridge_validator(l,[lines[k]for k in ids+jds]):continue + if any(l.crosses(LineString(c)) for k,(c,_) in enumerate(records) if k not in [i,j]):continue + records[i]=(q,ids+jds);records.pop(j);changed=True;break + if changed:break + # Intersect only measured adjacent planes, within a bounded endpoint gap. + for i,(a,ids) in enumerate(records): + for j in range(i+1,len(records)): + b,jds=records[j];u=a[-1]-a[0];v=b[-1]-b[0];u/=np.linalg.norm(u);v/=np.linalg.norm(v) + if abs(u@v)>np.cos(np.deg2rad(25)):continue + distances=np.linalg.norm(a[:,None,:]-b[None,:,:],axis=2);ia,ib=np.unravel_index(np.argmin(distances),distances.shape) + if distances[ia,ib]>.8:continue + coef=np.linalg.solve(np.c_[u,-v],b[ib]-a[ia]);p=a[ia]+coef[0]*u + if np.linalg.norm(p-a[ia])>.7 or np.linalg.norm(p-b[ib])>.7:continue + na=a.copy();nb=b.copy();na[ia]=p;nb[ib]=p + if LineString(na).length<1 or LineString(nb).length<1:continue + la,lb=LineString(na),LineString(nb) + if bridge_validator is not None and (not bridge_validator(la,[lines[k]for k in ids]) or not bridge_validator(lb,[lines[k]for k in jds])):continue + if any(la.crosses(LineString(c))or lb.crosses(LineString(c))for k,(c,_)in enumerate(records)if k not in [i,j]):continue + records[i]=(na,ids);records[j]=(nb,jds);a=na + return records diff --git a/simulation/urban-plan-research/continuation_pass/object_solver.py b/simulation/urban-plan-research/continuation_pass/object_solver.py new file mode 100644 index 00000000..04498e11 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/object_solver.py @@ -0,0 +1,149 @@ +"""Evidence-weighted whole-chain shortest path and joint candidate selection. + +The order of observations is an input hypothesis, NOT guaranteed topology. +v8 vectors, scene names and operator review coordinates are not inputs. +Uses existing line/arc assembly, SciPy HiGHS and GEOS; no trained model. +""" +from dataclasses import dataclass, asdict +import numpy as np +import cv2 +from scipy.optimize import milp, Bounds, LinearConstraint +from scipy.sparse import coo_matrix +from shapely.geometry import LineString +import shapely +from plan_shapes import assemble + +@dataclass(frozen=True) +class Policy: + station_m: float = .4 + node_spacing_m: float = 1.6 + maximum_primitive_m: float = 100. + residual_scale_m: float = .22 + line_complexity: float = 1.8 + arc_complexity: float = 3.2 + reliable_residual_limit_m: float = .65 + minimum_observed_m: float = 2. + milp_seconds: float = 30. + +def stations(p): + return np.r_[0.,np.cumsum(np.linalg.norm(np.diff(p,axis=0),axis=1))] + +def sample_chain(p, step=.4): + p=np.asarray(p,float);s=stations(p);keep=np.r_[True,np.diff(s)>1e-7];p,s=p[keep],s[keep] + if len(p)<2:return p + t=np.linspace(0,s[-1],max(2,int(np.ceil(s[-1]/step))+1)) + return np.c_[np.interp(t,s,p[:,0]),np.interp(t,s,p[:,1])] + +def fit_line(p,w): + total=w.sum() + if total<1e-8:return None + origin=(p*w[:,None]).sum(0)/total + q=p-origin;cov=(q*w[:,None]).T@q + _,v=np.linalg.eigh(cov);u=v[:,-1] + if u@(p[-1]-p[0])<0:u=-u + n=np.array([-u[1],u[0]]);res=q@n + ends=origin+((p[[0,-1]]-origin)@u)[:,None]*u + return dict(kind='line',origin=origin,axis=u,error=res,ends=ends,p=p[w>.25]) + +def fit_arc(p,w): + choose=w>.25 + if choose.sum()<8:return None + origin=(p*w[:,None]).sum(0)/w.sum();q=p-origin + sw=np.sqrt(w);a=np.c_[2*q,np.ones(len(q))] + c=np.linalg.lstsq(a*sw[:,None],(q*q).sum(1)*sw,rcond=None)[0] + center=c[:2]+origin;r=np.linalg.norm(p-center,axis=1);radius=np.sum(r*w)/w.sum() + if not 1.max(1,len(p)*.05):return None + v=p[[0,-1]]-center;v/=np.maximum(np.linalg.norm(v,axis=1)[:,None],1e-8) + return dict(kind='arc',center=center,radius=radius,error=r-radius,ends=center+radius*v,p=p[choose]) + +def fit_chain(points,weights,policy=Policy(), complexity_scale=1.): + p=np.asarray(points,float);w=np.clip(np.asarray(weights,float),0,1) + if len(p)!=len(w)or len(p)<3 or not np.isfinite(p).all():raise ValueError('Finite aligned evidence required') + supported=np.flatnonzero(w>.25) + if len(supported)<3:return None + a,b=int(supported[0]),int(supported[-1]);p,w=p[a:b+1],w[a:b+1];s=stations(p) + if w.sum()*policy.station_mpolicy.maximum_primitive_m:break + if not np.isfinite(costs[i]):continue + q=p[cuts[i]:cuts[j]+1];ww=w[cuts[i]:cuts[j]+1] + if len(q)<3:continue + line=fit_line(q,ww) + if line is None:continue + options=[line] + if len(q)>=8 and s[cuts[j]]-s[cuts[i]]<40 and np.max(abs(line['error'])*ww)>.1: + arc=fit_arc(q,ww) + if arc is not None:options.append(arc) + for m in options: + e=abs(m['error']);strong=ww>.65 + if strong.any() and np.quantile(e[strong],.95)>policy.reliable_residual_limit_m:continue + # Huber data term plus explicit primitive description length. + rr=e/policy.residual_scale_m;rho=np.where(rr<=1,rr**2,2*rr-1) + loss=float(np.sum(ww*rho)*policy.station_m)+(policy.line_complexity if m['kind']=='line' else policy.arc_complexity)*complexity_scale + edges+=1 + if costs[i]+loss.65 + # Assembly is rechecked; tangent fitting must not invalidate the chosen path. + if strong.any() and np.quantile(residual[strong],.95)>policy.reliable_residual_limit_m:return None + # Alternatives use different search penalties to propose geometry, but must + # be compared under one common objective after line/arc junction assembly. + rr=residual/policy.residual_scale_m + rho=np.where(rr<=1,rr**2,2*rr-1) + common_cost=float(np.sum(w*rho)*policy.station_m)+sum( + policy.line_complexity if m['kind']=='line' else policy.arc_complexity for m in chosen) + return dict(points=curve,primitives=primitives,cost=common_cost,search_cost=float(costs[-1]),trim=[a,b], + evidence_length_m=float(w.sum()*policy.station_m),p95_m=float(np.quantile(residual[strong],.95))if strong.any()else None, + graph_nodes=N,admissible_edges=edges,complexity_scale=complexity_scale) + +def select_candidates(groups,policy=Policy()): + """One alternative or explicit unresolved choice per evidence chain. + + Joint geometric exclusion is solved by HiGHS; cannot invent missing options. + """ + options=[];group_ids=[];c=[];geoms=[] + for i,g in enumerate(groups): + for candidate in g: + group_ids.append(i);options.append(candidate);geoms.append(LineString(candidate['points'])) + c.append(candidate['cost']) + group_ids.append(i);options.append(None);geoms.append(None) + c.append(max([x['cost']for x in g]+[1.])+max([x.get('evidence_length_m',1)for x in g]+[1.])*4+20) + if not options:return [],dict(conflicts=0,solver_status=0,unresolved=[]) + rows=[];cols=[];vals=[];lb=[];ub=[] + for i in range(len(groups)): + row=len(lb);lb.append(1.);ub.append(1.) + for j,gi in enumerate(group_ids): + if gi==i:rows.append(row);cols.append(j);vals.append(1.) + conflicts=[] + for i,a in enumerate(geoms): + if a is None:continue + for j in range(i): + b=geoms[j] + if b is None or group_ids[i]==group_ids[j]:continue + if a.crosses(b) or a.intersection(b).length>.5: + conflicts.append([i,j]);row=len(lb);lb.append(-np.inf);ub.append(1.) + rows.extend([row,row]);cols.extend([i,j]);vals.extend([1.,1.]) + A=coo_matrix((vals,(rows,cols)),shape=(len(lb),len(options))).tocsc() + fit=milp(np.asarray(c),integrality=np.ones(len(c)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options={'time_limit':policy.milp_seconds,'mip_rel_gap':.001}) + if fit.x is None:raise RuntimeError('No feasible whole-chain selection: '+fit.message) + indices=np.flatnonzero(fit.x>.5);selected=[(group_ids[j],options[j])for j in indices if options[j]is not None] + unresolved=[group_ids[j]for j in indices if options[j]is None] + return selected,dict(conflicts=len(conflicts),solver_status=int(fit.status),solver_message=fit.message,mip_gap=float(fit.mip_gap),unresolved=unresolved,objective=float(fit.fun)) diff --git a/simulation/urban-plan-research/continuation_pass/paint_dedup.py b/simulation/urban-plan-research/continuation_pass/paint_dedup.py new file mode 100644 index 00000000..50794664 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/paint_dedup.py @@ -0,0 +1,15 @@ +"""Object NMS after fitting; overlapping tile fragments may fit the same glyph.""" +from shapely.geometry import shape + +def deduplicate_glyphs(features): + symbols=[f for f in features if f['properties'].get('method')=='symbol-template'] + others=[f for f in features if f['properties'].get('method')!='symbol-template'] + kept=[];audit=[] + for f in sorted(symbols,key=lambda f:(-f['properties'].get('template_fit_score',0),f['id'])): + footprint=shape(f['geometry']).convex_hull;duplicate=None + for prior,g in kept: + if footprint.intersection(g).area/max(footprint.union(g).area,1e-9)>.6: + duplicate=prior;break + if duplicate is None:kept.append((f,footprint)) + else:audit.append(dict(rejected_id=f['id'],kept_id=duplicate['id'],reason='overlapping-fitted-symbol')) + return others+[f for f,_ in kept],audit diff --git a/simulation/urban-plan-research/continuation_pass/paint_families.py b/simulation/urban-plan-research/continuation_pass/paint_families.py new file mode 100644 index 00000000..9019a1e3 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/paint_families.py @@ -0,0 +1,63 @@ +"""Fit collinear paint as line/dash families, keeping the observed extent. + +OpenCV robust line fits and median period/width estimates; no site constants. +Only bounded internal slots may be reconstructed, never a new exterior lane. +""" +import numpy as np,cv2,shapely +from shapely.geometry import shape,Polygon,LineString +from layer_common import feature + +def normalize(features,lift,admit): + records=[];untouched=[] + for f in features: + g=shapely.force_2d(shape(f['geometry'])) + if f['properties'].get('subtype')!='linear_marking' or g.geom_type!='Polygon':untouched.append(f);continue + rect=cv2.minAreaRect(np.asarray(g.exterior.coords,np.float32));box=cv2.boxPoints(rect);edges=np.roll(box,-1,axis=0)-box;k=np.argmax(np.linalg.norm(edges,axis=1));L=np.linalg.norm(edges[k]);W=min(rect[1]);u=edges[k]/L + if not(1.27 and g.area/(L*W)>.68):untouched.append(f);continue + records.append(dict(f=f,g=g,center=np.array(rect[0]),axis=u,L=L,W=W)) + parent=list(range(len(records))) + def root(i): + while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i] + return i + for i,a in enumerate(records): + u=a['axis'];n=np.array([-u[1],u[0]]) + for j,b in enumerate(records[:i]): + delta=b['center']-a['center'] + if abs(u@b['axis']).18:continue + gap=abs(delta@u)-(a['L']+b['L'])/2 + if gap>12 or abs(delta@u)>55:continue + parent[root(i)]=root(j) + groups={} + for i in range(len(records)):groups.setdefault(root(i),[]).append(i) + output=list(untouched);audit=[] + for ids in groups.values(): + originals=[records[i]['f']for i in ids] + if len(ids)<2:output.extend(originals);continue + samples=np.concatenate([records[i]['center']+np.linspace(-records[i]['L']/2,records[i]['L']/2,max(3,int(records[i]['L']/.5)))[:,None]*records[i]['axis']for i in ids]) + fit=cv2.fitLine(samples.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=fit[:2];o=fit[2:];n=np.array([-u[1],u[0]]) + if np.max(abs((samples-o)@n))>.24:output.extend(originals);continue + ranges=sorted([((records[i]['center']-o)@u-records[i]['L']/2,(records[i]['center']-o)@u+records[i]['L']/2)for i in ids]);merged=[] + for a,b in ranges: + if merged and a<=merged[-1][1]+.15:merged[-1][1]=max(b,merged[-1][1]) + else:merged.append([a,b]) + widths=[records[i]['W']for i in ids];width=float(np.median(widths));lengths=np.array([b-a for a,b in merged]);centers=np.array([(a+b)/2 for a,b in merged]);gaps=np.array([b[0]-a[1]for a,b in zip(merged[:-1],merged[1:])]) + intervals=None;mode=None;added=0 + if len(merged)==1:intervals=merged;mode='continuous-paint-family' + elif np.max(gaps)<.85 or(np.median(lengths)>4 and np.max(gaps)<2.5): + intervals=[[merged[0][0],merged[-1][1]]];mode='continuous-paint-family';added=float(np.sum(gaps)) + elif len(merged)>=3 and np.std(lengths)/np.mean(lengths)<.4: + deltas=np.diff(centers);period=float(np.median(deltas[deltas<=np.quantile(deltas,.65)]));L=float(np.median(lengths)) + if period>L*1.3 and period<15: + slots=np.rint((centers-centers[0])/period).astype(int);phase=float(np.median(centers-slots*period)) + residual=np.max(abs(centers-(phase+slots*period))) + if residual<.35 and np.max(np.diff(slots))<=2: + targets=np.arange(slots[0],slots[-1]+1);intervals=[[phase+t*period-L/2,phase+t*period+L/2]for t in targets];mode='periodic-dash-family';added=int(len(targets)-len(slots)) + if intervals is None:output.extend(originals);continue + polygons=[] + for a,b in intervals: + xy=o+np.array([[a,-width/2],[b,-width/2],[b,width/2],[a,width/2],[a,-width/2]])@np.stack([u,n]);polygons.append(Polygon(xy)) + if not all(admit(p)for p in polygons):output.extend(originals);continue + ids_source=[r['id']for r in originals] + for p in polygons:output.append(feature(lift(p),'road_marking',subtype='linear_marking',method=mode,source_ids=ids_source,inferred_internal_completion=bool(added),template_width_m=width)) + audit.append(dict(method=mode,input_objects=len(ids),output_objects=len(polygons),width_m=width,added_internal_m_or_slots=added,source_ids=ids_source)) + return output,audit diff --git a/simulation/urban-plan-research/continuation_pass/paint_templates.py b/simulation/urban-plan-research/continuation_pass/paint_templates.py new file mode 100644 index 00000000..e279378d --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/paint_templates.py @@ -0,0 +1,85 @@ +"""Template hypotheses in metric object coordinates; never site coordinates.""" +import numpy as np,cv2,shapely +from shapely.geometry import Polygon,LineString +from shapely.ops import unary_union +from shapely.affinity import rotate,translate +from scipy.optimize import minimize +from road_glyph_presets import arrow + +def template(kind,L,W,stroke): + if kind!='letter_A':return arrow(kind,L,W,stroke) + # A is an original parametric preset. Arrows use the attributed SVG library. + outer=LineString([(0,-W/2),(L,0),(0,W/2)]).buffer(stroke/2,cap_style=2,join_style=3) + bar=LineString([(L*.3,-W*.35),(L*.3,W*.35)]).buffer(stroke/2,cap_style=2) + return unary_union([outer,bar]) + +def fit_symbol(p,heading=None,diagnostics=None): + if p.geom_type!='Polygon' or p.area<.25:return None + points=np.array(p.exterior.coords)[:,:2];rect=cv2.minAreaRect(points.astype('float32'));corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));u=edges[k]/np.linalg.norm(edges[k]);L=np.linalg.norm(edges[k]);W=min(rect[1]);origin=np.array(rect[0]);ang=np.arctan2(u[1],u[0]);fill=p.area/(L*W) + if not (1.21.2 and .09350:return None + target=np.zeros(shape,np.uint8) + def draw(poly): + out=np.zeros(shape,np.uint8) + for part in ([poly] if poly.geom_type=='Polygon' else getattr(poly,'geoms',[])): + if part.geom_type!='Polygon' or part.is_empty:continue + cv2.fillPoly(out,[np.rint((np.array(part.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1) + for hole in part.interiors:cv2.fillPoly(out,[np.rint((np.array(hole.coords)[:,:2]-lo)/cell).astype('int32')],0) + return out + target=draw(p);expanded=cv2.dilate(target,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))) + # The counter supplies a strong object identity cue, independent of a noisy + # semantic mask. A bounded 8 cm closing tolerates small wear breaks. + closed=p.buffer(.08).buffer(-.08) + counters=[Polygon(h)for part in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if part.geom_type=='Polygon'for h in part.interiors] + has_counter=any(h.area>.05*L*W for h in counters) + variants=['letter_A']if has_counter else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow'];best=None + if heading is not None:ang=float(np.arctan2(heading[1],heading[0])) + for kind in variants: + for flip in [0,np.pi]: + a=ang+flip;uu=np.array([np.cos(a),np.sin(a)]);base=origin-uu*L/2 + x0=np.array([base[0],base[1],a,L,W,.16]);bounds=[(base[0]-.4,base[0]+.4),(base[1]-.4,base[1]+.4),(a-.16,a+.16),(L*.85,L*1.15),(W*.75,W*1.25),(.08,.32)] + def polygon(x): + m=template(kind,x[3],x[4],x[5]);m=rotate(m,x[2],origin=(0,0),use_radians=True);return translate(m,x[0],x[1]) + def loss(x): + m=draw(polygon(x));wide=cv2.dilate(m,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))) + coverage=(m&expanded).sum()/max(m.sum(),1);recall=(wide&target).sum()/max(target.sum(),1) + overlap=(m&target).sum()/max((m|target).sum(),1) + return 1-(.6*2*coverage*recall/max(coverage+recall,1e-6)+.4*overlap)+.03*abs(x[3]/L-1) + score=loss(x0) + if kind!='letter_A' and (W<.60 or W/x0[5]<3.5):continue + # A worn letter may have an open counter; missing topology is not a veto. + if score>.8:continue + fit=minimize(loss,x0,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.004,ftol=.004));m=polygon(fit.x);r=draw(m) + coverage=float((r&expanded).sum()/max(r.sum(),1));recall=float((cv2.dilate(r,np.ones((5,5),np.uint8))&target).sum()/max(target.sum(),1));f1=2*coverage*recall/max(coverage+recall,1e-6);overlap=float((r&target).sum()/max((r|target).sum(),1));score=.6*f1+.4*overlap + if diagnostics is not None:diagnostics.append(dict(kind=kind,coverage=coverage,recall=recall,score=score,overlap=overlap,counter=has_counter,parameters=fit.x.tolist())) + if kind=='letter_A': + x=fit.x;bar=LineString([(x[3]*.3,-x[4]*.30),(x[3]*.3,x[4]*.30)]).buffer(x[5]/2,cap_style=2) + bar=translate(rotate(bar,x[2],origin=(0,0),use_radians=True),x[0],x[1]);support=draw(bar) + if (support&expanded).sum()/max(support.sum(),1)<.6:continue + # Positive shape overlap alone confuses arrow heads and triangular signs + # with A. Its counter is negative evidence and must stay largely unpainted. + holes=unary_union([Polygon(h)for part in ([m]if m.geom_type=='Polygon'else m.geoms)if part.geom_type=='Polygon'for h in part.interiors]) + core=holes.buffer(-.08) + mask=draw(core) + if mask.sum()<8 or (mask&expanded).sum()/mask.sum()>.15:continue + elif kind.startswith('straight_') and kind!='straight_arrow': + # A compound arrow needs its lateral branch, even if a straight arrow + # alone matches most of the template area. + x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]]) + yy,xx=np.mgrid[:r.shape[0],:r.shape[1]];xy=np.stack([lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]],axis=-1);side=xy@n + # Artwork is bbox-centered; use the outer quarter on the branch side. + sign=1 if 'left'in kind else -1 + branch=(r>0)&(side*sign>x[4]*.24) + if branch.sum()<5 or (branch&expanded).sum()/branch.sum()<.8:continue + longitudinal=xy@u;head=(r>0)&(longitudinal>x[3]*.8) + if head.sum()<5 or (head&expanded).sum()/head.sum()<.85:continue + elif kind in ['left_arrow','right_arrow']: + x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]]) + yy,xx=np.nonzero(target);xy=np.c_[lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]];longitudinal=xy@u;side=xy@n + front=side[longitudinal>x[3]*.72];tail=side[longitudinal=.72 and recall>=.86 and (best is None or score>best[1]):best=(m,score,kind,recall,fit.x.tolist()) + if best and best[1]>=.80:return best + return None diff --git a/simulation/urban-plan-research/continuation_pass/reanchor.py b/simulation/urban-plan-research/continuation_pass/reanchor.py new file mode 100644 index 00000000..5672ac95 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/reanchor.py @@ -0,0 +1,83 @@ +"""Re-use normal-strip DP and minimum-curvature fitting around joined seams. + +The visible sidewalk interface supplies broad context; physical Gaussian edges +locate the anchors. Occluded samples have zero observation weight. The remainder +of each accepted chain and its original scan terminals remain fixed. +""" +import numpy as np +from shapely.geometry import LineString,Point +from scipy.ndimage import gaussian_filter1d +from dataclasses import replace +from boundary_anchors import sample,smooth_anchors,AnchorPolicy +from object_solver import sample_chain,stations +from continuations import regularize + +def snap(record,f): + if not record.get('spans'):return record,dict(changed=False) + side=f.side.astype('float32',copy=False);road=f.road_mask.astype('float32',copy=False) + original=np.asarray(record['points']);line=LineString(original[:,:2]);p=sample_chain(original[:,:2],.4);st=stations(p) + active=np.zeros(len(p),bool);centers=[] + for span in record['spans']: + a,b=sorted(line.project(Point(np.asarray(q)[:2]))for q in [span[0],span[-1]]) + centers.append((a+b)/2) + active|=(st>max(0,a-10))&(st.5 + reward=(physical+1.25*np.maximum(contrast,0))*valid + cost=-reward+.10*offsets[None,:]**2 + center=len(offsets)//2;cost[~active]=1e5;cost[~active,center]=0 + transition=.5*((offsets[:,None]-offsets[None,:])/.4)**2 + previous=cost[0];back=np.zeros(cost.shape,np.int16) + for i in range(1,len(p)): + total=previous[:,None]+transition;back[i]=np.argmin(total,axis=0);previous=cost[i]+total.min(0) + ix=np.zeros(len(p),int);ix[-1]=np.argmin(previous) + for i in range(len(p)-1,0,-1):ix[i-1]=back[i,ix[i]] + rows=np.arange(len(p));chosen=xy[rows,ix];supported=(physical[rows,ix]>.45)&(contrast[rows,ix]>.5)&(valid[rows,ix]>.5) + confidence=supported.astype(float);confidence[~active]=100.;chosen[~active]=p[~active] + if np.count_nonzero(supported&active)<5:return record,dict(changed=False,reason='insufficient-new-anchors') + q=smooth_anchors(chosen,confidence,replace(AnchorPolicy(),sample_m=.4,smooth_lambda_m4=.8)) + q[~active]=p[~active];q[[0,-1]]=original[[0,-1],:2] + if not LineString(q).is_simple or np.max(np.linalg.norm(q-p,axis=1))>3.1:return record,dict(changed=False,reason='geometry-guard') + # The new path must actually increase physical/context agreement. + nn=n*np.array([1,-1]);score0,valid0=f.fields.measure(pix(p),nn);score1,valid1=f.fields.measure(pix(q),nn) + contrast0=sample(side,pix(p+n*.7))-sample(side,pix(p-n*.7)) + contrast1=sample(side,pix(q+n*.7))-sample(side,pix(q-n*.7)) + valid0*=sample(road,pix(p-n*.8))>.5;valid1*=sample(road,pix(q-n*.8))>.5 + before=float(np.mean((score0+1.25*np.maximum(contrast0,0))[active]*valid0[active]));after=float(np.mean((score1+1.25*np.maximum(contrast1,0))[active]*valid1[active])) + # Each join is judged independently, including overlapping neighbourhoods. + # Under occlusion, better image agreement cannot justify a new geometric + # wiggle: the data do not establish the extra turning of a curb. + occluded_station=np.max(sample(f.fields.occluder,uv),axis=1)>.25 + e0=(score0+1.25*np.maximum(contrast0,0))*valid0;e1=(score1+1.25*np.maximum(contrast1,0))*valid1 + groups=np.argmin(abs(st[:,None]-np.asarray(centers)[None,:]),axis=1);decisions=[] + def turning(x): + t=np.diff(gaussian_filter1d(x,1.,axis=0,mode='nearest'),axis=0) + angle=np.unwrap(np.arctan2(t[:,1],t[:,0]));return float(np.sum(abs(np.diff(angle)))) + for group in range(len(centers)): + window=(groups==group)&active + if not window.any():continue + b=float(np.mean(e0[window]));a=float(np.mean(e1[window]));old_turn=turning(p[window]);new_turn=turning(q[window]);occluded=float(np.mean(occluded_station[window])) + complexity_veto=occluded>.15 and new_turn>old_turn+.25 + accept=np.count_nonzero(supported&window)>=5 and a>b+.1 and not complexity_veto + decisions.append(dict(station_range_m=[float(st[window][0]),float(st[window][-1])],accepted=bool(accept),before=b,after=a,old_turn_radians=old_turn,new_turn_radians=new_turn,occluded_fraction=occluded,complexity_veto=bool(complexity_veto))) + if not accept:q[window]=p[window] + else: + # Adjacent accepted/rejected windows must join continuously. Fade + # only inside the accepted window; rejected geometry stays fixed. + sw=st[window];weight=np.clip(np.minimum(sw-sw[0],sw[-1]-sw)/3.,0,1) + weight=weight*weight*(3-2*weight) + q[window]=p[window]+weight[:,None]*(q[window]-p[window]) + if not any(x['accepted']for x in decisions):return record,dict(changed=False,reason='no-admissible-local-correction',before=before,after=after,windows=decisions) + if not LineString(q).is_simple:return record,dict(changed=False,reason='local-admission-geometry-guard',windows=decisions) + if original.shape[1]>2:q=np.c_[q,np.interp(st,stations(original[:,:2]),original[:,2])] + q,_=regularize(q) + return {**record,'points':q},dict(changed=True,before=before,after=after,maximum_change_m=float(np.max(np.linalg.norm(xy[rows,ix]-p,axis=1))),observed_new_anchor_samples=int(np.count_nonzero(supported&active)),windows=decisions) diff --git a/simulation/urban-plan-research/continuation_pass/recover_interfaces.py b/simulation/urban-plan-research/continuation_pass/recover_interfaces.py new file mode 100644 index 00000000..8ce19a5c --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/recover_interfaces.py @@ -0,0 +1,63 @@ +"""Recover missing street-side interfaces of measured sidewalk regions. + +One-sided Gaussian support is valid when the road side is degraded. Building, +terrain and survey frontiers remain vetoes. Existing boundaries are protected. +""" +import numpy as np,cv2,shapely,hashlib +from shapely.geometry import shape,LineString +from scipy.ndimage import gaussian_filter1d,binary_closing,binary_opening +from object_solver import sample_chain,fit_chain,Policy +from dataclasses import replace +from continuations import regularize +from boundary_anchors import sample + +def recover(f,old,roads): + road_geom=shapely.union_all([LineString(r['points'][:,:2])for r in roads]) + facade_geom=shapely.union_all([shapely.force_2d(shape(x['geometry']))for x in old['features']if x['properties']['class']=='building_facade']) + known_walk=shapely.union_all([shapely.force_2d(shape(x['geometry']))for x in old['features']if x['properties']['class']=='pedestrian_boundary']) + result=[];audit=[] + def pix(p):return np.c_[(p[:,0]-f.low[0])/f.cell-.5,(f.high[1]-p[:,1])/f.cell-.5] + def at(field,p):return sample(field,pix(p)) + contours,_=cv2.findContours(f.side.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) + for c in contours: + p=c[:,0];xy=np.c_[f.low[0]+(p[:,0]+.5)*f.cell,f.high[1]-(p[:,1]+.5)*f.cell] + if len(xy)<30:continue + q=sample_chain(np.vstack([xy,xy[0]]),.4)[:-1] + smooth=gaussian_filter1d(q,1.5,axis=0,mode='wrap');t=np.roll(smooth,-1,axis=0)-np.roll(smooth,1,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8);n=np.c_[-t[:,1],t[:,0]] + n*=np.sign(np.mean(at(f.walk,q+n*.8)-at(f.walk,q-n*.8)))or 1 + inside=q+n*.7;outside=q-n*.9 + own=at(f.walk,inside);other=at(f.walk,outside);road=at(f.road,outside) + structures=at(f.structure,outside);terrain=at(f.terrain,outside) + wall=(structures>.32)|((at(f.fields.z,outside)-at(f.fields.z,inside)>.7)&(at(f.alpha,outside)>.7)&(at(f.vehicle,outside)<.25)) + facade=shapely.distance(shapely.points(q),facade_geom)<1.2 + veto=wall|facade|(terrain>.4)|(at(f.alpha,q)<.3) + support=(own>.35)&(other<.4)&(at(f.alpha,inside)>.7)&~veto + # Only internal drops are filled, without crossing a positive wall/terrain. + flags=binary_closing(np.tile(support,3),structure=np.ones(13))[len(q):2*len(q)]&~veto + # Exclude already reconstructed geometry, including garden interfaces. + covered=(shapely.distance(shapely.points(q),road_geom)<.8)|(shapely.distance(shapely.points(q),known_walk)<.8) + flags&=~covered + flags=binary_opening(np.tile(flags,3),structure=np.ones(4))[len(q):2*len(q)] + if flags.all()or not flags.any():continue + k=int(np.flatnonzero(~flags)[0]);order=np.roll(np.arange(len(q)),-k);ff=flags[order];cuts=np.r_[0,np.flatnonzero(np.diff(ff.astype(int)))+1,len(q)] + for a,b in zip(cuts[:-1],cuts[1:]): + if not ff[a]or(b-a)*.4<8:continue + ix=order[a:b];p=q[ix];ro=float(np.mean(road[ix]));near=float(LineString(p).distance(road_geom)) + # Street evidence may be sparse, but must exist along this interface + # or meet a previously identified street edge at both ends. + end_near=[shapely.Point(e).distance(road_geom)for e in p[[0,-1]]] + if ro<.08 and not(max(end_near)<8 and near<3):continue + # A recovered observation has not passed the v8 shape stage. Fit a + # compact primitive chain; never emit a failed raw raster contour. + fit=fit_chain(p,np.ones(len(p)),replace(Policy(),residual_scale_m=.32,reliable_residual_limit_m=.55),complexity_scale=3.) + if fit is None or len(fit['primitives'])>max(2,LineString(p).length/6):continue + new=np.c_[fit['points'],at(f.fields.z,fit['points'])] + if not LineString(new[:,:2]).is_simple:continue + # Never add a duplicate parallel trace over the known road edge. + novel=LineString(new[:,:2]).difference(road_geom.buffer(1.0)).length + if novel.25).astype('uint8'),bounds=np.array([f.low,f.high]),cell=f.cell) +def pix(p): + p=np.asarray(p);return np.c_[(p[:,0]-f.low[0])/f.cell-.5,(f.high[1]-p[:,1])/f.cell-.5] +def at(field,p):return sample(field,pix(p)) +domain=binary_fill_holes((f.alpha>.3)|((f.walk+f.road)>.5)).astype('float32') +def sides(p): + p=sample_chain(np.asarray(p)[:,:2],.4);t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8);n=np.c_[-t[:,1],t[:,0]] + return p,n,at(f.walk,p+n)-at(f.walk,p-n)+at(f.road,p-n)-at(f.road,p+n) +def evaluate(curve,left,right): + p,n,contrast=sides(curve) + if np.mean(at(domain,p)>.5)<.95:return dict(allowed=False,reason='outside-survey-domain') + crossing=observed_crossing_length(curve,lambda q:at(f.transport,q),lambda q:at(f.alpha,q),lambda q:at(f.vehicle,q)) + if crossing>=.6:return dict(allowed=False,reason='visible-transport-corridor',visible_crossing_m=crossing) + a,_,sa=sides(left[-min(len(left),30):]);b,_,sb=sides(right[:min(len(right),30)]) + aa=float(np.mean(sa));bb=float(np.mean(sb));orientation=np.sign(aa+bb) + if aa*bb<0 and min(abs(aa),abs(bb))>.25:return dict(allowed=False,reason='opposite-surface-sides') + if not orientation:return dict(allowed=False,reason='unestablished-adjacency') + nr=n*orientation;inside=at(f.walk,p+nr);outside=at(f.walk,p-nr) + bothroad=(at(f.road,p+n)>.65)&(at(f.road,p-n)>.65) + if np.count_nonzero(bothroad[2:-2])*.4>max(.8,LineString(p).length*.25):return dict(allowed=False,reason='road-crossing-cap') + if np.mean((inside>.55)&(outside>.55))>.6:return dict(allowed=False,reason='cuts-pedestrian-interior') + uv=pix(p);normal=np.c_[nr[:,0],-nr[:,1]] + score,valid=f.fields.measure(uv,normal) + occ=at(f.vehicle,p) + context=float(np.mean(inside-outside)) + if context<-.2:return dict(allowed=False,reason='wrong-surface-side') + evidence=float(np.mean(score*valid));reward=evidence+.4*max(0,context) + return dict(allowed=True,reward=reward,physical_score=evidence,pedestrian_contrast=context,occluded_fraction=float(np.mean(occ>.25)),visible_crossing_m=crossing,inferred=True) + +base_bytes=(B/'whole-map.json').read_bytes();base=json.loads(base_bytes) +fs=[x for x in base['features']if x['properties']['class']=='road_boundary'] +raw=[dict(id=x['id'],points=np.asarray(x['geometry']['coordinates']),reasons=[x['properties'].get('start_reason'),x['properties'].get('end_reason')],**{'class':'road_boundary'})for x in fs] +fitted=[];shape_audit=[] +for r in raw: + q,rec=regularize(r['points'],policy);fitted.append({**r,'points':q});shape_audit.append(dict(id=r['id'],changed=rec is not None,fit=rec)) +# Retain both complete parents if regularization introduces a crossing. +for i,a in enumerate(fitted): + for j,b in enumerate(fitted[:i]): + if LineString(a['points'][:,:2]).crosses(LineString(b['points'][:,:2])): + a['points']=raw[i]['points'];b['points']=raw[j]['points'];shape_audit[i]['reverted']='crossing';shape_audit[j]['reverted']='crossing' +variants={'regularized':(fitted,{})} +variants['connected']=connect(raw,evaluate,policy) +variants['combined']=connect(fitted,evaluate,policy) +# Fit only after connectivity has been chosen, so smoothing does not move the +# candidate attachment stations before the endpoint graph is evaluated. +post=[] +for r in variants['connected'][0]: + q,fit=regularize(r['points'],policy);post.append({**r,'points':q}) +# A individually simple fit can still collide with another complete chain. +for i,a in enumerate(post): + for j,b in enumerate(post[:i]): + if LineString(a['points'][:,:2]).crosses(LineString(b['points'][:,:2])): + a['points']=variants['connected'][0][i]['points'];b['points']=variants['connected'][0][j]['points'] +variants['connected_then_fit']=(post,variants['connected'][1]) +from reanchor import snap +snapped=[];snap_audit=[] +for r in post: + new,audit=snap(r,f);snapped.append(new);snap_audit.append(dict(source_ids=r.get('source_ids',[r['id']]),**audit)) +# Roll back the neighborhood of a conflicting move, not an entire long street. +# This guard is geometric and identical at every scene/chain position. +from object_solver import stations +snapped=[{**r,'points':r['points'].copy()}for r in snapped] +for attempt in range(3): + collisions=[] + for i,a in enumerate(snapped): + for j,b in enumerate(snapped[:i]): + ga=LineString(a['points'][:,:2]);gb=LineString(b['points'][:,:2]) + if ga.crosses(gb):collisions.append((i,j,shapely.get_coordinates(ga.intersection(gb)))) + if not collisions:break + for i,j,xy in collisions: + for k in [i,j]: + if not snap_audit[k]['changed']:continue + parent_points=post[k]['points'];g=LineString(parent_points[:,:2]);p=sample_chain(snapped[k]['points'][:,:2],.25) + st=shapely.line_locate_point(g,shapely.points(p));targets=shapely.line_locate_point(g,shapely.points(xy));delta=np.min(abs(st[:,None]-targets[None,:]),axis=1) + weight=np.clip((delta-4*(attempt+1))/4,0,1);oldst=stations(parent_points[:,:2]);fallback=np.stack([np.interp(st,oldst,parent_points[:,d])for d in range(parent_points.shape[1])],axis=1) + fallback[:,:2]=weight[:,None]*p+(1-weight[:,None])*fallback[:,:2] + snapped[k]['points']=fallback;snap_audit[k]['local_conflict_rollbacks']=snap_audit[k].get('local_conflict_rollbacks',0)+1 +for i,a in enumerate(snapped): + for j,b in enumerate(snapped[:i]): + if LineString(a['points'][:,:2]).crosses(LineString(b['points'][:,:2]))or not LineString(a['points'][:,:2]).is_simple: + a['points']=post[i]['points'];b['points']=post[j]['points'];snap_audit[i]['reverted']='unresolved-crossing';snap_audit[j]['reverted']='unresolved-crossing' +variants['reanchored']=(snapped,variants['connected'][1]);post=snapped +(O/'reanchor-audit.json').write_text(json.dumps(snap_audit,allow_nan=False)) +from recover_interfaces import recover +old_full=json.loads(Path('/fullplan/full-map.json').read_text()) +extra,recovery_audit=recover(f,old_full,post) +joined_extra,extra_audit=connect(extra,evaluate,replace(policy,max_heading_degrees=25.,maximum_terminal_revision_m=2.)) +protected=shapely.union_all([LineString(r['points'][:,:2])for r in post]) +joined_extra=[r for r in joined_extra if not LineString(r['points'][:,:2]).crosses(protected)] +for r in joined_extra:r['inferred_class']=True +variants['recovered']=(post+joined_extra,extra_audit) +(O/'recovery-audit.json').write_text(json.dumps(recovery_audit,allow_nan=False)) +for name,(records,audit)in variants.items(): + features=[] + for r in records: + identity='refined-'+hashlib.sha256(r['points'].round(4).tobytes()).hexdigest()[:14] + props=dict(**{'class':r['class']},method='v8-seeds-common-primitive-and-endpoint-graph',source_ids=r.get('source_ids',[r['id']]),inferred_spans=[dict(status='inferred',coordinates=s,method='evidence-validated-endpoint-graph')for s in r.get('spans',[])],route_permission='unassigned',review_status='unreviewed',height_status='inherited-not-qualified') + # Report actual final geometry, after the bounded primitive fit, for inferred + # intervals. The raw candidate curves remain in the separate selection audit. + line=LineString(r['points'][:,:2]);st=np.r_[0,np.cumsum(np.linalg.norm(np.diff(r['points'][:,:2],axis=0),axis=1))] + for span in props['inferred_spans']: + a,b=sorted(line.project(Point(np.asarray(s)[:2]))for s in [span['coordinates'][0],span['coordinates'][-1]]) + stations=np.r_[a,st[(st>a)&(stweights[sl];mosaic[sl][take]=im[take];weights[sl][take]=score[take] + base=Image.fromarray(mosaic) +whole=draw_plan(base,world,D['features']);whole.save(O/'whole-overlay.jpg',quality=96) +plan=draw_plan(Image.new('RGB',base.size,'#f5f5f2'),world,D['features']);title(plan,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · инженерные слои').save(O/'whole-plan.jpg',quality=96) +preview=whole.copy();preview.thumbnail((2300,1500));title(preview,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · четыре слоя поверх гауссов').save(O/'overview.jpg',quality=96) +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];scores=[];records=[] +for tile in tiles: + name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);features=[f for f in D['features']if shape(f['geometry']).intersects(domain)];counts={c:sum(f['properties']['class']==c for f in features)for c in ['building_facade','road_marking','pedestrian_area','road_boundary']} + image=Image.open(S/name/'top.png').convert('RGB');overlay=draw_plan(image,lambda p:project(p,g),features) + overlay.save(O/(name+'.overlay.jpg'),quality=95);image.save(O/(name+'.source.jpg'),quality=95) + score=sum(v>0 for v in counts.values())*100+min(counts['building_facade'],10)*3+min(counts['road_marking'],20) + scores.append((score,name));records.append(dict(tile=name,counts=counts)) +chosen=[] +for score,name in sorted(scores,reverse=True): + if any(abs(int(name.split('-')[1])-int(n.split('-')[1]))<2 for n in chosen):continue + chosen.append(name) + if len(chosen)==3:break +sheet=Image.new('RGB',(1800,950*len(chosen)),'white');draw=ImageDraw.Draw(sheet) +for row,name in enumerate(chosen): + for col,suffix in enumerate(['source','overlay']): + im=Image.open(O/(name+'.'+suffix+'.jpg')).resize((900,900),Image.Resampling.LANCZOS);sheet.paste(im,(900*col,950*row+50));draw.text((900*col+12,950*row+12),name+' · '+('Гауссы'if col==0 else'Все слои'),font=font,fill='#263640') +sheet.save(O/'details.jpg',quality=96) +(O/'visual-manifest.json').write_text(json.dumps(dict(review_only_selection='automatic class diversity with spatial separation',selected=chosen,all_tiles=records,manual_processing_rois=[]),indent=2));print('PICTURES',chosen,flush=True) +# Whole-scene before/after comparison and an exhaustive glyph evidence sheet. +old=json.loads(Path('/fullplan/full-map.json').read_text()) +before=draw_plan(base,world,old['features']);before.thumbnail((2300,1500)) +after=whole.copy();after.thumbnail((2300,1500)) +rows=[title(before,os.environ['SCENE']+' · предыдущая сборка'),title(after,os.environ['SCENE']+' · уточнение')] +comparison=Image.new('RGB',(max(x.width for x in rows),sum(x.height for x in rows)+12),'white');y=0 +for row in rows:comparison.paste(row,(0,y));y+=row.height+12 +comparison.save(O/'comparison-full.jpg',quality=95) +glyphs=[f for f in D['features']if f['properties'].get('subtype')not in [None,'linear_marking','crosswalk']] +if glyphs: + sheet=Image.new('RGB',(1600,270*int(np.ceil(len(glyphs)/4))),'white');d=ImageDraw.Draw(sheet) + for k,item in enumerate(glyphs): + prop=item['properties'];name=prop.get('source_tile') + if not name:continue + g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + xy=shapely.get_coordinates(shape(item['geometry']));uv=project(xy,g)*factor;lo=uv.min(0)-25;hi=uv.max(0)+25;center=(lo+hi)/2;extent=max(hi-lo);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int)) + overlay=draw_plan(raw,lambda p:project(p,g)*factor,[item],width=3) + for j,im in enumerate([raw,overlay]):sheet.paste(im.crop(bbox).resize((195,195),Image.Resampling.LANCZOS),((k%4)*400+j*200,(k//4)*270+65)) + d.text(((k%4)*400+5,(k//4)*270+8),str(k+1)+' '+prop['subtype'],font=font,fill='#263640');d.text(((k%4)*400+5,(k//4)*270+34),name,font=font,fill='#263640') + sheet.save(O/'glyph-proof.jpg',quality=96) +# Inspect every admitted road interpolation, not a hand-picked success crop. +spans=[(f,s)for f in D['features']if f['properties']['class']=='road_boundary'for s in f['properties'].get('inferred_spans',[])] +if spans: + sheet=Image.new('RGB',(1800,645*len(spans)),'white');d=ImageDraw.Draw(sheet) + for k,(owner,span)in enumerate(spans): + coords=np.array(span['coordinates']);center=coords[:,:2].mean(0) + tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz')) + raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + uv=project(coords,g)*factor;middle=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*8/60;extent=max(extent,raw.width*18/60) + bbox=tuple(np.r_[middle-extent/2,middle+extent/2].astype(int)) + for col,(fs,label)in enumerate([(None,'Гауссы'),(old['features'],'До'),(D['features'],'После')]): + im=raw if fs is None else draw_plan(raw,lambda p:project(p,g)*factor,fs,width=max(2,int(factor*2))) + patch=im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS);sheet.paste(patch,(col*600,k*645+45));d.text((col*600+10,k*645+10),str(k+1)+' · '+label,font=font,fill='#263640') + sheet.save(O/'bridge-proof.jpg',quality=95) + for k in range(len(spans)):sheet.crop((0,k*645,1800,(k+1)*645)).save(O/('bridge-%02d.jpg'%(k+1)),quality=96) diff --git a/simulation/urban-plan-research/continuation_pass/render_scene.py b/simulation/urban-plan-research/continuation_pass/render_scene.py new file mode 100644 index 00000000..3ecc98ec --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/render_scene.py @@ -0,0 +1,58 @@ +"""Unaltered Gaussian evidence with computed vector overlays, full-scene review.""" +from pathlib import Path +import os,json,numpy as np +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape,box +from fit_scene import project +B=Path('/base');O=Path('/out');S=Path('/survey') +v=json.loads((B/'viewer-data.json').read_text());low,high=np.asarray(v['bounds_xy']);res=v['resolution_m'] +current=json.loads((O/'whole-map.json').read_text())['features'];old=json.loads(Path('/fullplan/full-map.json').read_text())['features'];old=[f for f in old if f['properties']['class']=='road_boundary'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +font=ImageFont.truetype('/candidate/review-font.ttf',22);small=ImageFont.truetype('/candidate/review-font.ttf',17) +def overlay(im,features,convert,width=3): + out=im.convert('RGB').copy();d=ImageDraw.Draw(out) + for f in features: + pts=convert(np.asarray(f['geometry']['coordinates']));color='#ed821e'if f['properties']['class']=='road_boundary'else'#009b80' + d.line([tuple(p)for p in pts],fill=color,width=width,joint='curve') + return out +def title(im,txt): + out=Image.new('RGB',(im.width,im.height+64),'white');out.paste(im,(0,64));d=ImageDraw.Draw(out);d.text((12,7),txt,font=font,fill='#263540');d.text((12,36),'Оранжевый: дорожный край · зелёный: граница пешеходной зоны с неустановленной поверхностью',font=small,fill='#435761');return out +if (B/'whole-gaussians.jpg').exists():base=Image.open(B/'whole-gaussians.jpg').convert('RGB') +else: + width,height=v['size'];mosaic=np.full((height,width,3),255,np.uint8);weights=np.zeros((height,width),np.float32) + for tile in tiles: + lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/res).astype(int);x,y=np.rint([(lo[0]-low[0])/res,(high[1]-hi[1])/res]).astype(int) + im=np.asarray(Image.open(S/tile['id']/'top.png').convert('RGB').resize((tw,th),Image.Resampling.LANCZOS));g=np.load(S/tile['id']/'top.geometry.npz');alpha=np.asarray(Image.fromarray(g['alpha'].astype('float32')).resize((tw,th),Image.Resampling.BILINEAR));g.close() + yy,xx=np.mgrid[:th,:tw];score=(.01+np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy])/max(tw,th))*np.clip(alpha,0,1);sl=np.s_[y:y+th,x:x+tw];take=score>weights[sl];mosaic[sl][take]=im[take];weights[sl][take]=score[take] + base=Image.fromarray(mosaic) +world=lambda p:np.c_[(p[:,0]-low[0])/res,(high[1]-p[:,1])/res] +scene={'maroseyka':'Маросейка','pokrovka':'Покровка','smolensk':'Смоленский бульвар'}[os.environ['SCENE']] +rendered=[] +for features,name in [(old,'Предыдущая сборка'),(current,'Новый проход — кандидат')]: + im=overlay(base,features,world);im.thumbnail((2300,1400));rendered.append(title(im,scene+' · '+name)) +sheet=Image.new('RGB',(max(i.width for i in rendered),sum(i.height for i in rendered)+12),'white');y=0 +for im in rendered:sheet.paste(im,(0,y));y+=im.height+12 +sheet.save(O/'comparison.jpg',quality=95);rendered[-1].save(O/'road-overview.jpg',quality=95) +plan=Image.new('RGB',base.size,'#f5f5f2');plan=overlay(plan,current,world);plan.thumbnail((2300,1400));title(plan,scene+' · только границы').save(O/'vector-plan.jpg',quality=95) +scores=[] +for tile in tiles: + domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);a=[shape(f['geometry']).intersection(domain)for f in old if shape(f['geometry']).intersects(domain)];b=[shape(f['geometry']).intersection(domain)for f in current if shape(f['geometry']).intersects(domain)] + import shapely + ga=shapely.union_all(a);gb=shapely.union_all(b) + delta=ga.difference(gb.buffer(.15)).length+gb.difference(ga.buffer(.15)).length + scores.append((delta,tile)) +chosen=[] +for score,tile in sorted(scores,key=lambda x:-x[0]): + center=np.mean(tile['bounds_xy'],axis=0) + if any(np.linalg.norm(center-np.mean(t['bounds_xy'],axis=0))<70 for t in chosen):continue + chosen.append(tile) + if len(chosen)==3:break +sheet=Image.new('RGB',(2400,len(chosen)*865),'white');d=ImageDraw.Draw(sheet) +for row,tile in enumerate(chosen): + name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(S/name/'top.png').convert('RGB') + for col,(features,label)in enumerate([(None,'Гауссы'),(old,'Предыдущая сборка'),(current,'Новый проход')]): + im=raw if features is None else overlay(raw,features,lambda p:project(p,g)) + im=im.resize((800,800),Image.Resampling.LANCZOS);sheet.paste(im,(col*800,row*865+60));d.text((col*800+12,row*865+12),name+' · '+label,font=font,fill='#263540') +sheet.save(O/'road-details.jpg',quality=95) +(O/'road-visual-manifest.json').write_text(json.dumps(dict(selected=[t['id']for t in chosen],selection='largest geometry disagreement with baseline plus spatial spacing; review only',manual_rois=[],all_tile_scores=[dict(tile=t['id'],difference_m=float(s))for s,t in scores]),indent=2)) +print('RENDERED',len(current),[t['id']for t in chosen]) diff --git a/simulation/urban-plan-research/continuation_pass/road_glyph_presets.py b/simulation/urban-plan-research/continuation_pass/road_glyph_presets.py new file mode 100644 index 00000000..a365bf18 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/road_glyph_presets.py @@ -0,0 +1,42 @@ +"""Reusable arrow artwork adapted from the CC BY-SA 4.0 SVG by Major Alexey. +Source: https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg +License: https://creativecommons.org/licenses/by-sa/4.0/ +Changes: curve sampling, coordinate normalization, metric scaling and stroke fit. +This attribution/license concerns the arrow artwork in this module. +""" +import re +import numpy as np +from shapely.geometry import Polygon +from shapely.affinity import scale +SOURCE_SHA256='b76f40ee8d1603ddfeb3cd430f397dcc509684f0a0aa38c61bbd8a2cba554ea8' +PATHS={'straight_arrow': 'M38.4,168.5 23.2,123.5 10,169 20,168.9 20,273 28,273 28,168.7 Z', 'right_arrow': 'M83,149.8c0,0-15.1-26.4-15.1-25.6l-0.1,19.2l-24.4,19.2l0.6,0.8V273h7V171.7l16.8-13.2l-0.1,17.1\n\t\t\t\tL83,149.8z', 'left_arrow': 'M124.8,162l-23.9-18.7l-0.1-19c0-0.8-15.1,25.6-15.1,25.6l15.3,25.6l-0.1-17.1l17.1,13.4V273h8V162H124.8z\n\t\t\t\t', 'straight_right_arrow': 'M179.4,206.5c0,0-15.1-26.4-15.1-25.6l-0.1,19.2L146,214.4v-45.7l11.7-0.2l-15.2-45L129.2,169l9.8-0.2V273\n\t\t\t\th7v-45.8l1.1,1.4l17.1-13.4l-0.1,17L179.4,206.5z', 'straight_left_arrow': 'M231.9,169l-13.3-45.5l-15.2,45l10.6,0.2v44.9l-17.1-13.5l-0.1-19.2c0-0.8-15.1,25.6-15.1,25.6l15.3,25.6\n\t\t\t\tl-0.1-16.9l17,13.4l0.1-0.1V273h8V168.9L231.9,169z'} + +def parse_path(path): + tokens=re.findall(r'[MLHVClmhvcZz]|[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?',path) + points=[];p=np.zeros(2);i=0;command=None + while i.001:g=g.buffer(delta,join_style=2) + return g diff --git a/simulation/urban-plan-research/continuation_pass/test_refine.py b/simulation/urban-plan-research/continuation_pass/test_refine.py new file mode 100644 index 00000000..630c0ba2 --- /dev/null +++ b/simulation/urban-plan-research/continuation_pass/test_refine.py @@ -0,0 +1,81 @@ +import json +from pathlib import Path +import numpy as np,shapely +from shapely.geometry import LineString +from continuations import connect,regularize,ContinuationPolicy,observed_crossing_length +from object_solver import sample_chain + +def record(name,p,**kwargs):return dict(id=name,points=sample_chain(p,.25),**{'class':'road_boundary'},**kwargs) +checks=[] +def check(name,passed,**details):checks.append(dict(name=name,passed=bool(passed),**details));assert passed,(name,details) +a=record('left',[[0,0],[12,0]]);b=record('right',[[18,0],[32,0]]) +out,audit=connect([a,b]);check('six-metre-occlusion',len(out)==1 and len(audit['selected'])==1 and LineString(out[0]['points']).hausdorff_distance(LineString([[0,0],[32,0]]))<.01) +out,audit=connect([a,{**b,'reasons':['survey-exterior',None]}]);check('explicit-survey-exit-remains-open',len(out)==2) +out,audit=connect([record('north',[[0,5],[12,5]]),record('south',[[0,-5],[12,-5]])]);check('opposite-parallel-sides-not-capped',len(out)==2) +out,audit=connect([a,b],lambda *_:dict(allowed=False,reason='road-crossing-cap'));check('observed-opening-veto',len(out)==2) +c=record('branch',[[18,2],[28,3]]) +out,audit=connect([a,b,c]);check('global-endpoint-choice-selects-straight',len(audit['selected'])==1 and set(audit['selected'][0]['source_ids'])=={'left','right'}) +p=sample_chain([[0,0],[12,0],[12,-2],[20,-2],[20,0],[35,0]],.2);q,_=regularize(p);check('square-parking-pocket-preserved',LineString(p).hausdorff_distance(LineString(q))<.45) +theta=np.linspace(-np.pi/2,0,50);p=sample_chain(np.vstack([[[0,0],[12,0]],np.c_[12+8*np.cos(theta),8+8*np.sin(theta)],[[20,22]]]),.2);q,_=regularize(p);check('round-turn-preserved',LineString(p).hausdorff_distance(LineString(q))<.45) +# Rotation/translation change no topology or metric policy. +angle=.73;R=np.array([[np.cos(angle),-np.sin(angle)],[np.sin(angle),np.cos(angle)]]);offset=np.array([350,-480]) +out2,audit2=connect([{**x,'points':x['points']@R.T+offset}for x in [a,b,c]]) +check('rigid-transform-transfer',len(audit2['selected'])==1 and set(audit2['selected'][0]['source_ids'])=={'left','right'}) +# Object-level checks exercise missing evidence and rejection, not just output shape. +from shapely.geometry import box,Polygon +from paint_families import normalize +from paint_templates import fit_symbol,template +from layer_common import feature +from frontage_chains import join_planes +features=[feature(box(x,-.08,x+2,.08),'road_marking',subtype='linear_marking')for x in [0,5,15,20]] +out,audit=normalize(features,lambda g:g,lambda g:True) +check('periodic-family-fills-internal-slot',len(out)==5 and len(audit)==1 and audit[0]['added_internal_m_or_slots']==1) +geometries=[shapely.geometry.shape(x['geometry'])for x in out] +check('periodic-family-no-extrapolation',min(g.bounds[0]for g in geometries)>-.01 and max(g.bounds[2]for g in geometries)<22.01) +parallel=[feature(box(x,y,x+7,y+.12),'road_marking',subtype='linear_marking')for x in [0,7.5]for y in [0,1]] +out,audit=normalize(parallel,lambda g:g,lambda g:True) +check('parallel-paint-families-stay-separate',len(out)==2 and len(audit)==2) +planes=[LineString([[0,0],[8,0]]),LineString([[13,0],[21,0]])] +out=join_planes(planes,gap=8,bridge_validator=lambda line,sources:not line.intersects(box(9,-1,12,1))) +check('facade-gap-does-not-bridge-street',len(out)==2) +out=join_planes(planes,gap=8,bridge_validator=lambda *_:True) +check('facade-occlusion-interpolated',len(out)==1 and len(out[0][1])==2) +a=template('letter_A',4,1.2,.18) +# A small loss at one foot is permitted; the distinguishing open counter remains. +worn=a.difference(box(-.3,-.8,.25,-.4));fit=fit_symbol(worn) +check('worn-A-recognized',fit is not None and fit[2]=='letter_A') +solid=Polygon([[0,-.6],[4,0],[0,.6]]) +fit=fit_symbol(solid) +check('filled-triangle-not-A',fit is None or fit[2]!='letter_A') +turn=template('straight_left_arrow',5,1.7,.16);diagnostics=[];fit=fit_symbol(turn,heading=[1,0],diagnostics=diagnostics) +if fit is None:print(json.dumps(diagnostics),flush=True) +check('compound-arrow-not-A',fit is not None and fit[2]=='straight_left_arrow',result=None if fit is None else fit[2]) +# A physical curb with an occluded middle must overrule a spurious sidewalk bow. +from types import SimpleNamespace +from boundary_anchors import PhysicalFields +from reanchor import snap +xx,yy=np.meshgrid(np.arange(400)*.1-5+.05,5-(np.arange(100)*.1+.05)) +side=(yy>0).astype('float32');rgb=np.repeat((90+80*side).astype('uint8')[:,:,None],3,axis=2);z=side*.12;alpha=np.ones_like(side) +vehicle=((xx>10)&(xx<18)&(abs(yy)<2)).astype('float32') +fields=PhysicalFields(rgb,z,alpha,vehicle,1-side,side,.1) +f=SimpleNamespace(low=np.array([-5.,-5.]),high=np.array([35.,5.]),cell=.1,side=side.astype(bool),road_mask=1-side,fields=fields) +x=np.linspace(0,30,151);points=np.c_[x,1.2*np.sin(np.pi*x/30)**2,np.zeros(len(x))] +r=dict(id='occluded-curb',points=points,spans=[points[(x>=8)&(x<=22)].tolist()],**{'class':'road_boundary'}) +q,audit=snap(r,f) +check('physical-curb-corrects-interior-bow',audit['changed'] and np.mean(abs(q['points'][:,1]))<.2,audit=audit) +check('reanchor-preserves-scan-terminals',np.allclose(q['points'][[0,-1]],points[[0,-1]])) +straight=np.array([[0.,0.],[18.,0.]]) +road=lambda p:((p[:,0]>8)&(p[:,0]<9.5)).astype(float) +ones=lambda p:np.ones(len(p));zeros=lambda p:np.zeros(len(p)) +check('narrow-visible-road-not-diluted-by-long-gap',observed_crossing_length(straight,road,ones,zeros)>.6) +check('vehicle-occlusion-is-not-observed-opening',observed_crossing_length(straight,road,ones,ones)==0) +check('along-curb-is-not-a-road-cap',observed_crossing_length(straight,lambda p:(p[:,1]<.1).astype(float),ones,zeros)==0) +from paint_dedup import deduplicate_glyphs +from shapely.affinity import translate,scale +g=template('letter_A',4,1.2,.18) +glyphs=[feature(p,'road_marking',subtype='letter_A',method='symbol-template',template_fit_score=s)for p,s in [(g,.94),(translate(scale(g,xfact=1.04,yfact=.96),.03,.02),.91),(translate(g,7,0),.92)]] +out,duplicates=deduplicate_glyphs(glyphs) +check('overlapping-glyph-fits-merged',len(out)==2 and len(duplicates)==1 and glyphs[0]['id']in [f['id']for f in out]) +check('nearby-independent-glyph-retained',glyphs[2]['id']in [f['id']for f in out]) +report=dict(passed=all(x['passed']for x in checks),checks=checks,real_scene_accuracy=False) +Path('/out/tests.json').write_text(json.dumps(report,indent=2));print(json.dumps(report)) diff --git a/simulation/urban-plan-research/corridor_pass/README.rst b/simulation/urban-plan-research/corridor_pass/README.rst new file mode 100644 index 00000000..50b6823a --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/README.rst @@ -0,0 +1,67 @@ +Automatic coverage and paint corridor calibration +================================================ + +Offline Gaussian-only continuation of completion-pass-20261012. Same algorithm +and metre-based policy on Maroseyka, Pokrovka and Smolensk. No scene-specific +coordinates, processing regions, point clouds, live deployment or rover commands. + +Stages +------ +1. Census existing periodic anchors and bounded neighboring slots. Distinguish + missing second render footprint from alpha, road, vehicle and symbol masks. +2. Greedy coverage planning on a metric grid; render additional 60 m / 4096 px + ground views only where two-render coverage is absent. Reuse the exact + Gaussian source and terrain field, height slice -0.6..+0.8 m. Vehicle exclusion + is the maximum probability from existing overlapping masks; unknown remains + blocked. This adds rendered coverage, not physical observations or scans. +3. Measure paint peaks, offsets and stroke lengths in two geometrically selected + views. Refit phase/period and a bounded smooth lateral model using SciPy robust + least squares. At least three measured anchors and three fully revalidated + anchors are required. Never fill a periodic slot without visible paint and + both adjacent observed gaps. The 4096 pixel raster is sampling resolution, + not measured surveying accuracy. +4. Add genuinely missing strokes. Refit existing strokes only when the change is + material and removed paint area is independently dark in both render mosaics. + Preserve other vectors and all other infrastructure layers. +5. Replay qualified periodic-row discovery across all eligible existing axes + using the augmented mosaics; add only genuinely absent, image-validated + strokes. Reuse the existing two-ridge extractor to nominate adjacent dividers. Both + mosaics must agree on the candidate, and full-object paint support must pass. + Subtract entire occupied longitudinal intervals to avoid narrow side slivers; + add only observed missing solid spans at least 2.7 m long. +6. Replay transaction audit, controlled negative/positive cases, full three-scene + qualification, and direct visual before/after inspection. + +Run through the official recorded-job queue on Worker 006. Pinned image, +network disabled, read-only source, 4 CPU, 20 GiB RAM, GPU only for Gaussian +rendering. The stage runner records source hashes, input hashes, UTC, monotonic +execution times and resource release. Every output change has a transaction. + +Limits +------ +The coverage census here is scoped to existing periodic marking families and +bounded adjacent slots, not a complete census of every road/building region. +Candidate rows still require existing vector anchors. Three familiar scenes are +regression checks, not unseen-data generalization proof. Two views of one Gaussian +reconstruction can share artifacts. No complete recall or absolute accuracy +measurement. GOST associations remain soft dimensional evidence, not compliance. +Arrows, zebras, roads, sidewalks and facades remain the previously accepted layers. + +Reuse and attribution +--------------------- +OpenCV morphology and ridge extraction, SciPy signal peaks and robust fitting, +Shapely metric geometry, existing gsplat rendering and terrain clipping. Replay +bundle retains earlier tests and arrow preset modules. Arrow artwork by +MajorAlexey, adapted to normalized polygon presets under CC BY-SA 4.0: +https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg +https://creativecommons.org/licenses/by-sa/4.0/ + +Qualified result +---------------- +Frozen source f08fe6a347e01e7d226b. All 237 controlled checks passed. +Maroseyka: 10 extra render tiles, 15 existing strokes corrected, 1 new stroke. +Pokrovka: 4 extra render tiles, 8 existing strokes corrected, 12 new strokes. +Smolensk: no map edits and no periodic-family coverage targets. +No new solid divider sections accepted. Thirteen new strokes are distinct from +the 23 corrections of existing strokes. Direct visual review covers 29 edit +transactions. Coverage gaps among checked anchors: 19 to 0 and 4 to 0. diff --git a/simulation/urban-plan-research/corridor_pass/audit_corridor.py b/simulation/urban-plan-research/corridor_pass/audit_corridor.py new file mode 100644 index 00000000..04c9bccc --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/audit_corridor.py @@ -0,0 +1,33 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +from corridor_profiles import POLICY,VERSION +from completion_profiles import supported,gap_supported +old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/corridor-rows.json').read_text());current={f['id']:f for f in old['features']};checks={k:True for k in ['transaction_replay','only_linear_objects_edited','no_new_neighbor_overlap','evidence_passes','retained_model_constraints']} +poly=lambda f:shapely.force_2d(shape(f['geometry'])) +for r in rows: + ids=r['source_ids'];before=r['before'];after=r['after'];checks['transaction_replay'] &= ids==[f['id']for f in before]and r['output_ids']==[f['id']for f in after]and all(current.get(f['id'])==f for f in before) + checks['only_linear_objects_edited'] &= all(f['properties'].get('subtype')=='linear_marking'for f in before+after) + a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in after]);novel=b.difference(a) + checks['no_new_neighbor_overlap'] &= all(novel.intersection(poly(f)).area<=.005 for fid,f in current.items()if fid not in ids and f['properties']['class']=='road_marking') + ev=r['evidence'];ok=len(r['source_views'])==2 and len(r['source_tiles'])>=2 + if r['kind'].startswith('calibrated-'): + ok &= len(ev['anchors'])>=3 and len(after)==1 + for record in [ev['slot']]+[q['views']for q in ev['anchors']]: + ok &= len(record)==2 and all(supported(v['paint'])and len(v['gaps'])==2 and all(g.get('full_corridor')and gap_supported(g,v['paint'])for g in v['gaps'])for v in record) + ok &= max(abs(record[0]['edges'][j]-record[1]['edges'][j])for j in [0,1])<=.20 + ok &= all(v['valid']>=.95 and v['dark_fraction']>=.85 for v in ev['removed']) + ok &= (len(before)==0 if r['kind']=='calibrated-new-stroke'else len(before)==1) + model=ev['model'];checks['retained_model_constraints'] &= model['max_residual']<=POLICY['max_curve_residual_m'] and model['length']>=.26 + elif r['kind']=='observed-periodic-strokes': + ok &= not before and len(ev['paint'])==2*len(ev['observations'])and all(supported(v)for v in ev['paint']) + ok &= len(ev['gaps'])==2*(len(ev['observations'])-1)and all(supported(v,False)if ev['mode']=='intervals'else v['valid']>=.95 and v['contrast_drop']>=18 and v['contrast']<(v['contrast']+v['contrast_drop'])*.65 for v in ev['gaps']) + ok &= all(len(v['edges'])==2 and max(abs(v['edges'][0][k]-v['edges'][1][k])for k in [0,1])<=.20 for v in ev['observations']) + elif r['kind']=='observed-companion-divider': + ok &= not before and len(ev['views'])==2 and ev['independent_polygon_iou']>.75 and all(v['valid']>=.98 and v['support']>=.85 for v in ev['views']) + else:ok=False + checks['evidence_passes'] &= ok + for fid in ids:current.pop(fid,None) + for f in after:current[f['id']]=f +features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=current==features;checks['unique_ids']=len(features)==len(new['features']);checks['unchanged_other_layers']=all(features.get(f['id'])==f for f in old['features']if f['properties'].get('subtype')!='linear_marking');checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']);checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes();report=json.loads(Path('/out/corridor-report.json').read_text());checks['same_policy']=new['corridor_refinement']==VERSION and report['policy']==POLICY;checks['every_operation_counted']=report['changed_segments']==len(rows)and sum(report['stages'].values())==len(rows) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False);Path('/out/corridor-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/corridor_pass/bundle.json b/simulation/urban-plan-research/corridor_pass/bundle.json new file mode 100644 index 00000000..e5445e05 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/bundle.json @@ -0,0 +1,154 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_completion.py": "completion_pass/audit_completion.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_corridor.py": "corridor_pass/audit_corridor.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "completion_profiles.py": "completion_pass/completion_profiles.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "coordinate_cache.py": "orthophoto/coordinate_cache.py", + "corridor_profiles.py": "corridor_pass/corridor_profiles.py", + "coverage_evidence.py": "corridor_pass/coverage_evidence.py", + "coverage_plan.py": "corridor_pass/coverage_plan.py", + "diagnose_corridor.py": "corridor_pass/diagnose_corridor.py", + "diagnose_coverage.py": "corridor_pass/diagnose_coverage.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "mapping.py": "corridor_pass/mapping.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "ortho_terrain.py": "orthophoto/ortho_terrain.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_completion.py": "completion_pass/refine_completion.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_corridor.py": "corridor_pass/refine_corridor.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_completion.py": "completion_pass/render_completion.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_corridor.py": "corridor_pass/render_corridor.py", + "render_coverage.py": "corridor_pass/render_coverage.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "continuation_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "corridor_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_completion.py": "completion_pass/test_completion.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_corridor.py": "corridor_pass/test_corridor.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py", + "validation.py": "corridor_pass/validation.py" + }, + "reference_qualification": "corridor-pass-20261012", + "source_snapshot": "f08fe6a347e01e7d226b", + "source_sha256": { + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_completion.py": "ef6adcfec3e1a4bd894b54a150fe3b8559bf73e94665bb9da6bd68007e90575d", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_corridor.py": "3f792b1830e9097644dd66c38eb2cf7efa11d75a0fda928ffa0a7780afb85bfe", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "completion_profiles.py": "b01cb280a265f170c2f3823d59d423c0cf11472050678cc4dad716c1f90ff786", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "coordinate_cache.py": "930f8f521ef13c02b589d0c182ab4cf337acc4c213354808d32178bbbea3edf4", + "corridor_profiles.py": "89428834387b56d9fcbfcd4fc00c963b05c2087e2fb5d75a488aa2a3f5322a77", + "coverage_evidence.py": "1b9c1e4b0c518047ad1eacc6e314132144ae05dcad8cc82dd88b9e1340513497", + "coverage_plan.py": "48e28d6781d5d04e83645ba0a9aa7f0398ae904d26bf2e81caa8d8e741bccdda", + "diagnose_corridor.py": "cff89f2a78ff315906b7d40ba1855f0f842afe1f7f74d1d38b7366e2959bcfd6", + "diagnose_coverage.py": "f5305f0c429aea3ba5f18e4261abd64fe8254e53db24323ffcebc152734864b7", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "mapping.py": "1c6ba0cc111250d73bc0bc282e9cbb7a602921bca931da6441bc9a6daf88b4f4", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "ortho_terrain.py": "9c9cab9d7086144fd1a108db28f796e9d267375d7135d50d5cb3f054eae75213", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_completion.py": "12f424d39a687e8b94823f2e2f7b2f2c95538f3504260b4373c47cc21b29c6e1", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_corridor.py": "fd1c4d4e028a037e32538c26a66f876425088b8b5b2c7ffc8d5dc807eba3290f", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_completion.py": "5e76d2a6ce41a6be8013f98df33951fe17fc209c078376ebfafe7c60ed0b14a7", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_corridor.py": "f6355e3761834fcf811c0cae9dc3ce602e7221afea4f674178d6c29085e87e9f", + "render_coverage.py": "2cba12c09333c242841b174f201c89ffce9e715b78b26b472117ae140ff4157c", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "row_evidence.py": "fec784ab795470d96e48c7022e59d5206b0c07b40d84843cbc058fcc4de896c0", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_completion.py": "a3a6a283221ae48ade8fd0cca2f145509fd6bedf8e808967c13438791654a7f1", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_corridor.py": "42788835ec88e91a3b92ec7ead4e4c489b01ddf11256b46b7b3722c6b4770703", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e", + "validation.py": "ee004220db3cdf2429af2a0e875cd9a63526587422881692ce56fe9d77f5cc2c" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/corridor_pass/corridor_profiles.py b/simulation/urban-plan-research/corridor_pass/corridor_profiles.py new file mode 100644 index 00000000..60775f55 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/corridor_profiles.py @@ -0,0 +1,81 @@ +"""Metric corridor calibration from measured paint, shared by all locations. + +OpenCV transverse background, SciPy peaks and robust polynomial least squares. +The old vectors nominate a corridor, never dictate its paint length or offset. +""" +import numpy as np +from scipy.signal import find_peaks,peak_widths +from scipy.ndimage import gaussian_filter1d +from scipy.optimize import least_squares +from interval_profiles import strip,runs,rectangle +from completion_profiles import POLICY as BASE,slot +VERSION='paint-corridor-calibration-v1' +POLICY={**BASE,'max_measured_offset_m':.35,'min_calibration_anchors':3,'max_curve_angle_deg':8.,'max_curve_second_derivative':.02,'max_curve_residual_m':.06,'max_measured_phase_m':.35,'max_length_recalibration_ratio':.5,'max_curve_extrapolation_m':8.,'min_pair_support':.85} + +def measure(seed,index,readers,debug=None): + if len(readers)!=2:return None + o,u=seed['origin'],seed['axis'];P,L=seed['period'],seed['length'];c=index*P;step=.025;ext=min(P/2,L/2+max(.5,.3*L));ts=np.arange(c-ext,c+ext+step/2,step);ns=np.arange(-.7,.701,step);records=[] + for vi,read in enumerate(readers): + con,allowed=strip(o,u,ts,ns,read);core=abs(ts-c)cut)&valid + for a,b in runs(~on): + if a>0 and b0 and b0 and bcut).mean()),contrast=float(np.median(sig[sel]))) + if bright['valid']<.95 or bright['support']<.82 or bright['contrast']<22:return None + records.append(dict(center=center,offset=float(ns[k]),length=length,width=W,paint=bright,edges=[lo,hi])) + if abs(records[0]['offset']-records[1]['offset'])>.05 or max(abs(records[0]['edges'][j]-records[1]['edges'][j])for j in [0,1])>.20:return None + return dict(index=index,center=float(np.mean([r['center']for r in records])),offset=float(np.mean([r['offset']for r in records])),length=float(np.median([r['length']for r in records])),width=float(np.median([r['width']for r in records])),views=records) + +def calibrate(seed,observations): + anchors=[r for r in observations if r['index']in seed['indices']] + if len(anchors).10*seed['period']or max(abs(ts-(phase+indices*P)))>.20 or max(abs(lengths-L))>max(.20,.25*L):return None + mid=float(np.mean(ts));scale=max(1.,float(np.ptp(ts)));x=(ts-mid)/scale;degree=2 if len(anchors)>=5 and np.ptp(ts)>=4 else 1 + A=np.stack([x**i for i in range(degree+1)],1);coef=least_squares(lambda c:A@c-ys,np.linalg.lstsq(A,ys,rcond=None)[0],loss='soft_l1',f_scale=.025).x + res=np.abs(A@coef-ys) + if max(res)>POLICY['max_curve_residual_m']:return None + probe=np.linspace(ts.min()-8,ts.max()+8,100);xx=(probe-mid)/scale;dy=np.polynomial.polynomial.polyval(xx,np.arange(1,len(coef))*coef[1:])/scale + second=2*coef[2]/scale**2 if degree==2 else 0. + if max(abs(dy))>np.tan(np.deg2rad(POLICY['max_curve_angle_deg']))or abs(second)>POLICY['max_curve_second_derivative']:return None + return dict(origin=seed['origin'],axis=seed['axis'],period=float(P),phase=float(phase),length=L,width=float(np.clip(np.median([r['width']for r in anchors]),.075,.27)),mid=mid,scale=scale,coef=coef,anchor_range=[float(ts.min()),float(ts.max())],anchors=anchors,max_residual=float(max(res))) + +def local_seed(model,index): + t=model['phase']+index*model['period'];x=(t-model['mid'])/model['scale'];coef=model['coef'];d=float(np.polynomial.polynomial.polyval(x,coef));slope=float(np.polynomial.polynomial.polyval(x,np.arange(1,len(coef))*coef[1:])/model['scale']);u=model['axis'];n=np.array([-u[1],u[0]]);axis=u+slope*n;axis/=np.linalg.norm(axis) + if abs(d)>POLICY['max_measured_offset_m']or tmodel['anchor_range'][1]+POLICY['max_curve_extrapolation_m']:return None + return dict(origin=model['origin']+t*u+d*n,axis=axis,period=model['period'],length=model['length'],width=model['width']) + +def validated_slot(model,index,readers,debug=None): + local=local_seed(model,index) + if local is None:return None + return slot(local,0,readers,debug) + +def missing_sections(candidate,existing): + """Subtract occupied longitudinal intervals, never create parallel side slivers.""" + import shapely + from layer_common import parts + from beta_profiles import describe + d=describe(candidate) + if d is None:return [] + o,u=d['origin'],d['axis'];output=candidate + nearby=existing.intersection(candidate.buffer(.10,join_style=2)) + for part in parts(nearby): + tt=(shapely.get_coordinates(part)-o)@u + output=output.difference(rectangle(o,u,float(tt.min())-.12,float(tt.max())+.12,2.)) + return [p for p in parts(output)if (z:=describe(p))is not None and z['length']>=2.7 and p.area>.15] diff --git a/simulation/urban-plan-research/corridor_pass/coverage_evidence.py b/simulation/urban-plan-research/corridor_pass/coverage_evidence.py new file mode 100644 index 00000000..cf96fec6 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/coverage_evidence.py @@ -0,0 +1,16 @@ +from pathlib import Path +import json,numpy as np +from functools import lru_cache +from PIL import Image +from discovery_evidence import DiscoveryViews +from layer_common import O +class CoverageViews(DiscoveryViews): + def __init__(self,tiles,*args): + p=O/'coverage/manifest.json';extra=json.loads(p.read_text())['tiles']if p.exists()else[];self.additional={t['id']for t in extra};super().__init__(tiles+extra,*args) + @lru_cache(maxsize=90) + def geometry(self,name): + return dict(np.load(O/'coverage'/name/'top.geometry.npz'))if name in self.additional else super().geometry(name) + @lru_cache(maxsize=12) + def inputs(self,name): + if name not in self.additional:return super().inputs(name) + return np.asarray(Image.open(O/'coverage'/name/'ground.png').convert('RGB')),np.load(O/'coverage'/name/'vehicle.npz')['vehicle'].astype('float32') diff --git a/simulation/urban-plan-research/corridor_pass/coverage_plan.py b/simulation/urban-plan-research/corridor_pass/coverage_plan.py new file mode 100644 index 00000000..23872584 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/coverage_plan.py @@ -0,0 +1,13 @@ +"""Automatically fill two-render coverage gaps; no operator-selected regions.""" +import numpy as np +POLICY=dict(width_m=60.,render_pixels=4096,center_grid_m=10.,usable_half_width_m=24.,max_tiles=40,lower_height_m=-.6,ground_height_m=.8) +def plan_centers(records): + points=np.array([r['center_xy']for r in records if any(v['gates']['coverage']<.95 for v in r['views'])],float).reshape(-1,2) + if not len(points):return [] + candidates=np.unique(np.round(points/POLICY['center_grid_m'])*POLICY['center_grid_m'],axis=0);remaining=np.ones(len(points),bool);result=[] + while remaining.any(): + covered=(abs(candidates[:,None,:]-points).max(2)<=POLICY['usable_half_width_m'])&remaining;counts=covered.sum(1);i=int(np.argmax(counts)) + if not counts[i]:raise ValueError('Uncovered target') + result.append(dict(center=candidates[i].tolist(),target_count=int(counts[i])));remaining[covered[i]]=False + if len(result)>POLICY['max_tiles']:raise ValueError('Automatic coverage budget exceeded') + return result diff --git a/simulation/urban-plan-research/corridor_pass/diagnose_corridor.py b/simulation/urban-plan-research/corridor_pass/diagnose_corridor.py new file mode 100644 index 00000000..6749364d --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/diagnose_corridor.py @@ -0,0 +1,28 @@ +from pathlib import Path +import json,os,collections,time +import numpy as np,shapely +from shapely.geometry import shape +from completion_profiles import families,slot +from discovery_evidence import DiscoveryViews +from layer_common import S,O +from interval_profiles import strip +from scipy.signal import find_peaks +started=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text()) +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +poly=lambda f:shapely.force_2d(shape(f['geometry'])) +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +views=DiscoveryViews(tiles,labels,low,high,protected);records=[] +fs=families([(f['id'],poly(f),f['properties'])for f in old['features']if f['properties'].get('subtype')=='linear_marking']) +for fi,g in enumerate(fs): + readers,used=views.readers(g['origin'],g['axis']);o,u=g['origin'],g['axis'];n=np.array([-u[1],u[0]]) + for ix in range(-2,g['max_index']+3): + d={};r=slot(g,ix,readers,d);c=ix*g['period'];ts=np.arange(c-.3*g['length'],c+.3*g['length'],.025);ns=np.arange(-.7,.701,.025);xy=(o+ts[:,None,None]*u+ns[None,:,None]*n).reshape(-1,2);evidence=[] + for reader in readers: + rgb,valid,gates=reader(xy,True);con,al=strip(o,u,ts,ns,reader);cross=np.median(np.where(al,con,0),axis=0);raw=np.median(con,axis=0);pk,_=find_peaks(cross,height=22,prominence=10,distance=4);pk0,_=find_peaks(raw,height=22,prominence=10,distance=4);band=np.tile(abs(ns)<=max(.04,g['width']*.25),len(ts));evidence.append(dict(gates={k:float(v[band].mean()) for k,v in gates.items()},valid=float(valid[band].mean()),offset_peaks=[dict(offset=float(ns[k]),contrast=float(cross[k]))for k in pk],unmasked_peaks=[dict(offset=float(ns[k]),contrast=float(raw[k]))for k in pk0])) + records.append(dict(family=fi,index=ix,anchor=ix in g['indices'],passed=r is not None,strict=d,views=evidence,center_xy=(o+c*u).tolist(),length=g['length'],period=g['period'],width=g['width'])) + print('FAMILY',fi+1,len(fs),flush=True) +summary={} +for subset in ['anchors','all']: + recs=[r for r in records if subset=='all'or r['anchor']];failed=[r for r in recs if not r['passed']];summary[subset]=dict(total=len(recs),passed=len(recs)-len(failed),reasons=dict(collections.Counter(r['strict'].get('reason','unclassified') for r in failed)),mask_failures={k:sum(any(v['gates'][k]<.95 for v in r['views'])for r in failed)for k in ['coverage','alpha','road','vehicle','protected']},off_axis_ridge=sum(all(any(.05= bounds[0] - job.get('halo_m', 15)) & + (world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1) + rows.append(d[mask].copy()) + d = np.concatenate(rows) + del rows + if not len(d): + raise ValueError('No Gaussians in the requested tile') + def tensor(names): + return torch.tensor(np.column_stack([d[n] for n in names]), device='cuda', dtype=torch.float32) + means = tensor(['x', 'y', 'z']) + quats = tensor([f'rot_{i}' for i in range(4)]) + scales = tensor([f'scale_{i}' for i in range(3)]).exp() + opacity = tensor(['opacity']).squeeze(-1).sigmoid() + dc = tensor([f'f_dc_{i}' for i in range(3)])[:, None, :] + rest_names = sorted((n for n in d.dtype.names if n.startswith('f_rest_')), key=lambda n: int(n.split('_')[-1])) + sh = torch.cat([dc, tensor(rest_names).reshape(len(d), 3, -1).transpose(1, 2)], dim=1) if rest_names else dc + degree = int(math.sqrt(sh.shape[1])) - 1 + print(json.dumps({'stage': 'render', 'source_splats': len(data), 'tile_splats': len(d), 'sh_degree': degree}), flush=True) + for spec in job['views']: + view, k = camera(spec) + w, h = spec['size'] + with torch.inference_mode(): + rgbd, alpha, _ = rasterization(means, quats, scales, opacity, sh, + torch.tensor(view @ transform, device='cuda', dtype=torch.float32)[None], + torch.tensor(k, device='cuda')[None], w, h, sh_degree=degree, + camera_model=spec.get('projection', 'pinhole'), render_mode='RGB+ED', + packed=True) + rgbd, alpha = rgbd[0].cpu().numpy(), alpha[0, :, :, 0].cpu().numpy() + rgbd[:, :, :3] += (1 - alpha[:, :, None]) + Image.fromarray(np.uint8(np.clip(rgbd[:, :, :3], 0, 1) * 255)).save(output / (spec['id'] + '.png')) + np.savez_compressed(output / (spec['id'] + '.geometry.npz'), depth=rgbd[:, :, 3], alpha=alpha, view=view, intrinsics=k) + write_json(output / (spec['id'] + '.render.json'), {'inputs': phase_inputs(job, spec), + 'files': {spec['id'] + ext: digest(output / (spec['id'] + ext)) for ext in ['.png', '.geometry.npz']}}) + print(json.dumps({'view': spec['id'], 'opaque_fraction': float(np.mean(alpha >= .95))}), flush=True) + + +def infer(job, output): + import torch + from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation + model_path = Path('/model') + global _semantic_cache + if '_semantic_cache' not in globals(): _semantic_cache = None + for name, expected in (job['model']['files'].items() if _semantic_cache is None else []): + if digest(model_path / name) != expected: + raise ValueError('Model asset checksum mismatch: ' + name) + if _semantic_cache is None: + _semantic_cache = (AutoImageProcessor.from_pretrained(model_path, local_files_only=True), + Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval()) + processor, model = _semantic_cache + for spec in job['views']: + if spec.get('projection', 'pinhole') != 'pinhole': + continue # Mapillary is a street-view model; orthographic views are review only. + verify_phase(output, spec['id'] + '.render.json', phase_inputs(job, spec)) + image = Image.open(output / (spec['id'] + '.png')).convert('RGB') + inputs = processor(images=image, return_tensors='pt').to('cuda') + with torch.inference_mode(): + result = model(**inputs) + # Same query aggregation as the upstream semantic postprocessor; retain a confidence plane. + classes = result.class_queries_logits.softmax(-1)[..., :-1] + masks = torch.nn.functional.interpolate(result.masks_queries_logits, size=(image.height, image.width), mode='bilinear', align_corners=False).sigmoid() + scores = torch.einsum('bqc,bqhw->bchw', classes, masks)[0] + value, labels = scores.max(0) + confidence = value / scores.sum(0).clamp_min(1e-6) + labels, confidence = labels.byte().cpu().numpy(), confidence.cpu().numpy() + geometry = np.load(output / (spec['id'] + '.geometry.npz')) + valid = (geometry['alpha'] >= .95) & np.isfinite(geometry['depth']) & (geometry['depth'] > 0) + labels[(confidence < job.get('min_confidence', .65)) | ~valid] = 255 + Image.fromarray(labels).save(output / (spec['id'] + '.labels.png')) + np.save(output / (spec['id'] + '.confidence.npy'), confidence) + base = np.asarray(image).copy() + overlay = base.copy() + for cls, (name, color) in CLASSES.items(): + overlay[labels == cls] = np.uint8(.45 * base[labels == cls] + .55 * np.array(color)) + Image.fromarray(overlay).save(output / (spec['id'] + '.overlay.png')) + write_json(output / (spec['id'] + '.inference.json'), {'inputs': inference_inputs(job, spec), + 'files': {spec['id'] + ext: digest(output / (spec['id'] + ext)) for ext in ['.labels.png', '.confidence.npy']}}) + print(json.dumps({'view': spec['id'], 'stage': 'inference', 'pixels': {CLASSES[c][0]: int((labels == c).sum()) for c in CLASSES if np.any(labels == c)}, 'unknown': int((labels == 255).sum())}), flush=True) + + +def inference_inputs(job, spec): + return fingerprint({'render': phase_inputs(job, spec), 'model': job['model'], 'confidence': job.get('min_confidence', .65)}) + + +def verify_phase(output, manifest, expected): + receipt = json.loads((output / manifest).read_text()) + if receipt['inputs'] != expected or any(digest(output / name) != sha for name, sha in receipt['files'].items()): + raise ValueError('Stale or changed phase input: ' + manifest) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--job', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--stage', choices=['render', 'infer', 'atlas', 'all'], default='all') + args = parser.parse_args() + job = validate_job(json.loads(args.job.read_text())) + args.output.mkdir(parents=True, exist_ok=True) + started = time.monotonic() + from atlas import fuse + def atlas(job, output): + for spec in job['views']: + verify_phase(output, spec['id'] + '.render.json', phase_inputs(job, spec)) + if spec.get('projection', 'pinhole') == 'pinhole': + verify_phase(output, spec['id'] + '.inference.json', inference_inputs(job, spec)) + document = fuse(job, output, unproject, CLASSES, write_json) + print(json.dumps({'stage': 'atlas', 'features': len(document['features']), 'coverage': document['coverage']}), flush=True) + for name, fn in [('render', render), ('infer', infer), ('atlas', atlas)]: + if args.stage in ['all', name]: + fn(job, args.output) + write_json(args.output / ('receipt-' + args.stage + '.json'), { + 'schema_version': 'missioncore.urban-mapping-receipt/v1', 'utc': datetime.now(timezone.utc).isoformat(), + 'elapsed_s': time.monotonic() - started, 'job_sha256': digest(args.job), 'stage': args.stage, + 'implementation': {p.name: digest(p) for p in Path(__file__).parent.glob('*.py')}, + 'files': {p.name: digest(p) for p in args.output.iterdir() if p.is_file() and not p.name.startswith('receipt-')}, + }) + +if __name__ == '__main__': + main() diff --git a/simulation/urban-plan-research/corridor_pass/refine_corridor.py b/simulation/urban-plan-research/corridor_pass/refine_corridor.py new file mode 100644 index 00000000..c5a93554 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/refine_corridor.py @@ -0,0 +1,116 @@ +from pathlib import Path +import os,json,time,hashlib,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping +from shapely.ops import transform +from layer_common import O,S,sample,feature,parts +from corridor_profiles import POLICY,VERSION,measure,calibrate,local_seed,missing_sections +from completion_profiles import families,slot,describe +from discovery_evidence import glyph_views +from coverage_evidence import CoverageViews as DiscoveryViews +from discovery_rules import uncovered +from interval_profiles import strip,resolve_pair +from gost_catalog import assess_dash +cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());original={f['id']:f for f in old['features']};current=dict(original) +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +poly=lambda f:shapely.force_2d(shape(f['geometry']));linear=lambda f:f['properties'].get('subtype')=='linear_marking' +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and not linear(f)]) +views=DiscoveryViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[] +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +def make(p,kind,ids,**kw):return feature(lift(p),'road_marking',subtype='linear_marking',line_kind=kind,method=VERSION,source_ids=ids,standard_compliance='not_assessed',**kw) +def allpaint():return shapely.union_all([poly(f)for f in current.values()if f['properties']['class']=='road_marking']) +def commit(kind,ids,new,ev,used,extra): + before=[current[i]for i in ids];a=shapely.union_all([poly(f)for f in before]);b=shapely.union_all([poly(f)for f in new]);novel=b.difference(a) + if not new or a.symmetric_difference(b).area<.015 or len({f['id']for f in new})!=len(new)or any(f['id']in current and f['id']not in ids for f in new):return False + if novel.intersection(protected).area>.005 or any(novel.intersection(poly(f)).area>.005 for i,f in current.items()if i not in ids and linear(f)):return False + for i in ids:current.pop(i) + for f in new:current[f['id']]=f + domain=shapely.union_all([a,b]);transactions.append(dict(kind=kind,source_ids=ids,output_ids=[f['id']for f in new],before=before,after=new,bounds_xy=domain.bounds,edit_domain=mapping(domain),evidence=ev,source_views=used,source_tiles=sorted(set(used[0])|set(used[1])),added_area_m2=novel.area,removed_area_m2=a.difference(b).area,**extra));print('EDIT',len(transactions),kind,len(ids),'->',len(new),flush=True);return True + +def removed_dark(a,b,local,readers,paint): + diff=a.difference(b.buffer(.025));o,u=local['origin'],local['axis'];n=np.array([-u[1],u[0]]) + if diff.area<.015:return [] + coords=shapely.get_coordinates(diff);tt=(coords-o)@u;ts=np.arange(tt.min(),tt.max()+.025,.025);ns=np.arange(-.7,.701,.025);xy=o+ts[:,None,None]*u+ns[None,:,None]*n;sel=shapely.contains_xy(diff,xy[:,:,0],xy[:,:,1]);ev=[] + if sel.sum()<5:return None + for vi,read in enumerate(readers): + con,valid=strip(o,u,ts,ns,read);values=con[sel];okay=valid[sel];threshold=max(15.,paint[vi]['paint']['contrast']*.35);e=dict(valid=float(okay.mean()),dark_fraction=float((values.45] + if len(candidates)!=1:continue + fid=candidates[0];a=poly(current[fid]);d=describe(a) + if d is None or a.symmetric_difference(p).area.75] + if len(matches)!=1:continue + iou=candidate.intersection(matches[0]).area/candidate.union(matches[0]).area + for section in missing_sections(candidate,allpaint()): + if not uncovered(section,allpaint()):continue + evidence,names=glyph_views(section,views,None,None) + if len(evidence)!=2 or any(e['valid']<.98 or e['support']<.85 for e in evidence):continue + f=make(section,'solid',[fid],observed_companion=True) + commit('observed-companion-divider',[],[f],dict(views=evidence,independent_polygon_iou=iou),[{names[0]:1},{names[1]:1}],dict(newly_captured_strokes=0,newly_captured_dividers=1,seed_id=fid)) + if si%25==0:print('COMPANION',si+1,len(seeds),flush=True) +result={**old,'features':list(current.values()),'corridor_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'corridor-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'corridor-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +counts=collections.Counter(r['kind']for r in transactions) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(counts),periodic_families=len(fs),profiled_axes=len(seeds),newly_captured_strokes=sum(r.get('newly_captured_strokes',0)for r in transactions),normalized_strokes=sum(r.get('normalized_strokes',0)for r in transactions),newly_captured_dividers=sum(r.get('newly_captured_dividers',0)for r in transactions),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'corridor-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/corridor_pass/render_corridor.py b/simulation/urban-plan-research/corridor_pass/render_corridor.py new file mode 100644 index 00000000..a0feb08b --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/render_corridor.py @@ -0,0 +1,41 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'corridor-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('corridor-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='corridor-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('corridor-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'corridor-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) +# Revisit every short-dash family shown in the prior delivery, using its stored +# bounds only for review framing; these bounds never enter the detector. +references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[] +for gi,rec in enumerate(references): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200 + uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]): + frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640') + fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only')) +(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2)) diff --git a/simulation/urban-plan-research/corridor_pass/render_coverage.py b/simulation/urban-plan-research/corridor_pass/render_coverage.py new file mode 100644 index 00000000..292fc8da --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/render_coverage.py @@ -0,0 +1,43 @@ +from pathlib import Path +import json,time,math,gc,hashlib,copy +import numpy as np,cv2,torch +from plyfile import PlyData +from PIL import Image +from gsplat import rasterization +from mapping import camera,digest +from ortho_terrain import sample +from coordinate_cache import transformed +from coverage_plan import plan_centers,POLICY +from fit_scene import project,world as unproject_xy +from layer_common import O,S +start=time.monotonic();folder=O/'coverage';folder.mkdir(exist_ok=True);census=json.loads((O/'corridor-census.json').read_text());plan=plan_centers(census['records']);inputs=dict(census_sha256=digest(O/'corridor-census.json'),policy=POLICY,source_code_sha256=digest(__file__)) +request=json.loads((S/'request.json').read_text());source=Path('/input')/request['source']['ply'];inputs['source_sha256']=request['source']['sha256'];inputs['terrain_sha256']=digest(Path('/ortho/terrain-reference.npz')) +old=folder/'manifest.json' +if old.exists(): + m=json.loads(old.read_text());assert m['inputs']==inputs,'Coverage cache signature changed';assert all(digest(folder/p)==h for p,h in m['sha256'].items());print('VERIFIED COVERAGE CACHE',len(m['tiles']));raise SystemExit(0) +if not plan: + old.write_text(json.dumps(dict(inputs=inputs,tiles=[],sha256={},seconds=time.monotonic()-start)));print('NO COVERAGE GAPS');raise SystemExit(0) +assert digest(source)==request['source']['sha256'];T=np.array(request['source']['source_to_world']);assert np.allclose(T[:3,:3].T@T[:3,:3],np.eye(3));data=PlyData.read(source,mmap='r')['vertex'].data;xyz=transformed(data,T,str(source),proof_path=folder/'coordinate-cache-proof.json');field=dict(np.load('/ortho/terrain-reference.npz'));relative=np.empty(len(data),np.float32) +for begin in range(0,len(data),250000): + q=xyz[begin:begin+250000];relative[begin:begin+len(q)]=q[:,2]-sample(field,q[:,:2]) +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in tiles]);geoms={t['id']:dict(np.load(S/t['id']/'top.geometry.npz'))for t in tiles};records=[];hashes={} +for i,entry in enumerate(plan): + center=np.array(entry['center']);name='coverage-%03d'%i;dest=folder/name;dest.mkdir(exist_ok=True);near=tiles[int(np.argmin(np.linalg.norm(centers-center,axis=1)))];job=json.loads((S/near['id']/'job.json').read_text());spec=copy.deepcopy(next(v for v in job['views']if v['id']=='top'));delta=center-np.array(spec['eye'][:2]);spec['eye'][:2]=center.tolist();spec['target'][:2]=(np.array(spec['target'][:2])+delta).tolist();spec['size']=[4096,4096];spec['width_m']=60;lo,hi=center-30,center+30 + mask=(abs(xyz[:,:2]-center).max(1)<=40)&(relative>=POLICY['lower_height_m'])&(relative<=POLICY['ground_height_m']);d=data[mask].copy();del mask + if not len(d):continue + def tensor(names):return torch.tensor(np.column_stack([d[n]for n in names]),device='cuda',dtype=torch.float32) + means=tensor(['x','y','z']);quats=tensor([f'rot_{k}'for k in range(4)]);scales=tensor([f'scale_{k}'for k in range(3)]).exp();opacity=tensor(['opacity']).squeeze(-1).sigmoid();dc=tensor([f'f_dc_{k}'for k in range(3)])[:,None,:];rest=sorted([n for n in d.dtype.names if n.startswith('f_rest_')],key=lambda n:int(n.split('_')[-1]));sh=torch.cat([dc,tensor(rest).reshape(len(d),3,-1).transpose(1,2)],dim=1)if rest else dc;degree=int(math.sqrt(sh.shape[1]))-1;view,k=camera(spec) + with torch.inference_mode():rgbd,alpha,_=rasterization(means,quats,scales,opacity,sh,torch.tensor(view@T,device='cuda',dtype=torch.float32)[None],torch.tensor(k,device='cuda')[None],4096,4096,sh_degree=degree,camera_model='ortho',render_mode='RGB+ED',packed=True) + v=rgbd[0].cpu().numpy();a=alpha[0,:,:,0].cpu().numpy();v[:,:,:3]+=1-a[:,:,None];Image.fromarray(np.uint8(np.clip(v[:,:,:3],0,1)*255)).save(dest/'ground.png');ak=k.copy();ak[:2,:]*=1200/4096;g=dict(depth=cv2.resize(v[:,:,3],(1200,1200),interpolation=cv2.INTER_AREA),alpha=cv2.resize(a,(1200,1200),interpolation=cv2.INTER_AREA),view=view,intrinsics=ak);np.savez_compressed(dest/'top.geometry.npz',**g) + # Carry the already computed vehicle exclusion conservatively from every + # covering old view. Unknown source coverage stays blocked, never clear. + yy,xx=np.mgrid[:1200,:1200];points=unproject_xy(np.c_[xx.ravel(),yy.ravel()],g);vehicle=np.zeros(len(points),np.float32);covered=np.zeros(len(points),bool) + for ti,t in enumerate(tiles): + if abs(centers[ti]-center).max()>65:continue + uv=project(points,geoms[t['id']]).astype('float32');valid=(uv.min(1)>=0)&(uv.max(1)<1199) + if not valid.any():continue + oldveh=np.load(Path('/ortho/evidence')/(t['id']+'.normal.npz'))['vehicle'].astype('float32');idx=np.flatnonzero(valid);q=uv[idx];vv=np.concatenate([cv2.remap(oldveh,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).ravel()for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]);vehicle[idx]=np.maximum(vehicle[idx],vv);covered[idx]=True + vehicle[~covered]=1.;np.savez_compressed(dest/'vehicle.npz',vehicle=vehicle.reshape(1200,1200).astype('float16'));(dest/'camera.json').write_text(json.dumps(spec));records.append(dict(id=name,bounds_xy=[lo.tolist(),hi.tolist()],status='surveyed',target_count=entry['target_count'],splats=len(d),vehicle_mask='maximum of existing overlapping vehicle probabilities; unknown blocked')) + for p in dest.iterdir():hashes[str(p.relative_to(folder))]=digest(p) + print('COVERAGE RENDER',i+1,len(plan),len(d),flush=True);del d,means,quats,scales,opacity,dc,sh,rgbd,alpha,v,a;gc.collect();torch.cuda.empty_cache() +old.write_text(json.dumps(dict(inputs=inputs,tiles=records,sha256=hashes,seconds=time.monotonic()-start,physical_scans_added=0,manual_regions=[],point_cloud_input=False),indent=2));print('COVERAGE COMPLETE',len(records),time.monotonic()-start,flush=True) diff --git a/simulation/urban-plan-research/corridor_pass/row_evidence.py b/simulation/urban-plan-research/corridor_pass/row_evidence.py new file mode 100644 index 00000000..4e1dfc88 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/row_evidence.py @@ -0,0 +1,57 @@ +"""Geometry-only ownership for two continuous Gaussian evidence mosaics.""" +from pathlib import Path +from functools import lru_cache +import numpy as np,cv2,shapely +from PIL import Image +from fit_scene import project +from layer_common import S,sample +from row_profiles import POLICY + +def choose_owners(distances,coverage): + # Stable order is geometry then tile index, never paint intensity/confidence. + if distances.shape[1]==0:return np.full((len(distances),2),-1,dtype=int) + order=np.argsort(np.where(coverage,distances,np.inf),axis=1,kind='stable')[:,:2] + if order.shape[1]<2:order=np.pad(order,((0,0),(0,2-order.shape[1])),constant_values=-1) + for j in range(2): + okay=(order[:,j]>=0)&coverage[np.arange(len(order)),np.maximum(order[:,j],0)] + order[~okay,j]=-1 + return order +class GaussianViews: + def __init__(self,tiles,labels,low,high,protected): + self.tiles=tiles;self.labels=labels;self.low=low;self.high=high;self.protected=protected + self.centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in tiles]) + @lru_cache(maxsize=90) + def geometry(self,name):return dict(np.load(S/name/'top.geometry.npz')) + @lru_cache(maxsize=4) + def inputs(self,name): + rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB')) + with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle'].astype('float32') + return rgb,vehicle + def readers(self,origin,axis): + o=np.asarray(origin);u=np.asarray(axis);n=np.array([-u[1],u[0]]);used=[{},{}];cache={} + def ownership(points): + ts,inverse=np.unique(np.round((points-o)@u,6),return_inverse=True) + key=ts.tobytes() + if key not in cache: + centers=o+ts[:,None]*u;distance=np.linalg.norm(centers[:,None,:]-self.centers[None,:,:],axis=2);coverage=np.zeros(distance.shape,bool) + for i,tile in enumerate(self.tiles): + # Require the whole transverse evidence strip, not only its + # center, to fit inside each selected image footprint. + a=project(centers-POLICY['coverage_half_width_m']*n,self.geometry(tile['id']));b=project(centers+POLICY['coverage_half_width_m']*n,self.geometry(tile['id'])) + uv=np.concatenate([a,b],axis=1);m=POLICY['coverage_margin_px'];coverage[:,i]=(uv.min(1)>=m)&(uv.max(1)<1200-m) + cache[key]=choose_owners(distance,coverage) + return cache[key][inverse] + def reader(rank): + def read(points, detailed=False): + owners=ownership(points)[:,rank];gates={k:np.zeros(len(points),bool) for k in ['coverage','alpha','road','vehicle','protected']};colors=np.zeros((len(points),3),'uint8');allowed=np.zeros(len(points),bool) + for i in np.unique(owners): + if i<0:continue + select=np.flatnonzero(owners==i);xy=points[select];name=self.tiles[i]['id'];used[rank][name]=used[rank].get(name,0)+len(select);g=self.geometry(name);rgb,vehicle=self.inputs(name) + uv=project(xy,g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5 + def remap(a,q):return np.concatenate([cv2.remap(a,part[:,0,None],part[:,1,None],cv2.INTER_LINEAR).reshape(len(part),-1)for part in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]) + colors[select]=remap(rgb,native);veh=remap(vehicle,uv).ravel();alpha=remap(g['alpha'].astype('float32'),uv).ravel() + gates['coverage'][select]=True;gates['alpha'][select]=alpha>=.65;gates['road'][select]=sample(self.labels,xy,self.low,self.high)==1;gates['vehicle'][select]=veh<.20;gates['protected'][select]=~shapely.contains_xy(self.protected,xy[:,0],xy[:,1]) + allowed[select]=np.logical_and.reduce([v[select] for v in gates.values()]) + return (colors,allowed,gates) if detailed else (colors,allowed) + return read + return [reader(0),reader(1)],used diff --git a/simulation/urban-plan-research/corridor_pass/test_corridor.py b/simulation/urban-plan-research/corridor_pass/test_corridor.py new file mode 100644 index 00000000..6243e47d --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/test_corridor.py @@ -0,0 +1,42 @@ +import runpy,json,numpy as np +from corridor_profiles import measure,calibrate,local_seed,validated_slot +from completion_profiles import slot +prior=runpy.run_path('/candidate/test_completion.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +o=np.zeros(2);u=np.array([1.,0.]);seed=dict(origin=o,axis=u,period=1.,length=.8,width=.12,indices=[0,1,2,3,4],source_ids=list('abcde'),max_index=4) +def reader(offset=lambda x:0,missing=False,solid=False): + def read(xy): + x,y=xy.T;on=np.ones(len(x),bool)if solid else abs(x-np.round(x))<.25;sig=140*on*np.exp(-.5*((y-offset(x))/.045)**2);rgb=np.repeat(np.clip(65+sig,0,255)[:,None],3,1).astype('uint8');valid=np.ones(len(x),bool) + if missing:valid[abs(x-2)<.2]=False + return rgb,valid + return read +rd=reader();obs=[measure(seed,i,[rd,rd])for i in seed['indices']];checks['measure_length_from_paint']=all(r is not None and .40.04 for q in sections) +checks['fully_present_divider_has_no_new_section']=not missing_sections(p,p) +checks['short_hole_left_to_seam_stage']=not missing_sections(rectangle(o,u,0,10,.12),shapely.union_all([rectangle(o,u,0,4,.12),rectangle(o,u,5,10,.12)])) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/corridor-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed'] diff --git a/simulation/urban-plan-research/corridor_pass/validation.py b/simulation/urban-plan-research/corridor_pass/validation.py new file mode 100644 index 00000000..632ca6d1 --- /dev/null +++ b/simulation/urban-plan-research/corridor_pass/validation.py @@ -0,0 +1,75 @@ +"""Bounded job contract and phase identity; no model dependencies.""" +import hashlib +import json +import math +import re +from pathlib import PurePosixPath + + +def fingerprint(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest() + + +def filename(value): + if not isinstance(value, str) or not value or PurePosixPath(value).name != value or "\\" in value or value in {".", ".."}: + raise ValueError('Asset names must be relative filenames') + + +def validate_job(job): + if job.get('schema_version') != 'missioncore.urban-mapping-job/v1': + raise ValueError('Unsupported mapping job') + source = job['source'] + filename(source['ply']) + for name in ('sha256', 'world_sha256', 'collider_sha256'): + if not re.fullmatch('[0-9a-f]{64}', source[name]): + raise ValueError('A mapping job requires immutable source identities') + model = job['model'] + if model['repository'] != 'facebook/mask2former-swin-large-mapillary-vistas-semantic': + raise ValueError('This provider requires Mapillary Vistas labels') + for name, sha in model['files'].items(): + filename(name) + if not re.fullmatch('[0-9a-f]{64}', sha): + raise ValueError('Invalid model asset identity') + if not {'config.json', 'preprocessor_config.json', 'pytorch_model.bin'} <= model['files'].keys(): + raise ValueError('Incomplete model manifest') + def vector(value, length): + if not isinstance(value, list) or len(value) != length or any(type(v) not in (int, float) or not math.isfinite(v) for v in value): + raise ValueError('Invalid finite coordinate vector') + bounds = job['bounds_xy'] + if len(bounds) != 2: + raise ValueError('Invalid atlas bounds') + for point in bounds: + vector(point, 2) + cell = job.get('cell_m', .1) + if not .02 <= cell <= 1 or any(b <= a for a, b in zip(*bounds)): + raise ValueError('Invalid atlas extent or cell size') + if math.prod(math.ceil((b-a)/cell) for a, b in zip(*bounds)) > 1_000_000: + raise ValueError('Split the scene into bounded tiles (maximum 1 million cells)') + if not 0 <= job.get('halo_m', 15) <= 50 or not 0 <= job.get('min_confidence', .65) <= 1: + raise ValueError('Invalid mapping thresholds') + views = job['views'] + if not 2 <= len(views) <= 32 or sum(v.get('projection', 'pinhole') == 'ortho' for v in views) != 1: + raise ValueError('Use one orthographic reference and 1–31 perspective views') + identifiers = set() + for v in views: + if not re.fullmatch('[a-zA-Z0-9_-]{1,64}', v['id']) or v['id'] in identifiers: + raise ValueError('View identifiers must be unique safe names') + identifiers.add(v['id']) + if len(v['size']) != 2 or any(type(n) is not int or not 64 <= n <= 2048 for n in v['size']): + raise ValueError('Unsupported render dimensions') + for name in ('eye', 'target'): + vector(v[name], 3) + vector(v.get('up', [0, 0, 1]), 3) + projection = v.get('projection', 'pinhole') + if projection == 'ortho': + if not 0 < v['width_m'] <= 200: + raise ValueError('Invalid orthographic width') + elif projection != 'pinhole' or not 10 <= v['fov_degrees'] <= 130: + raise ValueError('Invalid perspective camera') + if type(job.get('min_views', 1)) is not int or not 1 <= job.get('min_views', 1) < len(views): + raise ValueError('Invalid observation quorum') + return job + + +def phase_inputs(job, spec): + return fingerprint({'source': job['source'], 'bounds': job['bounds_xy'], 'halo': job.get('halo_m', 15), 'view': spec}) diff --git a/simulation/urban-plan-research/coverage_pass/README.md b/simulation/urban-plan-research/coverage_pass/README.md new file mode 100644 index 00000000..9a587017 --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/README.md @@ -0,0 +1,34 @@ +# Whole-scene coverage audit and repair + +This pass consumes the accepted Gaussian-derived map and calibrated Gaussian +render/depth evidence. It accepts no per-location coordinate edits, point-cloud +inputs, collider evidence, or manual processing regions. + +- `audit_scene.py` inventories every surveyed tile, every pedestrian interior + ring and every marking predominantly inside a pedestrian polygon. +- `refine_coverage.py` tests small enclosed holes against a robust local ground + plane. Partial observation can be interpolated only with sufficient measured + planar support; raised objects, vegetation, road interiors, large holes and + unsupported gaps remain. The outer boundary and retained rings are unchanged. +- Linear road-marking fragments on the pedestrian side of the curb are rejected + by a joint spatial rule. Paint inside a pedestrian zone away from the curb is + not rejected by class alone. Bikes and crosswalks do not use this rejection. +- `refine_patterns.py` searches overlapping metric windows over every Gaussian + tile for finite zigzags, with OpenCV morphology, Hough segments, skeletonization and periodic + least-squares fitting. Touching symbols do not hide all linked segments. Every accepted leg still needs image support. +- `refine_crossings.py` searches weak paint only at internal gaps bounded by observed zebra stripes. + Edge extrapolation is disabled until crossing extent is independently known. + A candidate must end at the shared zebra limits: continued bright structure + outside either end rejects rails and through-going lines. It does not add entirely unobserved bars or extend indefinitely beyond the + available evidence. Measured spacing is a prior, not a GOST compliance claim. + +Every operation has a before/after transaction, source evidence and an audit. +Full-scene tile sheets and all substantial changed areas are rendered for review. +The same frozen bundle must run on all qualification scenes before publication. +Publishing remains the existing qualified-map workflow with backup and readback; +this is an offline research pass, not a new automatic product job. + +The outputs are semantic observations. A filled pedestrian polygon is not a +physical collision mesh, a verified traversability permission or geodetic truth. +Remaining gaps are explicitly retained in the audit; complete recall is not +claimed without a labeled evaluation set. diff --git a/simulation/urban-plan-research/coverage_pass/audit_coverage.py b/simulation/urban-plan-research/coverage_pass/audit_coverage.py new file mode 100644 index 00000000..b3fca824 --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/audit_coverage.py @@ -0,0 +1,24 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape,Polygon,LineString +from coverage_rules import VERSION,POLICY,fill_hole,reject_linear +from coverage_crossings import accept_crossing +from coverage_patterns import accept_pattern as accept_zigzag +O=Path('/out');sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest();base=Path('/fullplan/full-map.json');old=json.loads(base.read_text());new=json.loads((O/'full-map.json').read_text());rows=json.loads((O/'coverage-rows.json').read_text());report=json.loads((O/'coverage-report.json').read_text());holes=json.loads((O/'holes.json').read_text());current={f['id']:f for f in old['features']};poly=lambda f:shapely.force_2d(shape(f['geometry'])) +checks=dict(replay=True,ground_evidence=True,preserved_outer_rings=True,only_admitted_holes_removed=True,paint_evidence=True,clean_shapes=True,no_foreign_paint_overlap=True) +for r in rows: + checks['replay']&=r['source_ids']==[f['id']for f in r['before']]and r['output_ids']==[f['id']for f in r['after']] + for f in r['before']:checks['replay']&=current.pop(f['id'],None)==f + if r['kind']=='ground-hole-repair': + a,b=r['before'][0],r['after'][0];chosen=[x for x in holes if x['id']==a['id']and x['accepted']];checks['ground_evidence']&=all(fill_hole(e)for e in chosen);checks['preserved_outer_rings']&=a['geometry']['coordinates'][0]==b['geometry']['coordinates'][0];keep=[a['geometry']['coordinates'][0]]+[ring for i,ring in enumerate(a['geometry']['coordinates'][1:])if i not in r['holes']];checks['only_admitted_holes_removed']&=keep==b['geometry']['coordinates']and set(r['holes'])=={x['hole']for x in chosen} + elif r['kind']=='off-road-paint-rejection':checks['paint_evidence']&=reject_linear(r['evidence'])and r['before'][0]['properties']['subtype']=='linear_marking' + elif r['kind']=='window-assembled-zigzag': + f=r['after'][0];p=f['properties'];q=poly(f);checks['paint_evidence']&=bool(accept_zigzag(r['evidence']['whole'],r['evidence']['legs'],r['fit']));checks['clean_shapes']&=q.symmetric_difference(LineString(p['vertices']).buffer(p['width_m']/2,cap_style=2,join_style=2)).area<1e-7 + elif r['kind']=='rhythm-crosswalk-recovery': + e=r['evidence'];checks['paint_evidence']&=accept_crossing(e);q=poly(r['after'][0]);checks['clean_shapes']&=abs(q.area-q.minimum_rotated_rectangle.area)<1e-6 + else:raise ValueError(r['kind']) + for f in r['after']: + if f['properties']['class']=='road_marking':checks['no_foreign_paint_overlap']&=poly(f).intersection(shapely.union_all([poly(v)for v in current.values()if v['properties']['class']=='road_marking'])).area<=.01 + current[f['id']]=f +features={f['id']:f for f in new['features']};checks['replay_matches_map']=current==features;checks['unique_ids']=len(features)==len(new['features']);checks['finite_valid_geometry']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']);checks['policy_pinned']=report['policy']==POLICY and report['policy_version']==new['coverage_refinement']==VERSION;checks['baseline_pinned']=sha(base)==report['baseline_sha256'];checks['prior_observation_review_preserved']=old.get('observation_review')==new.get('observation_review');checks['unrelated_features_unchanged']=all(features.get(f['id'])==f for f in old['features']if f['id']not in {k for r in rows for k in r['source_ids']});checks['holes_counted']=sum(x['accepted']for x in holes)==report['holes_filled'];checks['no_manual_rois']=report['manual_rois']==[] +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=sha(O/'full-map.json'),complete_recall_measured=False,metric_accuracy_measured=False);(O/'coverage-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/coverage_pass/audit_scene.py b/simulation/urban-plan-research/coverage_pass/audit_scene.py new file mode 100644 index 00000000..0006d107 --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/audit_scene.py @@ -0,0 +1,64 @@ +"""Exhaustive tile review and geometry diagnostics; no automatic edits.""" +from pathlib import Path +import json,hashlib,os,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,Polygon,box +from PIL import Image,ImageDraw,ImageFont +from fit_scene import project +from layer_common import sample +from search_views import SearchViews +from component_surface import planar_vehicle_clearance +cv2.setNumThreads(3) +O=Path('/out');S=Path('/survey');D=json.loads(Path('/fullplan/full-map.json').read_text());features=D['features'];poly=lambda f:shapely.force_2d(shape(f['geometry'])) +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None) +walk=shapely.union_all([poly(f)for f in features if f['properties']['class']=='pedestrian_area']);records=[];holes=[];intrusions=[] +font=ImageFont.truetype('/candidate/review-font.ttf',17) +colors={'road_boundary':(236,124,25),'pedestrian_boundary':(18,165,92),'building_facade':(0,151,224),'road_marking':(241,195,0)} +def paint(im,g,fs): + rgba=im.convert('RGBA');layer=Image.new('RGBA',im.size);d=ImageDraw.Draw(layer);factor=im.width/1200 + for f in fs: + if f['properties']['class']!='pedestrian_area':continue + for i,ring in enumerate(f['geometry']['coordinates']):d.polygon([tuple(q)for q in project(ring,g)*factor],fill=(25,193,120,58)if i==0 else(0,0,0,0)) + rgba=Image.alpha_composite(rgba,layer);d=ImageDraw.Draw(rgba) + for f in fs: + color=colors.get(f['properties']['class']) + if color is None:continue + rings=f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']] + for ring in rings:d.line([tuple(q)for q in project(ring,g)*factor],fill=color,width=max(2,int(factor*1.5))) + return rgba.convert('RGB') +def grid_points(p,step=.12): + x,y=np.meshgrid(np.arange(p.bounds[0]+step/2,p.bounds[2],step),np.arange(p.bounds[1]+step/2,p.bounds[3],step));xy=np.c_[x.ravel(),y.ravel()];return xy[shapely.contains_xy(p,xy[:,0],xy[:,1])] +for f in features: + p=poly(f);props=f['properties'] + if props['class']=='pedestrian_area': + for hi,ring in enumerate(p.interiors): + h=Polygon(ring);xy=grid_points(h,.15);rec=dict(id=f['id'],hole=hi,area_m2=h.area,centroid=list(h.centroid.coords)[0],bounds=h.bounds,vertices=len(ring.coords)) + if .15<=h.area<=30 and len(xy): + rec['ground_agreement_fraction']=float(planar_vehicle_clearance(xy,views).mean());lab=sample(labels,xy,low,high);rec['labels']={str(k):float((lab==k).mean())for k in [0,1,2]} + holes.append(rec) + if props['class']=='road_marking': + fraction=p.intersection(walk).area/max(p.area,1e-9) + if fraction>.25:intrusions.append(dict(id=f['id'],subtype=props.get('subtype'),pedestrian_fraction=fraction,area_m2=p.area,bounds=p.bounds,centroid=list(p.centroid.coords)[0],method=props.get('method'))) +for ti,t in enumerate(tiles): + name=t['id'];g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);domain=box(*t['bounds_xy'][0],*t['bounds_xy'][1]);fs=[f for f in features if poly(f).intersects(domain)];overlay=paint(raw,g,fs) + row=Image.new('RGB',(1000,550),'white');draw=ImageDraw.Draw(row) + for col,im in enumerate([raw,overlay]): + row.paste(im.resize((500,500),Image.Resampling.LANCZOS),(500*col,50));draw.text((500*col+8,7),str(ti+1)+' '+name+' '+('ГАУССЫ'if col==0 else'ВСЕ СЛОИ'),font=font,fill='black') + row.save(O/('walk-%03d.jpg'%ti),quality=94);records.append(dict(index=ti,tile=name,file='walk-%03d.jpg'%ti,features=len(fs),bounds=t['bounds_xy'])) + print('TILE',ti,name,flush=True) +for start in range(0,len(records),8): + group=records[start:start+8];sheet=Image.new('RGB',(2000,550*((len(group)+1)//2)),'white') + for j,rec in enumerate(group):sheet.paste(Image.open(O/rec['file']),((j%2)*1000,(j//2)*550)) + sheet.save(O/('walk-sheet-%02d.jpg'%(start//8)),quality=94) +issues=[dict(kind='hole',**x)for x in holes if x['area_m2']>=.15]+[dict(kind='intrusion',**x)for x in intrusions];panels=[] +for i,item in enumerate(issues): + center=np.array(item['centroid']);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);overlay=paint(raw,g,features);lo=np.array(item['bounds'][:2])-2.;hi=np.array(item['bounds'][2:])+2.;uv=project([[lo[0],lo[1]],[hi[0],hi[1]]],g)*raw.width/1200;mid=uv.mean(0);extent=max(abs(uv[1]-uv[0]));bbox=tuple(np.r_[mid-extent/2,mid+extent/2].astype(int));row=Image.new('RGB',(800,450),'white');d=ImageDraw.Draw(row) + for col,im in enumerate([raw,overlay]):row.paste(im.crop(bbox).resize((400,400),Image.Resampling.LANCZOS),(400*col,50)) + d.text((5,6),str(i)+' '+item['kind']+' '+name+' '+str(round(item['area_m2'],2))+' m2',font=font,fill='black');d.text((5,28),'ground '+str(round(item.get('ground_agreement_fraction',-1),2))+' ped '+str(round(item.get('pedestrian_fraction',-1),2)),font=font,fill='black');row.save(O/('issue-%03d.jpg'%i),quality=94);item.update(index=i,tile=name,file='issue-%03d.jpg'%i);panels.append(row) +for start in range(0,len(panels),8): + group=panels[start:start+8];sheet=Image.new('RGB',(1600,450*((len(group)+1)//2)),'white') + for j,row in enumerate(group):sheet.paste(row,((j%2)*800,(j//2)*450)) + sheet.save(O/('issue-sheet-%02d.jpg'%(start//8)),quality=94) +report=dict(scene=os.environ['SCENE'],tiles=len(tiles),tile_manifest=records,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),holes=holes,intrusions=intrusions,issues=issues,classes=dict(collections.Counter(f['properties']['class']for f in features)),manual_processing_rois=[]) +(O/'scene-audit.json').write_text(json.dumps(report,indent=2));print('SUMMARY',json.dumps(dict(tiles=len(tiles),holes=len(holes),issues=len(issues),intrusions=len(intrusions))),flush=True) diff --git a/simulation/urban-plan-research/coverage_pass/bundle.json b/simulation/urban-plan-research/coverage_pass/bundle.json new file mode 100644 index 00000000..3474225d --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/bundle.json @@ -0,0 +1,149 @@ +{ + "source_snapshot": "f0c3a26fe8db0f2c042b", + "files": { + "assembly_evidence.py": "assembly_pass/assembly_evidence.py", + "assembly_rules.py": "assembly_pass/assembly_rules.py", + "assembly_templates.py": "assembly_pass/assembly_templates.py", + "assembly_zigzag.py": "assembly_pass/assembly_zigzag.py", + "audit_assembly.py": "assembly_pass/audit_assembly.py", + "audit_assembly_joins.py": "assembly_pass/audit_assembly_joins.py", + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_catalog.py": "catalog_pass/audit_catalog.py", + "audit_completion.py": "completion_pass/audit_completion.py", + "audit_components.py": "component_pass/audit_components.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_corridor.py": "corridor_pass/audit_corridor.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_search.py": "search_pass/audit_search.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_symbols.py": "symbol_pass/audit_symbols.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "bicycle_artwork.py": "catalog_pass/bicycle_artwork.py", + "catalog_context.py": "catalog_pass/catalog_context.py", + "catalog_dependencies.py": "catalog_pass/catalog_dependencies.py", + "catalog_dependency_pins.py": "catalog_pass/catalog_dependency_pins.py", + "catalog_evidence.py": "symbol_pass/catalog_evidence.py", + "catalog_rules.py": "catalog_pass/catalog_rules.py", + "catalog_templates.py": "catalog_pass/catalog_templates.py", + "catalog_zigzag.py": "catalog_pass/catalog_zigzag.py", + "completion_profiles.py": "completion_pass/completion_profiles.py", + "component_arrows.py": "component_pass/component_arrows.py", + "component_bicycle.py": "component_pass/component_bicycle.py", + "component_conflicts.py": "component_pass/component_conflicts.py", + "component_evidence.py": "component_pass/component_evidence.py", + "component_mosaics.py": "component_pass/component_mosaics.py", + "component_rules.py": "component_pass/component_rules.py", + "component_surface.py": "component_pass/component_surface.py", + "component_targets.py": "component_pass/component_targets.py", + "component_zigzag_rules.py": "component_pass/component_zigzag_rules.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "coordinate_cache.py": "orthophoto/coordinate_cache.py", + "corridor_profiles.py": "search_pass/corridor_profiles.py", + "coverage_evidence.py": "coverage_pass/coverage_evidence.py", + "coverage_plan.py": "corridor_pass/coverage_plan.py", + "diagnose_assembly.py": "assembly_pass/diagnose_assembly.py", + "diagnose_components.py": "component_pass/diagnose_components.py", + "diagnose_corridor.py": "corridor_pass/diagnose_corridor.py", + "diagnose_coverage.py": "corridor_pass/diagnose_coverage.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_assembly.py": "assembly_pass/extract_assembly.py", + "extract_catalog.py": "catalog_pass/extract_catalog.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "extract_search.py": "search_pass/extract_search.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "inspect_bicycles.py": "catalog_pass/inspect_bicycles.py", + "inspect_catalog.py": "catalog_pass/inspect_catalog.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "join_assembly.py": "assembly_pass/join_assembly.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "mapping.py": "corridor_pass/mapping.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "ortho_terrain.py": "orthophoto/ortho_terrain.py", + "paint_channels.py": "component_pass/paint_channels.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "prepare_symbols.py": "symbol_pass/prepare_symbols.py", + "refine_assembly.py": "assembly_pass/refine_assembly.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_catalog.py": "catalog_pass/refine_catalog.py", + "refine_completion.py": "completion_pass/refine_completion.py", + "refine_components.py": "component_pass/refine_components.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_corridor.py": "corridor_pass/refine_corridor.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_search.py": "search_pass/refine_search.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_symbols.py": "symbol_pass/refine_symbols.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "refine_zigzags.py": "component_pass/refine_zigzags.py", + "render_assembly.py": "assembly_pass/render_assembly.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_catalog.py": "catalog_pass/render_catalog.py", + "render_completion.py": "completion_pass/render_completion.py", + "render_components.py": "component_pass/render_components.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_corridor.py": "corridor_pass/render_corridor.py", + "render_coverage.py": "corridor_pass/render_coverage.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_hypotheses.py": "component_pass/render_hypotheses.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "catalog_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_search.py": "search_pass/render_search.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_symbols.py": "symbol_pass/render_symbols.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "review_symbols.py": "symbol_pass/review_symbols.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "corridor_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "search_rules.py": "search_pass/search_rules.py", + "search_views.py": "search_pass/search_views.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "semantic_symbols.py": "symbol_pass/semantic_symbols.py", + "symbol_evidence.py": "symbol_pass/symbol_evidence.py", + "symbol_rules.py": "symbol_pass/symbol_rules.py", + "test_assembly.py": "assembly_pass/test_assembly.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_catalog.py": "catalog_pass/test_catalog.py", + "test_completion.py": "completion_pass/test_completion.py", + "test_components.py": "component_pass/test_components.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_corridor.py": "corridor_pass/test_corridor.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_search.py": "search_pass/test_search.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_symbols.py": "symbol_pass/test_symbols.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py", + "validation.py": "corridor_pass/validation.py", + "zigzag_evidence.py": "component_pass/zigzag_evidence.py", + "zigzag_mosaics.py": "component_pass/zigzag_mosaics.py", + "audit_coverage.py": "coverage_pass/audit_coverage.py", + "render_coverage_changes.py": "coverage_pass/render_coverage_changes.py", + "test_coverage.py": "coverage_pass/test_coverage.py", + "coverage_crossings.py": "coverage_pass/coverage_crossings.py", + "zigzag_segments.py": "coverage_pass/zigzag_segments.py", + "audit_scene.py": "coverage_pass/audit_scene.py", + "refine_coverage.py": "coverage_pass/refine_coverage.py", + "coverage_rules.py": "coverage_pass/coverage_rules.py", + "refine_patterns.py": "coverage_pass/refine_patterns.py", + "refine_crossings.py": "coverage_pass/refine_crossings.py", + "coverage_patterns.py": "coverage_pass/coverage_patterns.py", + "crossing_completion.py": "families_pass/crossing_completion.py", + "crosswalk_family.py": "full_plan/crosswalk_family.py" + } +} \ No newline at end of file diff --git a/simulation/urban-plan-research/coverage_pass/coverage_crossings.py b/simulation/urban-plan-research/coverage_pass/coverage_crossings.py new file mode 100644 index 00000000..512ebf5d --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/coverage_crossings.py @@ -0,0 +1,11 @@ +"""Recover bounded worn stripes; reject curbs, rails and through-going lines.""" +import numpy as np +CROSSING_POLICY=dict(max_pedestrian_fraction=.05,min_valid=.95,min_contrast=2.5,min_supported_columns=.45,max_added_slots_per_end=0,require_internal_anchors=True,max_end_supported_columns=.35,max_end_contrast_ratio=.30,end_context_m=1.5) +def stripe_contrast(gray): + delta=gray[1:4]-(gray[0]+gray[4])[None,:]/2 + return dict(contrast=float(np.median(delta)),supported_columns=float(((delta>2.5).mean(0)>=2/3).mean())) +def bounded_stripe(v): + ends=v.get('ends',[]) + return len(ends)==2 and all(e['valid']>=CROSSING_POLICY['min_valid'] and (e['supported_columns']<=CROSSING_POLICY['max_end_supported_columns'] or e['contrast']=CROSSING_POLICY['min_valid']and v['contrast']>=CROSSING_POLICY['min_contrast']and v['supported_columns']>=CROSSING_POLICY['min_supported_columns']and bounded_stripe(v)for v in e['views']) diff --git a/simulation/urban-plan-research/coverage_pass/coverage_evidence.py b/simulation/urban-plan-research/coverage_pass/coverage_evidence.py new file mode 100644 index 00000000..f337db6b --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/coverage_evidence.py @@ -0,0 +1,50 @@ +"""Calibrated Gaussian depth/RGB sampling; no cloud or collider dependency.""" +import numpy as np,cv2,shapely +from scipy.optimize import least_squares +from fit_scene import project +from component_surface import ground_geometry +from mapping import unproject +from layer_common import sample +from paint_channels import paint_mask + +def points(p,step=.10): + if p.is_empty:return np.empty((0,2)) + x,y=np.meshgrid(np.arange(p.bounds[0]+step/2,p.bounds[2],step),np.arange(p.bounds[1]+step/2,p.bounds[3],step));xy=np.c_[x.ravel(),y.ravel()];xy=xy[shapely.contains_xy(p,xy[:,0],xy[:,1])] + return xy if len(xy)>=4 else np.array([p.representative_point().coords[0]]) +def read(a,uv): + return np.concatenate([cv2.remap(a.astype('float32'),q[:,0,None],q[:,1,None],cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT).reshape(len(q),-1)for q in np.array_split(uv.astype('float32'),max(1,int(np.ceil(len(uv)/20000))))]) +def ground_samples(xy,views): + centers=np.array([np.mean(t['bounds_xy'],axis=0)for t in views.original]);distance=np.linalg.norm(xy[:,None,:]-centers[None,:,:],axis=2) + for i,t in enumerate(views.original): + uv=project(xy,views.geometry(t['id']));distance[(uv.min(1)<20)|(uv.max(1)>=1180),i]=np.inf + owner=np.argmin(distance,axis=1);z=np.full(len(xy),np.nan);valid=np.zeros(len(xy),bool);rgb=np.zeros((len(xy),3),'uint8') + for i in np.unique(owner): + ids=np.flatnonzero((owner==i)&np.isfinite(distance[:,i]));name=views.original[i]['id'] + if not len(ids):continue + g=ground_geometry(name);uv=project(xy[ids],g);depth=read(g['depth'],uv).ravel();alpha=read(g['alpha'],uv).ravel();z[ids]=unproject(uv,depth,g['view'],g['intrinsics'],'ortho')[:,2];valid[ids]=(alpha>=.90)&np.isfinite(depth) + im=views.inputs(name)[0];rgb[ids]=read(im,(uv+.5)*(im.shape[0]/1200)-.5).clip(0,255).astype('uint8') + return z,valid,rgb + +def hole_evidence(h,walk,views): + from coverage_rules import POLICY + xy=points(h,POLICY['sample_m']);ring=points(h.buffer(.8).difference(h.buffer(.15)).intersection(walk),.15) + z,valid,rgb=ground_samples(xy,views);rz,rv,_=ground_samples(ring,views);origin=np.array(h.centroid.coords[0]);e=dict(area_m2=h.area,span_m=max(h.bounds[2]-h.bounds[0],h.bounds[3]-h.bounds[1]),ring_samples=int(rv.sum()),ground_coverage=float(valid.mean()),plane_agreement=0.,plane_p95_m=999.,vegetation_fraction=1.,road_fraction=float(np.mean(sample(views.labels,xy,views.low,views.high)==1))) + if rv.sum()32)&(hsv[:,0]<95)&(hsv[:,1]>55)).mean());e['plane']=coef.tolist();return e + +def paint_support(p,views): + """Two closest complete source windows; white OR yellow, no semantic veto.""" + center=np.array(p.centroid.coords[0]);rank=sorted(views.tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));result=[] + xy=points(p,.04) + for t in rank: + name=t['id'];g=views.geometry(name);uv=project(xy,g) + if not ((uv.min(1)>=20)&(uv.max(1)<1180)).all():continue + im=views.inputs(name)[0];scale=im.shape[0]/1200;lo=np.floor(uv.min(0)*scale-100).astype(int).clip(0,im.shape[0]);hi=np.ceil(uv.max(0)*scale+100).astype(int).clip(0,im.shape[0]);crop=im[lo[1]:hi[1],lo[0]:hi[0]];cell=60/im.shape[0] + paint=paint_mask(crop,'white',cell)|paint_mask(crop,'yellow',cell);k=max(1,round(.06/cell));paint=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k*2+1,)*2));native=(uv+.5)*scale-.5-lo + support=read(paint,native).ravel()>.5;coverage=read(g['alpha'],uv).ravel()>=.85 + result.append(dict(tile=name,support=float(support.mean()),coverage=float(coverage.mean()))) + if len(result)==2:break + return result diff --git a/simulation/urban-plan-research/coverage_pass/coverage_patterns.py b/simulation/urban-plan-research/coverage_pass/coverage_patterns.py new file mode 100644 index 00000000..3293152a --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/coverage_patterns.py @@ -0,0 +1,11 @@ +from component_zigzag_rules import accept_zigzag +PATTERN_POLICY=dict(min_primary_recall=.70,min_additional_recall=.70,max_negative_paint=.12) +def accept_pattern(ev,legs,fit): + mode=accept_zigzag(ev,legs,fit) + if not mode:return None + # A path through a hatched box is not a standalone zigzag. Its other strokes + # must not be ignored just because every proposed leg happens to be painted. + for i,e in enumerate(ev): + if e['paint_coverage']==0:continue + if e['recall']PATTERN_POLICY['max_negative_paint']:return None + return mode diff --git a/simulation/urban-plan-research/coverage_pass/coverage_rules.py b/simulation/urban-plan-research/coverage_pass/coverage_rules.py new file mode 100644 index 00000000..63dfb988 --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/coverage_rules.py @@ -0,0 +1,15 @@ +"""Scene-independent coverage repair. Distinguish ground from paint/topology.""" +VERSION='observed-coverage-v1' +POLICY=dict(max_hole_area_m2=8.,max_hole_span_m=6.,sample_m=.10, + min_ground_coverage=.55,min_plane_agreement=.97,max_plane_error_m=.10, + max_plane_p95_m=.08,min_ring_samples=16,max_vegetation_fraction=.02, + max_road_fraction=.05,linear_pedestrian_fraction=.85, + max_artifact_paint_support=.55,curb_band_m=.35,min_curb_fraction=.90, + manual_rois=[],point_cloud_input=False) +def fill_hole(e): + return (0=POLICY['min_ring_samples'] and e['ground_coverage']>=POLICY['min_ground_coverage'] and + e['plane_agreement']/max(e['ground_coverage'],1e-9)>=POLICY['min_plane_agreement'] and e['plane_p95_m']<=POLICY['max_plane_p95_m'] and + e['vegetation_fraction']<=POLICY['max_vegetation_fraction'] and e['road_fraction']<=POLICY['max_road_fraction']) +def reject_linear(e): + return e['pedestrian_fraction']>=POLICY['linear_pedestrian_fraction'] and (e.get('curb_fraction',0)>=POLICY['min_curb_fraction'] or (bool(e['views']) and all(v['coverage']>=.95 and v['support']=.65)&(d<=1.7)] + if len(d)<2:continue + period=float(np.median(d));phase=float(np.median(centers-np.round((centers-centers[0])/period)*period));slots=np.round((centers-phase)/period).astype(int);errors=abs(centers-(phase+slots*period));width=float(np.clip(m['width'],.25,.8)) + if np.quantile(errors,.9)>.12 or width>=.8*period:continue + occupied=set(slots);candidates=[k for k in range(min(slots)+1,max(slots))if k not in occupied];family=shapely.union_all([o['p']for o in group]);rank=sorted(views.tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-m['origin'])) + for k in candidates: + c=phase+k*period;lo=m['left'][0]+m['left'][1]*c;hi=m['right'][0]+m['right'][1]*c + t=np.r_[np.linspace(lo+.15*(hi-lo),hi-.15*(hi-lo),64),lo-np.linspace(.25,CROSSING_POLICY['end_context_m'],6),hi+np.linspace(.25,CROSSING_POLICY['end_context_m'],6)];offsets=np.array([-.5*period,-.3*width,0.,.3*width,.5*period]);xy=m['origin']+t[None,:,None]*m['u']+(c+offsets)[:,None,None]*m['v'];flat=xy.reshape(-1,2);checks=[] + uvbox=np.array([[lo,c-width/2],[hi,c-width/2],[hi,c+width/2],[lo,c+width/2],[lo,c-width/2]]);p=Polygon(m['origin']+uvbox[:,0,None]*m['u']+uvbox[:,1,None]*m['v']);onroad=float((sample(labels,flat,low,high)==1).mean()) + for tile in rank: + name=tile['id'];g=views.geometry(name);uv=project(flat,g) + if not((uv.min(1)>=20)&(uv.max(1)<1180)).all():continue + im,vehicle=views.inputs(name);rgb=read(im,(uv+.5)*im.shape[0]/1200-.5).clip(0,255).astype('uint8').reshape(5,76,3);gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY).astype(float);contrast=stripe_contrast(gray[:,:64]);alpha=read(g['alpha'],uv).reshape(5,76);veh=read(vehicle,uv).reshape(5,76);valid=(alpha>.85)&(veh<.25);ends=[dict(**stripe_contrast(gray[:,i:i+6]),valid=float(valid[:,i:i+6].mean()))for i in [64,70]];checks.append(dict(tile=name,**contrast,valid=float(valid[:,:64].mean()),ends=ends)) + if len(checks)==2:break + pedestrian_fraction=p.intersection(walk).area/max(p.area,1e-9);accepted=accept_crossing(dict(internal=bool(min(slots).01] + if existing:rec['blocked']='existing-paint';continue + out=feature(lift(p),'road_marking',subtype='crosswalk',method=VERSION,source_ids=[o['f']['id']for o in group],source_tiles=[e['tile']for e in checks],source_tile=checks[0]['tile'],crosswalk_family=gi,observed_center=True,recovered_stripe=True,ends_source='robust-shared-family',shared_width_m=width,measured_period_m=period,standard_compliance='not_assessed',evidence_mode='weak-paint-at-measured-rhythm') + current[out['id']]=out;rec['accepted']=True;rows.append(dict(kind='rhythm-crosswalk-recovery',before=[],after=[out],source_ids=[],output_ids=[out['id']],bounds_xy=p.bounds,evidence=rec));print('STRIPE',gi,k,checks,flush=True) +doc['features']=list(current.values());(O/'full-map.json').write_text(json.dumps(doc,allow_nan=False));(O/'coverage-rows.json').write_text(json.dumps(rows));(O/'crossing-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));report=json.loads((O/'coverage-report.json').read_text());report['crossing_policy']=CROSSING_POLICY;report['crosswalk_stripes_added']=sum(r['accepted']for r in diagnostics);(O/'coverage-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/coverage_pass/refine_patterns.py b/simulation/urban-plan-research/coverage_pass/refine_patterns.py new file mode 100644 index 00000000..53889c8c --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/refine_patterns.py @@ -0,0 +1,83 @@ +"""Metric sliding windows prevent a long paint component hiding its zigzag. + +Uses the existing OpenCV/SciPy skeleton fitter, calibrated Gaussian views and +per-leg admission. Windows are exhaustive and independent of scene identity. +""" +from pathlib import Path +import json,os,time,hashlib +import cv2,numpy as np,shapely +from shapely.geometry import Polygon,LineString,Point,box,shape,mapping +from shapely.ops import transform +from fit_scene import world,project +from layer_common import O,S,sample,parts,feature +from search_views import SearchViews +from paint_channels import paint_mask +from zigzag_segments import segment_proposals +from catalog_zigzag import fit_zigzag +from coverage_patterns import accept_pattern as accept_zigzag +from zigzag_mosaics import mosaic_views +from assembly_zigzag import extend +from assembly_rules import extension_supported +from beta_profiles import describe +from coverage_rules import VERSION +cv2.setNumThreads(3);start=time.monotonic();doc=json.loads((O/'full-map.json').read_text());current={f['id']:f for f in doc['features']};rows=json.loads((O/'coverage-rows.json').read_text());diag=[];proposals=[] +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,labels,low,high,None);poly=lambda f:shapely.force_2d(shape(f['geometry'])) +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +def eligible(p): + if p.is_empty or p.geom_type!='Polygon' or p.area<.1:return False + L,W=sorted(cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2])[1],reverse=True) + return 3.85)).astype('uint8'),(size,size),interpolation=cv2.INTER_NEAREST)>0 + mask=paint_mask(rgb,'yellow',cell,allowed).astype('uint8') + for segfit in segment_proposals(mask,cell): + vertices=world((segfit['vertices']/cell+.5)*1200/size-.5,g);line=LineString(vertices);width=.10;f=dict(vertices=vertices.tolist(),legs=segfit['legs'],fit_residual_m=segfit['fit_residual_m'],proposal_recall=1.,width_m=width,polygon=line.buffer(width/2,cap_style=2,join_style=2),proposal_method='Hough-periodic-chain');proposals.append(dict(f,source_tile=name)) + kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7));closed=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,kernel) + # Connected components can contain both a symbol and a zigzag. Independent + # overlapping metric windows expose the interior regular portion. + cc,h=cv2.findContours(closed,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);n=0 + if h is not None: + for i,c in enumerate(cc): + if h[0,i,3]>=0 or cv2.contourArea(c)*cell*cell<.15:continue + holes=[];j=h[0,i,2] + while j>=0: + if cv2.contourArea(cc[j])*cell*cell>.002:holes.append(world((cc[j][:,0]+.5)*1200/size-.5,g)) + j=h[0,j,0] + p=shapely.make_valid(Polygon(world((c[:,0]+.5)*1200/size-.5,g),holes));regions=parts(p) + if p.area>.2: + a,b,cx,d=p.bounds + for x in np.arange(a,cx,6.): + for y in np.arange(b,d,6.):regions.extend(parts(p.intersection(box(x-.2,y-.2,x+12.,y+12.)))) + for region in regions: + if not eligible(region):continue + f=fit_zigzag(region) + if f is None:continue + proposals.append(dict(f,source_tile=name));n+=1 + print('PROPOSALS',name,n,flush=True) +seen=[] +print('TOTAL PROPOSALS',len(proposals),flush=True) +for pi,fit in enumerate(sorted(proposals,key=lambda f:(-f['legs'],f['fit_residual_m']))): + q=fit['polygon'];source=fit['source_tile'] + if any(q.difference(x.buffer(.08)).area/q.area<.02 and x.difference(q.buffer(.08)).area/x.area<.02 for x in seen):continue + seen.append(q) + def check_leg(p): + d=describe(p) + if d is None:return False,[],[] + ends=[Point(d['origin']+sign*d['length']/2*d['axis']).buffer(.20)for sign in [-1,1]];ev,names=mosaic_views(p,views,negative_context=shapely.union_all([q,p]+ends));return extension_supported(ev),ev,names + growth=extend(fit['vertices'],fit['width_m'],check_leg) + if growth['legs_added']:fit['vertices']=growth['vertices'];fit['legs']=len(growth['vertices'])-1;q=LineString(fit['vertices']).buffer(fit['width_m']/2,cap_style=2,join_style=2) + ev,names=mosaic_views(q,views);leg_evidence=[mosaic_views(LineString([a,b]).buffer(fit['width_m']/2,cap_style=2),views,negative_context=q)[0]for a,b in zip(fit['vertices'],fit['vertices'][1:])];mode=accept_zigzag(ev,leg_evidence,fit) + if len(diag)%20==0:print('EVALUATED',len(diag),'of',len(proposals),flush=True) + rec={k:v for k,v in fit.items()if k!='polygon'};rec.update(evidence=ev,leg_evidence=leg_evidence,mode=mode,accepted=False);diag.append(rec) + if not mode:continue + overlaps=[f for f in current.values()if f['properties']['class']=='road_marking'and poly(f).intersection(q).area>.005] + # Preserve unrelated paint. Only a covered fragment or a shorter same-pattern + # object can be atomically replaced; no location or ID list participates. + if any(f['properties'].get('subtype')not in ['zigzag','linear_marking'] or poly(f).difference(q.buffer(.12)).area/poly(f).area>.02 or poly(f).intersection(q).area/poly(f).area<.50 for f in overlaps):rec['blocked']='unrelated-paint';continue + if overlaps and q.area<1.15*sum(poly(f).area for f in overlaps):continue + out=feature(lift(q),'road_marking',subtype='zigzag',method=VERSION,source_tile=source,source_tiles=names,vertices=fit['vertices'],leg_count=fit['legs'],width_m=fit['width_m'],fit_residual_m=fit['fit_residual_m'],source_ids=[f['id']for f in overlaps],standard_compliance='not_assessed') + for f in overlaps:del current[f['id']] + current[out['id']]=out;rec['accepted']=True;rows.append(dict(kind='window-assembled-zigzag',source_ids=[f['id']for f in overlaps],output_ids=[out['id']],before=overlaps,after=[out],bounds_xy=q.bounds,evidence=dict(whole=ev,legs=leg_evidence),fit=rec));print('ADMIT',source,fit['legs'],flush=True) +doc['features']=list(current.values());(O/'full-map.json').write_text(json.dumps(doc,allow_nan=False));(O/'coverage-rows.json').write_text(json.dumps(rows));(O/'pattern-diagnostics.json').write_text(json.dumps(diag,indent=2));report=json.loads((O/'coverage-report.json').read_text());report.update(zigzag_candidates=len(proposals),zigzag_evaluated=len(diag),zigzags_added=sum(r['accepted']for r in diag),pattern_seconds=time.monotonic()-start);(O/'coverage-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/coverage_pass/render_coverage_changes.py b/simulation/urban-plan-research/coverage_pass/render_coverage_changes.py new file mode 100644 index 00000000..848471f9 --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/render_coverage_changes.py @@ -0,0 +1,41 @@ +from pathlib import Path +import json,numpy as np,shapely,cv2 +from shapely.geometry import shape,box +from PIL import Image,ImageDraw,ImageFont +from layer_common import O,S +from search_views import SearchViews +from fit_scene import project +cv2.setNumThreads(3);old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());rows=json.loads((O/'coverage-rows.json').read_text());holes=json.loads((O/'holes.json').read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];views=SearchViews(tiles,None,None,None,None);font=ImageFont.truetype('/candidate/review-font.ttf',21);poly=lambda f:shapely.force_2d(shape(f['geometry']));manifest=[] +def paint(raw,g,features): + im=raw.convert('RGBA');layer=Image.new('RGBA',im.size);d=ImageDraw.Draw(layer);factor=im.width/1200 + for f in features: + if f['properties']['class']!='pedestrian_area':continue + for i,r in enumerate(f['geometry']['coordinates']):d.polygon([tuple(x)for x in project(r,g)*factor],fill=(25,193,120,58)if i==0 else(0,0,0,0)) + im=Image.alpha_composite(im,layer).convert('RGB');d=ImageDraw.Draw(im) + for f in features: + if f['properties']['class']!='road_marking':continue + for r in f['geometry']['coordinates']:d.line([tuple(x)for x in project(r,g)*factor],fill='#f1c300',width=max(2,round(factor))) + return im +loaded={} +def images(name): + if name not in loaded: + g=views.geometry(name);raw=Image.fromarray(views.inputs(name)[0]);loaded.clear();loaded[name]=(g,raw,paint(raw,g,old['features']),paint(raw,g,new['features'])) + return loaded[name] +def frame(name,bounds,label,filename,size=500): + g,raw,before,after=images(name);x0,y0,x1,y1=bounds;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*raw.width/1200;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*2/60;extent=max(extent,raw.width*5/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));out=Image.new('RGB',(size*3,size+50),'white');d=ImageDraw.Draw(out) + for i,(im,title)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):out.paste(im.crop(bbox).resize((size,size),Image.Resampling.LANCZOS),(size*i,50));d.text((size*i+8,10),label+' · '+title,font=font,fill='black') + out.save(O/filename,quality=94);return out +# All scene tiles, not a small selected set. +for ti,t in enumerate(tiles): + g,raw,before,after=images(t['id']);out=Image.new('RGB',(1800,650),'white');d=ImageDraw.Draw(out) + for i,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):out.paste(im.resize((600,600),Image.Resampling.LANCZOS),(i*600,50));d.text((i*600+8,10),t['id']+' · '+label,font=font,fill='black') + out.save(O/('coverage-tile-%03d.jpg'%ti),quality=94) +# Every non-surface transaction and every repaired hole >=0.5m2. +issues=[dict(kind='hole',bounds_xy=h['bounds_xy'],id=h['id'],hole=h['hole'],area_m2=h['area_m2'])for h in holes if h['accepted']and h['area_m2']>=.5]+[dict(kind=r['kind'],bounds_xy=r['bounds_xy'],ids=r['output_ids']or r['source_ids'])for r in rows if r['kind']!='ground-hole-repair'] +for i,issue in enumerate(issues): + b=issue['bounds_xy'];center=np.array([(b[0]+b[2])/2,(b[1]+b[3])/2]);t=min(views.tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));fn='coverage-change-%03d.jpg'%i;frame(t['id'],b,str(i),fn);manifest.append(dict(**issue,index=i,file=fn,tile=t['id'])) +for start in range(0,len(manifest),4): + group=manifest[start:start+4];out=Image.new('RGB',(1500,550*len(group)),'white') + for j,r in enumerate(group):out.paste(Image.open(O/r['file']),(0,550*j)) + out.save(O/('coverage-proof-%03d.jpg'%(start//4)),quality=94) +(O/'coverage-visual-manifest.json').write_text(json.dumps(dict(tiles=[t['id']for t in tiles],changes=manifest),indent=2));print('RENDERED',len(tiles),'tiles',len(issues),'changes',flush=True) diff --git a/simulation/urban-plan-research/coverage_pass/test_coverage.py b/simulation/urban-plan-research/coverage_pass/test_coverage.py new file mode 100644 index 00000000..04addf10 --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/test_coverage.py @@ -0,0 +1,48 @@ +"""Synthetic counterexamples and all previously accepted component tests.""" +import json,runpy,numpy as np +from shapely.geometry import box,Point +import coverage_evidence as evidence +from coverage_rules import fill_hole,reject_linear +from unittest.mock import patch +from types import SimpleNamespace +prior=runpy.run_path('/candidate/test_components.py')['result'];checks={} +views=SimpleNamespace(labels=np.zeros((200,200),'uint8'),low=np.array([-10.,-10.]),high=np.array([10.,10.])) +h=box(-.5,-.5,.5,.5);walk=box(-4,-4,4,4).difference(h) +def fake_samples(xy,raised=False,missing=False,green=False): + inside=(abs(xy[:,0])<.5)&(abs(xy[:,1])<.5);z=.02*xy[:,0]-.01*xy[:,1]+(raised*inside*.5);valid=np.ones(len(xy),bool) + if missing:valid[inside&(xy[:,0]>.15)]=False + rgb=np.tile([100,140,70]if green else[130,130,130],(len(xy),1)).astype('uint8');return z,valid,rgb +for name,kwargs,expected in [('flat_paving',{},True),('raised_bench',dict(raised=True),False),('partially_missing_paving',dict(missing=True),True),('planar_vegetation',dict(green=True),False)]: + with patch.object(evidence,'ground_samples',lambda xy,v:fake_samples(xy,**kwargs)): + e=evidence.hole_evidence(h,walk,views);checks[name]=fill_hole(e)==expected +with patch.object(evidence,'ground_samples',lambda xy,v:(np.zeros(len(xy)),np.zeros(len(xy),bool),np.zeros((len(xy),3),'uint8'))):checks['unknown_ground_not_filled']=not fill_hole(evidence.hole_evidence(h,walk,views)) +base=dict(area_m2=1.,span_m=1.,ring_samples=50,ground_coverage=1.,plane_agreement=1.,plane_p95_m=.01,vegetation_fraction=0.,road_fraction=0.) +checks['large_interior_preserved']=not fill_hole({**base,'area_m2':30.}) +checks['road_inside_sidewalk_not_filled']=not fill_hole({**base,'road_fraction':.5}) +checks['poor_plane_not_filled']=not fill_hole({**base,'plane_p95_m':.4}) +checks['isolated_hole_without_ring_preserved']=not fill_hole({**base,'ring_samples':4}) +checks['curb_fragment_on_sidewalk_rejected']=reject_linear(dict(pedestrian_fraction=.95,curb_fraction=.96,views=[])) +checks['road_edge_line_retained']=not reject_linear(dict(pedestrian_fraction=.1,curb_fraction=1.,views=[])) +checks['painted_line_inside_sidewalk_retained']=not reject_linear(dict(pedestrian_fraction=1.,curb_fraction=.1,views=[dict(coverage=1.,support=1.)])) +checks['unobserved_line_not_rejected_on_color_alone']=not reject_linear(dict(pedestrian_fraction=1.,curb_fraction=.1,views=[dict(coverage=.1,support=0.)])) +from zigzag_segments import segment_proposals +from coverage_patterns import accept_pattern +import cv2 +mask=np.zeros((600,600),'uint8');verts=np.array([[60,180],[120,240],[180,180],[240,240],[300,180],[360,240]],'int32');cv2.polylines(mask,[verts],False,1,4);cv2.line(mask,(60,180),(60,100),1,4) +checks['touching_stopline_does_not_hide_zigzag']=any(f['legs']>=4 for f in segment_proposals(mask)) +rot=cv2.warpAffine(mask,cv2.getRotationMatrix2D((300,300),27,1),(600,600)) +checks['rotated_zigzag_proposals']=any(f['legs']>=3 for f in segment_proposals(rot)) +checks['blank_image_no_zigzag_proposals']=not segment_proposals(np.zeros_like(mask)) +e=dict(paint_coverage=1.,paint_valid=1.,support=1.,observed_support=1.,recall=.95,negative_paint=.01);fit=dict(legs=4,fit_residual_m=.01,proposal_recall=1.) +checks['observed_zigzag_accepted']=bool(accept_pattern([e,e],[[e,e]]*4,fit)) +checks['path_through_hatched_box_rejected']=not accept_pattern([{**e,'recall':.45,'negative_paint':.2}]*2,[[e,e]]*4,fit) +from coverage_crossings import stripe_contrast,accept_crossing +dark_ends=[dict(valid=1.,contrast=0.,supported_columns=0.)]*2 +im=np.full((5,64),100.);im[1:4]=105.;e=dict(internal=True,pedestrian_fraction=0.,views=[dict(valid=1.,ends=dark_ends,**stripe_contrast(im))]);checks['worn_wide_zebra_recovered']=accept_crossing(e) +im=np.full((5,64),100.);im[2]=160.;checks['bright_narrow_curb_not_zebra']=not accept_crossing(dict(internal=True,pedestrian_fraction=0.,views=[dict(valid=1.,ends=dark_ends,**stripe_contrast(im))])) +checks['crosswalk_extension_into_sidewalk_rejected']=not accept_crossing({**e,'pedestrian_fraction':.8}) +checks['second_view_contradiction_rejects_zebra']=not accept_crossing({**e,'views':e['views']+[dict(valid=1.,contrast=-2.,supported_columns=0.)]}) +checks['no_zebra_extrapolation_beyond_observed_anchors']=not accept_crossing({**e,'internal':False}) +checks['continued_rails_not_zebra']=not accept_crossing({**e,'views':[{**e['views'][0],'ends':[dict(valid=1.,contrast=12.,supported_columns=1.)]*2}]}) +checks['unknown_zebra_ends_not_completed']=not accept_crossing({**e,'views':[{**e['views'][0],'ends':[]}]}) +result=dict(passed=all(checks.values())and prior['passed'],checks={k:bool(v)for k,v in checks.items()},prior_checks=len(prior['checks'])+prior['prior_checks'],prior_passed=prior['passed']);open('/out/coverage-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/coverage_pass/zigzag_segments.py b/simulation/urban-plan-research/coverage_pass/zigzag_segments.py new file mode 100644 index 00000000..755bd55f --- /dev/null +++ b/simulation/urban-plan-research/coverage_pass/zigzag_segments.py @@ -0,0 +1,54 @@ +"""OpenCV Hough segments + periodic least-squares fitting for branched paint. + +A touching letter or stop-line must not invalidate an entire connected region. +These are proposals only; the existing per-leg Gaussian evidence gate decides. +""" +import numpy as np,cv2 +from shapely.geometry import LineString + +def segment_proposals(mask,cell=.025): + cv2.setRNGSeed(0) + raw=cv2.HoughLinesP(mask.astype('uint8'),1,np.pi/360,threshold=18,minLineLength=round(.8/cell),maxLineGap=round(.15/cell)) + if raw is None:return [] + raw=raw[:,0].reshape(-1,2,2)*cell;length=np.linalg.norm(raw[:,1]-raw[:,0],axis=1);raw=raw[(length>=.8)&(length<=5.7)] + merged=[] + for p in sorted(raw,key=lambda p:-np.linalg.norm(p[1]-p[0])): + u=(p[1]-p[0])/np.linalg.norm(p[1]-p[0]);found=False + for rec in merged: + v=rec['u'];o=rec['o'];n=np.array([-v[1],v[0]]);t=(p-o)@v + if abs(u@v)>np.cos(np.deg2rad(6)) and max(abs((p-o)@n))<.12 and t.min()rec['lo']-.2: + rec['lo']=min(rec['lo'],t.min());rec['hi']=max(rec['hi'],t.max());rec['offsets'].append(float(np.mean((p-o)@n)));found=True;break + if not found:merged.append(dict(u=u,o=p.mean(0),lo=-np.linalg.norm(p[1]-p[0])/2,hi=np.linalg.norm(p[1]-p[0])/2,offsets=[0.])) + seg=[] + for r in merged: + if not .830000:return + if len(ids)>=3: + q=np.array(vertices);idx=np.arange(len(q));X=np.c_[idx,(-1.)**idx,np.ones(len(q))];coef=np.linalg.lstsq(X,q,rcond=None)[0];fitted=X@coef;axis,amp=coef[:2];res=np.linalg.norm(fitted-q,axis=1).max() + if res>.16 or abs(axis@amp)/max(np.linalg.norm(axis)*np.linalg.norm(amp),1e-9)>.25:return + key=tuple(sorted(i for i,e in ids)) + if key not in seen: + seen.add(key);result.append(dict(vertices=fitted,fit_residual_m=float(res),legs=len(q)-1)) + if len(ids)>=16:return + i,end=ids[-1];p=np.array(vertices);prev=p[-1]-p[-2];L=np.linalg.norm(prev) + for j,k in adj[i,end]: + if any(j==idx for idx,e in ids):continue + nxt=seg[j,1-k];v=nxt-p[-1];ell=np.linalg.norm(v);angle=np.arctan2(np.cross(prev,v),prev@v) + if not .752: + prior=p[-2]-p[-3];turn=np.arctan2(np.cross(prior,prev),prior@prev) + if turn*angle>=0 or abs(abs(turn)-abs(angle))>np.deg2rad(15):continue + visit(ids+[(j,1-k)],vertices+[nxt]) + for i,p in enumerate(seg): + for e in [0,1]:visit([(i,e)],[p[1-e],p[e]]) + return result diff --git a/simulation/urban-plan-research/discovery_pass/README.rst b/simulation/urban-plan-research/discovery_pass/README.rst new file mode 100644 index 00000000..6c994309 --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/README.rst @@ -0,0 +1,64 @@ +Independent Gaussian paint discovery — offline research +====================================================== + +This bundle follows beta-pass-20261012. It consumes its accepted full-map, +calibrated Gaussian RGB ground renders, Gaussian-derived labels/height, +vehicle masks, cached marking semantics, and survey tile index. It does not +consume point clouds. All computation, tests and rendering run on Worker006. + +Stages +------ +extract_discovery: run the existing OpenCV top-hat/connected component/Hough +extractor over every surveyed tile at a common metric resolution. Components +and bounded morphological closing supply fragmented glyph hypotheses; original +paint geometry, including holes, is retained for fitting. Cached semantic scores +are proposal filters. No existing vector axis seeds this search. + +refine_discovery: use the existing robust row fitting and beta two-render +profiles to validate periodic rows. Whole glyphs use attributed templates and +two whole-object image footprints selected by geometry before RGB inspection. +Positive paint, negative space, observed recall and valid coverage are required. +The proposal fit tolerates incomplete/noisy contours (score >= .74, recall >= .75); +this alone never authorizes output. Both image footprints must separately pass +valid coverage >= .98, paint support >= .73, observed recall >= .78 and negative +paint fraction <= .23. Template branch/head/counter identity checks stay active. The tail requires +50% positive support to tolerate wear; head and side branch require 73%. +A pure turn needs a lateral head displacement relative to the independently +Huber-fitted paint tail, not relative to the optimized template angle. +A glyph also needs compatible nearby image strips and observed dark space beyond +its ends. End probes start .35 m outside the preset to allow bounded fit error; +a continuing lane stripe cannot be reclassified as an arrow. +An isolated stripe is explicitly unclassified without a measured periodic row. +Only non-overlapping missing objects are added. Every baseline object is retained. + +Render tiles are different views of one Gaussian reconstruction, not independent +physical scans. Outputs remain observation-only, unreviewed for routing, and +standard_compliance=not_assessed. GOST catalog associations are suggestions, not +legal tolerances or compliance certification. No new physical accuracy claim. + +Reproduction +------------ +Use bundle.json to resolve byte-identical canonical modules; qualification +operator/replay retains the bounded runner, registry and frozen source manifest. +Execution requires the pinned Docker image, private Gaussian inputs, and the +pinned external review font. No downloads or installs occur in the container. +Run test_discovery, extract_discovery, refine_discovery, audit_discovery, +render_discovery and render_plan, then verify inputs, receipts, maps and images. +The same source snapshot and POLICY are required on all three scenes. + +Attribution +----------- +Arrow artwork: MajorAlexey, 1.18 Russian road marking.svg, CC BY-SA 4.0. +Source: https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg +License: https://creativecommons.org/licenses/by-sa/4.0/ +Source SHA-256: b76f40ee8d1603ddfeb3cd430f397dcc509684f0a0aa38c61bbd8a2cba554ea8 +Adaptation: normalized polygon presets with parameterized length/width/stroke. +The letter A is an existing original parametric preset. Artwork derivatives +retain their CC BY-SA attribution and licensing obligations. + +Limits +------ +This stage does not change roads, facades, pedestrian areas or existing paint. +It does not infer a completely unobserved symbol or certify complete recall. +Curved rows, thin low-contrast paint, occlusions, template variants outside the +library and inadequate second-render coverage can still be missed. diff --git a/simulation/urban-plan-research/discovery_pass/audit_discovery.py b/simulation/urban-plan-research/discovery_pass/audit_discovery.py new file mode 100644 index 00000000..a8ed285b --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/audit_discovery.py @@ -0,0 +1,32 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +from discovery_rules import POLICY,VERSION,uncovered,glyph_pass +from beta_profiles import supported +old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/discovery-rows.json').read_text());current={f['id']:f for f in old['features']} +def poly(f):return shapely.force_2d(shape(f['geometry'])) +existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking']) +checks=dict(transaction_replay=True,only_paint_added=True,no_new_neighbor_overlap=True,evidence_passes=True,independent_image_proposals=True) +for r in rows: + checks['transaction_replay']&=not r['before']and not r['source_ids']and r['output_ids']==[f['id']for f in r['after']]and all(f['id']not in current for f in r['after']) + checks['independent_image_proposals']&=r['discovery_without_vector_seed'] + checks['only_paint_added']&=all(f['properties']['class']=='road_marking'and f['properties']['method']==VERSION for f in r['after']) + okay=len(set(r['source_tiles']))>=2;ev=r['evidence'] + if r['kind']=='glyph':okay&=len(ev)==2 and all(glyph_pass(e)and len(e.get('parts',[]))>=2 and len(e.get('ends',[]))==2 for e in ev)and r['template_fit_score']>=POLICY['symbol_proposal_score'] and r['fit_recall']>=POLICY['symbol_proposal_recall']and r['lane_context']['passed']and r['lane_context']['supporting_strips']>=2 + elif r['kind']=='observed-strip':okay&=len(ev['paint'])==2 and len(ev['ends'])==4 and all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']and e['contrast']>=22 for e in ev['paint'])and all(e.get('full_corridor')and supported(e,False)for e in ev['ends']) + elif r['kind']=='periodic-row': + okay&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint'])and len(ev['gaps'])==2*(len(ev['observations'])-1) + okay&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps']) + okay&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=.20 for e in ev['observations']) + else:okay=False + checks['evidence_passes']&=okay + for f in r['after']: + checks['no_new_neighbor_overlap']&=uncovered(poly(f),existing);existing=shapely.union_all([existing,poly(f)]);current[f['id']]=f +features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features']) +checks['all_baseline_objects_unchanged']=all(features.get(f['id'])==f for f in old['features']) +checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']) +checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes() +report=json.loads(Path('/out/discovery-report.json').read_text());checks['same_policy']=new['discovery_refinement']==VERSION and report['policy']==POLICY +checks['every_operation_counted']=report['changed_segments']==len(rows)and report['added_objects']==sum(len(r['after'])for r in rows) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False) +Path('/out/discovery-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/discovery_pass/bundle.json b/simulation/urban-plan-research/discovery_pass/bundle.json new file mode 100644 index 00000000..1c5d5602 --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/bundle.json @@ -0,0 +1,116 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_beta.py": "beta_pass/audit_beta.py", + "audit_consensus.py": "consensus_pass/audit_consensus.py", + "audit_discovery.py": "discovery_pass/audit_discovery.py", + "audit_norms.py": "norms_pass/audit_norms.py", + "audit_rows.py": "rows_pass/audit_rows.py", + "audit_sections.py": "sections_pass/audit_sections.py", + "audit_transitions.py": "transitions_pass/audit_transitions.py", + "beta_profiles.py": "beta_pass/beta_profiles.py", + "consensus_profiles.py": "consensus_pass/consensus_profiles.py", + "discovery_evidence.py": "discovery_pass/discovery_evidence.py", + "discovery_rules.py": "discovery_pass/discovery_rules.py", + "extract_discovery.py": "discovery_pass/extract_discovery.py", + "fit_scene.py": "full_plan/fit_scene.py", + "fragment_templates.py": "discovery_pass/fragment_templates.py", + "gost_catalog.py": "norms_pass/gost_catalog.py", + "image_profiles.py": "lines_pass/image_profiles.py", + "interval_profiles.py": "intervals_pass/interval_profiles.py", + "layer_common.py": "full_plan/layer_common.py", + "line_reconstruction.py": "intervals_pass/line_reconstruction.py", + "norm_profiles.py": "norms_pass/norm_profiles.py", + "paint_templates.py": "continuation_pass/paint_templates.py", + "refine_beta.py": "beta_pass/refine_beta.py", + "refine_consensus.py": "consensus_pass/refine_consensus.py", + "refine_discovery.py": "discovery_pass/refine_discovery.py", + "refine_norms.py": "norms_pass/refine_norms.py", + "refine_rows.py": "rows_pass/refine_rows.py", + "refine_sections.py": "sections_pass/refine_sections.py", + "refine_transitions.py": "transitions_pass/refine_transitions.py", + "render_beta.py": "beta_pass/render_beta.py", + "render_consensus.py": "consensus_pass/render_consensus.py", + "render_discovery.py": "discovery_pass/render_discovery.py", + "render_norms.py": "norms_pass/render_norms.py", + "render_plan.py": "continuation_pass/render_plan.py", + "render_rows.py": "rows_pass/render_rows.py", + "render_sections.py": "sections_pass/render_sections.py", + "render_transitions.py": "transitions_pass/render_transitions.py", + "road_glyph_presets.py": "continuation_pass/road_glyph_presets.py", + "row_evidence.py": "rows_pass/row_evidence.py", + "row_profiles.py": "rows_pass/row_profiles.py", + "section_profiles.py": "sections_pass/section_profiles.py", + "test_beta.py": "beta_pass/test_beta.py", + "test_consensus.py": "consensus_pass/test_consensus.py", + "test_discovery.py": "discovery_pass/test_discovery.py", + "test_intervals.py": "intervals_pass/test_intervals.py", + "test_lines.py": "lines_pass/test_lines.py", + "test_norms.py": "norms_pass/test_norms.py", + "test_rows.py": "rows_pass/test_rows.py", + "test_sections.py": "sections_pass/test_sections.py", + "test_transitions.py": "transitions_pass/test_transitions.py", + "transition_profiles.py": "transitions_pass/transition_profiles.py" + }, + "reference_qualification": "discovery-pass-20261012", + "source_snapshot": "91768632d85929db9c92", + "source_sha256": { + "audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f", + "audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2", + "audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974", + "audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d", + "audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01", + "audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7", + "audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a", + "beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e", + "consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091", + "discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb", + "discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491", + "extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7", + "gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537", + "image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8", + "interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738", + "norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7", + "paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6", + "refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831", + "refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36", + "refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b", + "refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5", + "refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8", + "refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3", + "refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b", + "render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c", + "render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682", + "render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20", + "render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e", + "render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c", + "render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d", + "road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322", + "row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c", + "row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df", + "section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de", + "test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b", + "test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7", + "test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538", + "test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12", + "test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a", + "test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f", + "test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449", + "test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f", + "test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438", + "transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/discovery_pass/discovery_evidence.py b/simulation/urban-plan-research/discovery_pass/discovery_evidence.py new file mode 100644 index 00000000..a80a9e01 --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/discovery_evidence.py @@ -0,0 +1,29 @@ +"""Whole-object footprints choose two render tiles before seeing their paint.""" +import numpy as np,cv2,shapely +from functools import lru_cache +from row_evidence import GaussianViews +from fit_scene import project +from layer_common import sample +from discovery_rules import glyph_score + +class DiscoveryViews(GaussianViews): + # Bounded decode cache for a whole-map search with overlapping render tiles. + @lru_cache(maxsize=12) + def inputs(self,name):return super().inputs(name) + +def glyph_views(p,views,kind,parameters): + lo=np.array(p.bounds[:2])-1.;hi=np.array(p.bounds[2:])+1.;cell=.04 + xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell) + x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()];corners=np.array([[lo[0],lo[1]],[lo[0],hi[1]],[hi[0],lo[1]],[hi[0],hi[1]]]);center=(lo+hi)/2 + eligible=[] + for i,t in enumerate(views.tiles): + uv=project(corners,views.geometry(t['id'])) + if uv.min()>=20 and uv.max()<1180:eligible.append((float(np.linalg.norm(center-views.centers[i])),i)) + if len(eligible)<2:return [],[] + ev=[];names=[] + for _,i in sorted(eligible)[:2]: + name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points,g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5 + def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))]) + colors=read(rgb,native).reshape(len(yy),len(xx),3);valid=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points,views.low,views.high)==1) + ev.append(glyph_score(colors,valid.reshape(len(yy),len(xx)),points,p,kind=kind,parameters=parameters));names.append(name) + return ev,names diff --git a/simulation/urban-plan-research/discovery_pass/discovery_rules.py b/simulation/urban-plan-research/discovery_pass/discovery_rules.py new file mode 100644 index 00000000..ea637001 --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/discovery_rules.py @@ -0,0 +1,69 @@ +"""Image proposals do not require an existing vector; admission remains measured.""" +import numpy as np, cv2, shapely +from shapely.geometry import Polygon, shape, mapping +from line_reconstruction import observation + +VERSION='image-discovery-v1' +POLICY=dict(proposal_image_size=2048,fragment_join_radii_m=[.12,.25],min_symbol_area_m2=.25,symbol_proposal_score=.74,symbol_proposal_recall=.75, + min_semantic_mean=.06,min_semantic_peak=.35,max_new_overlap_m2=.005, + duplicate_clearance_m=.10,min_symbol_valid=.98,min_symbol_paint_support=.73,min_tail_support=.50, + min_symbol_observed_recall=.78,max_symbol_negative_paint=.23, + min_solid_length_m=3.,min_solid_valid=.98,min_solid_bright=.93, + max_glyph_end_paint=.25,glyph_end_probe_start_m=.35,glyph_end_probe_stop_m=.85,glyph_context_angle_deg=15.,glyph_context_radius_m=10.,glyph_context_length_m=6.) + +def glyph_context(p,parameters,records): + u=np.array([np.cos(parameters[2]),np.sin(parameters[2])]);support=[] + for r in records: + if r['L']<3 or r['W']>.35:continue + distance=r['polygon'].distance(p) + if .3=np.cos(np.deg2rad(POLICY['glyph_context_angle_deg'])):support.append(r) + length=sum(r['L']for r in support) + return dict(passed=len(support)>=2 and length>=POLICY['glyph_context_length_m'],supporting_strips=len(support),supporting_length_m=float(length),source_tiles=sorted(set(r['source_tile']for r in support))) + +def eligible_symbol(p): + if p.is_empty or p.area1.2 and .0915)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36))) + target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w) + near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0 + wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0 + region=shapely.contains_xy(polygon.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(h,w) + negative=region&~wide + result=dict(valid=float(allowed[region].mean())if region.any()else 0., + support=float(near[target].mean())if target.any()else 0., + recall=float(wide[paint®ion&allowed].mean())if (paint®ion&allowed).any()else 0., + negative_paint=float(paint[negative&allowed].mean())if (negative&allowed).any()else 1.) + if kind is not None and parameters is not None: + px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w) + regions=[('head',t>L*.80),('tail',tW*.24)) + result['parts']=[] + for name,where in regions: + select=target&where + result['parts'].append(dict(part=name,valid=float(allowed[select].mean())if select.any()else 0.,support=float(near[select].mean())if select.any()else 0.)) + result['ends']=[] + for name,interior,exterior in [('tail',t-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t=POLICY['min_symbol_valid']and e['support']>=POLICY['min_symbol_paint_support']and e['recall']>=POLICY['min_symbol_observed_recall']and e['negative_paint']<=POLICY['max_symbol_negative_paint']and all(p['valid']>=POLICY['min_symbol_valid']and p['support']>=(POLICY['min_tail_support']if p['part']=='tail'else POLICY['min_symbol_paint_support'])for p in e.get('parts',[]))and all(p['valid']>=POLICY['min_symbol_valid']and p['paint_fraction']<=POLICY['max_glyph_end_paint']for p in e.get('ends',[])) diff --git a/simulation/urban-plan-research/discovery_pass/extract_discovery.py b/simulation/urban-plan-research/discovery_pass/extract_discovery.py new file mode 100644 index 00000000..a142d6a7 --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/extract_discovery.py @@ -0,0 +1,64 @@ +from pathlib import Path +import json,time,hashlib +import numpy as np,cv2,shapely +from PIL import Image +from shapely.geometry import Polygon,shape,mapping +from scipy.ndimage import distance_transform_edt +from layer_common import O,S,sample,parts +from fit_scene import world,project +from line_reconstruction import extract,dedup +from discovery_rules import POLICY,eligible_symbol,pack +cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text()) +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds'] +inside=distance_transform_edt(labels==1)*.1 +protected=[shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'] +protected_union=shapely.union_all(protected);symbols=shapely.union_all([shapely.force_2d(shape(f['geometry'])).convex_hull for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')not in ['linear_marking','crosswalk']]) +lines=[];glyphs=[];reports=[] +for tile in tiles: + name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));size=POLICY['proposal_image_size'];mpp=60/size + rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB').resize((size,size),Image.Resampling.LANCZOS)) + with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=cv2.resize(z['vehicle'].astype('float32'),(size,size)) + with np.load(Path('/evidence_plan/evidence')/(name+'.npz'))as z:semantic=cv2.resize(z['road marking'].astype('float32'),(size,size)) + def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g) + yy,xx=np.mgrid[:size,:size];points=xy(np.c_[xx.ravel(),yy.ravel()]);allowed=(sample(inside,points,low,high)>.25).reshape(size,size)&(vehicle<.2)&(cv2.resize(g['alpha'].astype('float32'),(size,size))>.65) + mask=np.zeros((size,size),np.uint8);domain=shapely.box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]) + for p in protected: + if p.intersects(domain): + for q in parts(p.buffer(.10)):cv2.fillPoly(mask,[np.rint((project(q.exterior.coords,g)+.5)*size/1200-.5).astype('int32')],1) + observations,rec=extract(rgb,allowed&(mask==0),xy,name,mpp);lines.extend(observations) + gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2) + ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel) + binary=((ridge>12)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))&allowed).astype('uint8') + cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[] + if hier is not None: + for i,c in enumerate(cc): + if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.018:continue + holes=[];j=hier[0,i,2] + while j>=0: + if cv2.contourArea(cc[j])*mpp*mpp>.018:holes.append(xy(cc[j][:,0])) + j=hier[0,j,0] + p=shapely.make_valid(Polygon(xy(c[:,0]),holes));components.extend(parts(p)) + union=shapely.union_all(components);proposals=list(components) + for radius in POLICY['fragment_join_radii_m']: + for region in parts(union.buffer(radius).buffer(-radius)): + if not eligible_symbol(region):continue + p=union.intersection(region.buffer(.02)) + if not p.is_empty:proposals.append(p) + count=0 + for p in proposals: + if not eligible_symbol(p)or p.intersection(symbols).area/p.area>.35:continue + coords=project(np.asarray(p.convex_hull.exterior.coords),g);uv=np.rint((coords+.5)*size/1200-.5).astype('int32');x,y,w,h=cv2.boundingRect(uv) + if x<0 or y<0 or x+w>size or y+h>size:continue + sel=np.zeros((h,w),np.uint8);cv2.fillPoly(sel,[uv-[x,y]],1);vals=semantic[y:y+h,x:x+w][sel>0] + mean=float(vals.mean());peak=float(np.quantile(vals,.9)) + if mean.75 for q in candidates):continue + candidates.append(r) +(O/'discovery-proposals.json').write_text(json.dumps(dict(lines=[pack(r)for r in records],glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,policy=POLICY,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest()),allow_nan=False)) +print('PROPOSALS',len(records),len(candidates),flush=True) diff --git a/simulation/urban-plan-research/discovery_pass/fragment_templates.py b/simulation/urban-plan-research/discovery_pass/fragment_templates.py new file mode 100644 index 00000000..560d93ad --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/fragment_templates.py @@ -0,0 +1,97 @@ +"""Template hypotheses in metric object coordinates; never site coordinates.""" +import numpy as np,cv2,shapely +from shapely.geometry import Polygon,LineString +from shapely.ops import unary_union +from shapely.affinity import rotate,translate +from scipy.optimize import minimize +from road_glyph_presets import arrow + +def turn_signature(xy,u,L,W,sign): + # Measure the tail's actual paint axis; rotating a turn template over a + # straight arrow must not manufacture the required lateral head displacement. + t=xy@u;tail=xy[tL*.72] + if len(tail)<8 or len(front)<8:return False + fit=cv2.fitLine(tail.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();axis=fit[:2] + if axis@u<0:axis=-axis + if axis@umax(.18,.25*W) + +def template(kind,L,W,stroke): + if kind!='letter_A':return arrow(kind,L,W,stroke) + # A is an original parametric preset. Arrows use the attributed SVG library. + outer=LineString([(0,-W/2),(L,0),(0,W/2)]).buffer(stroke/2,cap_style=2,join_style=3) + bar=LineString([(L*.3,-W*.35),(L*.3,W*.35)]).buffer(stroke/2,cap_style=2) + return unary_union([outer,bar]) + +def fit_symbol(p,heading=None,diagnostics=None): + from discovery_rules import POLICY + if p.geom_type not in ['Polygon','MultiPolygon'] or p.area<.25:return None + points=np.array(p.convex_hull.exterior.coords)[:,:2];rect=cv2.minAreaRect(points.astype('float32'));corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));u=edges[k]/np.linalg.norm(edges[k]);L=np.linalg.norm(edges[k]);W=min(rect[1]);origin=np.array(rect[0]);ang=np.arctan2(u[1],u[0]);fill=p.area/(L*W) + if not (1.21.2 and .09350:return None + target=np.zeros(shape,np.uint8) + def draw(poly): + out=np.zeros(shape,np.uint8) + for part in ([poly] if poly.geom_type=='Polygon' else getattr(poly,'geoms',[])): + if part.geom_type!='Polygon' or part.is_empty:continue + cv2.fillPoly(out,[np.rint((np.array(part.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1) + for hole in part.interiors:cv2.fillPoly(out,[np.rint((np.array(hole.coords)[:,:2]-lo)/cell).astype('int32')],0) + return out + target=draw(p);expanded=cv2.dilate(target,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))) + # The counter supplies a strong object identity cue, independent of a noisy + # semantic mask. A bounded 8 cm closing tolerates small wear breaks. + closed=p.buffer(.08).buffer(-.08) + counters=[Polygon(h)for part in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if part.geom_type=='Polygon'for h in part.interiors] + has_counter=any(h.area>.05*L*W for h in counters) + variants=['letter_A']if has_counter else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow'];best=None + if heading is not None:ang=float(np.arctan2(heading[1],heading[0])) + for kind in variants: + for flip in [0,np.pi]: + a=ang+flip;uu=np.array([np.cos(a),np.sin(a)]);base=origin-uu*L/2 + x0=np.array([base[0],base[1],a,L,W,.16]);bounds=[(base[0]-.4,base[0]+.4),(base[1]-.4,base[1]+.4),(a-.16,a+.16),(L*.85,L*1.15),(W*.75,W*1.25),(.08,.32)] + def polygon(x): + m=template(kind,x[3],x[4],x[5]);m=rotate(m,x[2],origin=(0,0),use_radians=True);return translate(m,x[0],x[1]) + def loss(x): + m=draw(polygon(x));wide=cv2.dilate(m,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))) + coverage=(m&expanded).sum()/max(m.sum(),1);recall=(wide&target).sum()/max(target.sum(),1) + overlap=(m&target).sum()/max((m|target).sum(),1) + return 1-(.6*2*coverage*recall/max(coverage+recall,1e-6)+.4*overlap)+.03*abs(x[3]/L-1) + score=loss(x0) + if kind!='letter_A' and (W<.60 or W/x0[5]<3.5):continue + # A worn letter may have an open counter; missing topology is not a veto. + if score>.8:continue + fit=minimize(loss,x0,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.004,ftol=.004));m=polygon(fit.x);r=draw(m) + coverage=float((r&expanded).sum()/max(r.sum(),1));recall=float((cv2.dilate(r,np.ones((5,5),np.uint8))&target).sum()/max(target.sum(),1));f1=2*coverage*recall/max(coverage+recall,1e-6);overlap=float((r&target).sum()/max((r|target).sum(),1));score=.6*f1+.4*overlap + if diagnostics is not None:diagnostics.append(dict(kind=kind,coverage=coverage,recall=recall,score=score,overlap=overlap,counter=has_counter,parameters=fit.x.tolist())) + if kind=='letter_A': + x=fit.x;bar=LineString([(x[3]*.3,-x[4]*.30),(x[3]*.3,x[4]*.30)]).buffer(x[5]/2,cap_style=2) + bar=translate(rotate(bar,x[2],origin=(0,0),use_radians=True),x[0],x[1]);support=draw(bar) + if (support&expanded).sum()/max(support.sum(),1)<.6:continue + # Positive shape overlap alone confuses arrow heads and triangular signs + # with A. Its counter is negative evidence and must stay largely unpainted. + holes=unary_union([Polygon(h)for part in ([m]if m.geom_type=='Polygon'else m.geoms)if part.geom_type=='Polygon'for h in part.interiors]) + core=holes.buffer(-.08) + mask=draw(core) + if mask.sum()<8 or (mask&expanded).sum()/mask.sum()>.15:continue + elif kind.startswith('straight_') and kind!='straight_arrow': + # A compound arrow needs its lateral branch, even if a straight arrow + # alone matches most of the template area. + x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]]) + yy,xx=np.mgrid[:r.shape[0],:r.shape[1]];xy=np.stack([lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]],axis=-1);side=xy@n + # Artwork is bbox-centered; use the outer quarter on the branch side. + sign=1 if 'left'in kind else -1 + branch=(r>0)&(side*sign>x[4]*.24) + if branch.sum()<5 or (branch&expanded).sum()/branch.sum()<.8:continue + longitudinal=xy@u;head=(r>0)&(longitudinal>x[3]*.8) + if head.sum()<5 or (head&expanded).sum()/head.sum()<.85:continue + elif kind in ['left_arrow','right_arrow']: + x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]]) + yy,xx=np.nonzero(target);xy=np.c_[lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]];longitudinal=xy@u;side=xy@n + sign=1 if kind=='left_arrow'else -1 + if not turn_signature(xy,u,x[3],x[4],sign):continue + if coverage>=.72 and recall>=POLICY['symbol_proposal_recall'] and (best is None or score>best[1]):best=(m,score,kind,recall,fit.x.tolist()) + if best and best[1]>=POLICY['symbol_proposal_score']:return best + return None diff --git a/simulation/urban-plan-research/discovery_pass/refine_discovery.py b/simulation/urban-plan-research/discovery_pass/refine_discovery.py new file mode 100644 index 00000000..709bc65b --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/refine_discovery.py @@ -0,0 +1,97 @@ +from pathlib import Path +import os,json,time,hashlib,collections +import numpy as np,cv2,shapely +from shapely.geometry import shape,mapping +from shapely.ops import transform +from layer_common import O,S,sample,feature +from line_reconstruction import rows +from beta_profiles import describe,profiles,discover,section_evidence,supported +from interval_profiles import rectangle +from row_evidence import GaussianViews +from discovery_rules import VERSION,POLICY,unpack,uncovered,glyph_pass,glyph_context +from discovery_evidence import glyph_views,DiscoveryViews +from fragment_templates import fit_symbol +from gost_catalog import assess_dash +cv2.setNumThreads(3);start=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']} +proposals=json.loads((O/'discovery-proposals.json').read_text());assert proposals['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest() +with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds'] +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'] +def poly(f):return shapely.force_2d(shape(f['geometry'])) +def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p) +paint=[poly(f)for f in old['features']if f['properties']['class']=='road_marking'];existing=shapely.union_all(paint) +protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']) +views=DiscoveryViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[] +def admit(polys,subtype,kind,evidence,source_tiles,**extra): + global existing + kept=[p for p in polys if uncovered(p,existing)] + if not kept:return False + new=[feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_ids=[],source_tile=source_tiles[0],source_tiles=source_tiles,line_kind='dashed'if kind=='periodic-row'else'unclassified-strip'if kind=='observed-strip'else None,standard_compliance='not_assessed',**extra)for p in kept] + if len(set(f['id']for f in new))!=len(new)or any(f['id']in current for f in new):return False + for f in new:current[f['id']]=f + existing=shapely.union_all([existing]+kept) + transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']for f in new],before=[],after=new,bounds_xy=shapely.union_all(polys).bounds,evidence=evidence,source_tiles=source_tiles,discovery_without_vector_seed=True,**extra)) + print('ADMIT',len(transactions),kind,subtype,len(new),flush=True);return True + +# Fragment sets and complete components share the same attributed presets. +# The two full-object render footprints are selected by geometry only. +records=[unpack(r)for r in proposals['lines']] +for gi,r in enumerate(proposals['glyphs']): + p=shape(r['geometry']);diag=[];f=fit_symbol(p,diagnostics=diag) + if f is None:diagnostics.append(dict(kind='glyph',reason='template-rejected',proposal=gi,best_score=max((q['score']for q in diag),default=0),model_trials=diag));continue + polygon,score,kind,recall,params=f + if not uncovered(polygon,existing):continue + context=glyph_context(polygon,params,records) + if not context['passed']:diagnostics.append(dict(kind='glyph',proposal=gi,reason='no-compatible-lane-context',context=context,geometry=mapping(polygon)));continue + ev,names=glyph_views(polygon,views,kind,params);okay=len(ev)==2 and len(set(names))==2 and all(glyph_pass(e)for e in ev) + diagnostics.append(dict(kind='glyph',proposal=gi,subtype=kind,score=score,evidence=ev,passed=okay,geometry=mapping(polygon))) + if okay:admit([polygon],kind,'glyph',ev,names,template_fit_score=score,fit_recall=recall,template_parameters=params,fragment_count=len(getattr(p,'geoms',[p])),lane_context=context) + if gi%10==0:print('GLYPH',gi+1,'/',len(proposals['glyphs']),flush=True) + +views.protected=shapely.union_all([protected]+[poly(f).convex_hull for f in current.values()if f['properties'].get('method')==VERSION and f['properties'].get('subtype')!='linear_marking']) + +# Use both individual image strips and robust component-center row hypotheses. +# No old vector supplies a proposal axis or selects a processing neighborhood. +records=[unpack(r)for r in proposals['lines']];seeds=[] +for r in records: + if r['W']<=.35 and r['L']>=.3 and r['polygon'].intersection(existing.buffer(.1)).area/r['polygon'].area<.70: + seed=describe(r['polygon']) + if seed is not None:seeds.append(seed) +for row in rows(records): + if len(row['records'])<3:continue + o,u=row['origin'].astype(float),row['axis'].astype(float);u/=np.linalg.norm(u);ts=(row['points']-o)@u;L=float(ts.max()-ts.min()) + if 1.8 for p in seen):continue + seen.append(domain);profiled+=1;readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers) + profile_stats['two_view_profile'if pv is not None else 'no_two_view_profile']+=1 + found=discover(seed,pv) + for r in found:r['source_tiles']=sorted(set(used[0])|set(used[1]));periodic.append(r) + if pv is not None and seed['length']>=POLICY['min_solid_length_m']: + # Keep measured uninterrupted intervals only. Endpoints of new solids + # come from agreeing paint runs, never a semantic/visibility mask edge. + for a,b in pv[0]['intervals']: + if b-a<3 or b<-seed['length']/2 or a>seed['length']/2:continue + matches=[(c,d)for c,d in pv[1]['intervals']if max(abs(a-c),abs(b-d))<=.2] + if not matches:continue + c,d=min(matches,key=lambda z:abs(z[0]-a)+abs(z[1]-b));lo0,hi0=(a+c)/2,(b+d)/2 + ev=[section_evidence(v,lo0+.1,hi0-.1)for v in pv] + if not all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']and e['contrast']>=22 for e in ev):continue + from beta_profiles import corridor_dark + ends=[corridor_dark(v,*span)for v in pv for span in [(lo0-.3,lo0-.07),(hi0+.07,hi0+.3)]] + if not all(supported(e,False)for e in ends):continue + p=rectangle(seed['origin'],seed['axis'],lo0,hi0,float(np.clip(np.median([v['width']for v in pv]),.075,.27)),float(np.mean([v['offset']for v in pv]))) + solids.append(dict(polygon=p,evidence=dict(paint=ev,ends=ends),source_tiles=sorted(set(used[0])|set(used[1])))) + if profiled%25==0:print('PROFILE',profiled,'/',len(seeds),'ROWS',len(periodic),'SOLIDS',len(solids),flush=True) + +for r in sorted(periodic,key=lambda r:-len(r['polygons'])): + ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode']) + admit(r['polygons'],'linear_marking','periodic-row',ev,r['source_tiles'],period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width'])) +for r in sorted(solids,key=lambda r:-r['polygon'].area):admit([r['polygon']],'linear_marking','observed-strip',r['evidence'],r['source_tiles']) +result={**old,'features':list(current.values()),'discovery_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False)) +(O/'discovery-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'discovery-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes()) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(collections.Counter(r['kind']for r in transactions)),profiled_axes=profiled,profile_stats=dict(profile_stats),raw_line_proposals=len(records),raw_glyph_proposals=len(proposals['glyphs']),added_objects=sum(len(r['after'])for r in transactions),added_subtypes=dict(collections.Counter(f['properties']['subtype']for r in transactions for f in r['after'])),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False) +(O/'discovery-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/discovery_pass/render_discovery.py b/simulation/urban-plan-research/discovery_pass/render_discovery.py new file mode 100644 index 00000000..6ed8f789 --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/render_discovery.py @@ -0,0 +1,31 @@ +from pathlib import Path +import os,json,shutil +from datetime import datetime,timezone +import numpy as np,shapely +from PIL import Image,ImageDraw,ImageFont +from shapely.geometry import shape +from layer_common import O,S +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'discovery-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('discovery-*.jpg'): + h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name) +def draw(im,g,features): + im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200 + for f in features: + if f['properties'].get('class')!='road_marking':continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2))) + return im +frames=[];manifest=[];loaded={} +for gi,rec in enumerate(groups): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'] + if name not in loaded: + g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))} + g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='discovery-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects'])) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('discovery-proof-%03d.jpg'%(start//4+1)),quality=94) +(O/'discovery-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True) diff --git a/simulation/urban-plan-research/discovery_pass/test_discovery.py b/simulation/urban-plan-research/discovery_pass/test_discovery.py new file mode 100644 index 00000000..9570daaf --- /dev/null +++ b/simulation/urban-plan-research/discovery_pass/test_discovery.py @@ -0,0 +1,54 @@ +import json,runpy,numpy as np,shapely +from shapely.affinity import rotate,translate +from shapely.geometry import box +from discovery_rules import uncovered,eligible_symbol,glyph_score,glyph_pass,glyph_context +from fragment_templates import fit_symbol,turn_signature +from road_glyph_presets import arrow +from line_reconstruction import observation,rows +from beta_profiles import profiles,discover +from interval_profiles import rectangle +prior=runpy.run_path('/candidate/test_beta.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()} +p=arrow('straight_arrow',4.,1.2,.16) +checks['preset_is_glyph_proposal']=eligible_symbol(p) +checks['narrow_lane_strip_not_glyph']=not eligible_symbol(box(0,0,5,.12)) +checks['solid_box_not_glyph']=not eligible_symbol(box(0,0,4,1.2)) +checks['zero_area_not_glyph']=not eligible_symbol(box(0,0,0,0)) +fragmented=p.difference(box(1.5,-2,1.56,2));fit=fit_symbol(fragmented) +checks['fragmented_arrow_uses_reusable_preset']=fit is not None and fit[2]=='straight_arrow' +checks['near_duplicate_not_added']=not uncovered(translate(box(0,0,5,.12),yoff=.10),box(0,0,5,.12)) +checks['real_separate_parallel_strip_allowed']=uncovered(translate(box(0,0,5,.12),yoff=.32),box(0,0,5,.12)) +checks['overlapping_paint_not_added']=not uncovered(box(0,0,5,.12),box(2,0,8,.12)) +checks['empty_map_accepts_first_object']=uncovered(p,shapely.GeometryCollection()) +cell=.04;x,y=np.meshgrid(np.arange(-1,5,cell),np.arange(-2,2,cell));points=np.c_[x.ravel(),y.ravel()];on=shapely.contains_xy(p,points[:,0],points[:,1]).reshape(x.shape) +rgb=np.repeat(np.where(on,220,65)[:,:,None],3,axis=2).astype('uint8');valid=np.ones(x.shape,bool) +ev=glyph_score(rgb,valid,points,p);checks['visible_preset_has_paint_and_negative_support']=glyph_pass(ev) +checks['unobserved_preset_rejected']=not glyph_pass(glyph_score(rgb,np.zeros_like(valid),points,p)) +checks['paint_free_patch_rejected']=not glyph_pass(glyph_score(np.full_like(rgb,65),valid,points,p)) +filled=shapely.contains_xy(p.convex_hull,points[:,0],points[:,1]).reshape(x.shape);rr=np.repeat(np.where(filled,220,65)[:,:,None],3,axis=2).astype('uint8') +checks['painted_negative_space_rejected']=not glyph_pass(glyph_score(rr,valid,points,p)) +checks['head_and_tail_verified_separately']=glyph_pass(glyph_score(rgb,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16])) +missing=rgb.copy();missing[x>3.1]=65 +checks['missing_head_cannot_authorize_arrow']=not glyph_pass(glyph_score(missing,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16])) +cp=arrow('straight_left_arrow',4,1.5,.16);on2=shapely.contains_xy(cp,points[:,0],points[:,1]).reshape(x.shape);crgb=np.repeat(np.where(on2,220,65)[:,:,None],3,axis=2).astype('uint8') +checks['compound_parts_all_observed']=glyph_pass(glyph_score(crgb,valid,points,cp,kind='straight_left_arrow',parameters=[0,0,0,4,1.5,.16])) +crgb[y>.2]=65 +checks['missing_side_branch_cannot_authorize_compound']=not glyph_pass(glyph_score(crgb,valid,points,cp,kind='straight_left_arrow',parameters=[0,0,0,4,1.5,.16])) +xy=points[on.ravel()] +for degrees in [-9,0,9]: + a=np.deg2rad(degrees);axis=np.array([np.cos(a),np.sin(a)]) + checks['straight_arrow_not_turn_with_hypothesis_angle_'+str(degrees)]=not turn_signature(xy,axis,4,1.2,1)and not turn_signature(xy,axis,4,1.2,-1) +for kind,sign in [('left_arrow',1),('right_arrow',-1)]: + tp=arrow(kind,4,1.5,.16);txy=points[shapely.contains_xy(tp,points[:,0],points[:,1])] + checks[kind+'_has_independently_measured_turn']=turn_signature(txy,np.array([1.,0]),4,1.5,sign) +missingtail=rgb.copy();missingtail[x<1.0]=65 +checks['entire_missing_tail_rejected']=not glyph_pass(glyph_score(missingtail,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16])) +through=rgb.copy();through[abs(y)<.08]=220 +checks['stripe_through_symbol_cannot_be_arrow']=not glyph_pass(glyph_score(through,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16])) +context=[observation(np.array(box(-1,offset,6,offset+.12).exterior.coords),'image')for offset in [-1.5,1.5]] +checks['arrow_agrees_with_independent_lane_strips']=glyph_context(p,[0,0,0,4,1.2,.16],context)['passed'] +checks['perpendicular_noise_not_lane_arrow']=not glyph_context(p,[0,0,np.pi/2,4,1.2,.16],context)['passed'] +checks['one_strip_not_sufficient_context']=not glyph_context(p,[0,0,0,4,1.2,.16],context[:1])['passed'] +# Empty vector map: image component centers alone supply the row hypothesis. +obs=[observation(np.array(rectangle(np.zeros(2),np.array([1.,0]),i,i+.5,.12).exterior.coords),'image')for i in range(6)] +rs=rows(obs);checks['image_components_form_row_without_vectors']=any(len(r['records'])>=4 for r in rs) +result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/discovery-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed'] diff --git a/simulation/urban-plan-research/driveway_refinement.py b/simulation/urban-plan-research/driveway_refinement.py new file mode 100644 index 00000000..f2be3bf3 --- /dev/null +++ b/simulation/urban-plan-research/driveway_refinement.py @@ -0,0 +1,55 @@ +"""Paired straight access boundaries from LSD anchors in a reviewed region.""" +import cv2,numpy as np +from shapely.geometry import LineString,Point +from shapely.ops import substring +from plan_junctions import unit,line_intersection +import qualify_junctions as q + + +def fit_access(line,center,e,bounds): + station=line.project(Point(center));origin=np.asarray(line.interpolate(station).coords[0]);segment=np.array(substring(line,max(0,station-3),min(line.length,station+3)).coords) + u=unit(segment[-1,:2]-segment[0,:2]);v=np.array([-u[1],u[0]]) + if np.mean(e.occupancy(origin[None,:2]+v)-e.occupancy(origin[None,:2]-v))>0:v=-v + raw=cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD).detect(cv2.cvtColor(e.image,cv2.COLOR_RGB2GRAY))[0] + anchors=[];transverse=[] + for r in ([]if raw is None else raw[:,0,:]): + ends=q.world(r.reshape(2,2),e.g);mid=ends.mean(0);length=np.linalg.norm(ends[1]-ends[0]);direction=unit(ends[1]-ends[0]);depth=float((mid-origin[:2])@v) + if length<.8 or not(bounds[0].97 and .5.97 and depth>3:transverse.append(dict(ends=ends,length=length,mid=mid,depth=depth)) + choices=[] + for i,a in enumerate(anchors): + for b in anchors[i+1:]: + if a['direction']@b['direction']<.99:continue + direction=unit(a['direction']*a['length']+b['direction']*b['length']);normal=np.array([-direction[1],direction[0]]) + if normal@u<0:normal=-normal + origins=sorted([a['mid'],b['mid']],key=lambda p:p@normal);width=float((origins[1]-origins[0])@normal) + if not 2anchor_depth+.4 and x['length']>.45*width and abs((x['mid']-midpoint)@normal) 4 * 1024**3: + raise ValueError("Numeric archive exceeds verification envelope") + members = [] + for name in names: + if not name.endswith(".npy"): + raise ValueError("Unexpected NPZ member") + with archive.open(name) as stream: + members.append((name, stream_digest(stream))) + return members + if path.suffix == ".gz": + with gzip.open(path, "rb") as stream: + return stream_digest(stream) + return file_digest(path) + + +def inventory(root): + paths = sorted( + p for p in root.rglob("*") + if p.is_file() and p.suffix in {".npz", ".npy", ".png", ".gz"} + ) + if len(paths) > 5000 or sum(p.stat().st_size for p in paths) > 20 * 1024**3: + raise ValueError("Run exceeds the bounded verification envelope") + if any(p.is_symlink() or not p.resolve().is_relative_to(root.resolve()) for p in paths): + raise ValueError("Evidence path escapes the frozen run") + return {p.relative_to(root).as_posix(): p for p in paths} + + +def compare(baseline, candidate, expected_baseline, expected_candidate, output): + for root, expected in [(baseline, expected_baseline), (candidate, expected_candidate)]: + assert not (root / "active.json").exists(), "Run is still active" + assert file_digest(root / "summary.json") == expected, "Summary changed" + a = json.loads((baseline / "summary.json").read_text()) + b = json.loads((candidate / "summary.json").read_text()) + assert a["cold_run"] and b["cold_run"] + assert a["completed_stages"] == b["completed_stages"] == 30 + ma = json.loads((baseline / "manifest.json").read_text()) + mb = json.loads((candidate / "manifest.json").read_text()) + sa, sb = ma["source_files"], mb["source_files"] + changed = sorted(k for k in sa.keys() | sb.keys() if sa.get(k) != sb.get(k)) + assert changed == ["simulation/urban-plan-research/systematic/refine_markings.py"], changed + checks = { + "worker_source_exact": ma["worker_sha256"] == mb["worker_sha256"], + "same_release_support": ma["release"] == mb["release"], + "historical_geometry_not_an_input": ( + ma["old_geometry_as_input"] is False and mb["old_geometry_as_input"] is False + ), + "gaussian_exact": a["gaussian_sha256"] == b["gaussian_sha256"], + "poses_exact": a["poses_sha256"] == b["poses_sha256"], + "final_map_file_exact": a["final_map_sha256"] == b["final_map_sha256"], + "final_map_content_exact": a["final_map"] == b["final_map"], + "same_stage_resources": [ + (r["phase"], r["resources"], r["gpu"]) + for r in a["execution_profile"]["stages"] + ] == [ + (r["phase"], r["resources"], r["gpu"]) + for r in b["execution_profile"]["stages"] + ], + } + left, right = inventory(baseline / "run"), inventory(candidate / "run") + assert left and right, "No numeric or image evidence to compare" + checks["same_numeric_and_image_inventory"] = left.keys() == right.keys() + rows = [] + for name in sorted(left.keys() & right.keys()): + ah, bh = file_digest(left[name]), file_digest(right[name]) + row = dict(path=name, baseline_sha256=ah, candidate_sha256=bh, file_exact=ah == bh) + row["payload_exact"] = row["file_exact"] or ( + payload_digest(left[name]) == payload_digest(right[name]) + ) + rows.append(row) + if len(rows) % 200 == 0: + print("EVIDENCE_COMPARED", len(rows), "/", len(left), flush=True) + checks["all_numeric_and_image_payloads_exact"] = all(r["payload_exact"] for r in rows) + json_checks = {} + for name in [ + "primary_search/observations.json", + "primary_search/search-proposals.json", + "primary_search/symbol-patches.json", + "marking_pass/full-map.json", + "marking_pass/marking-rows.json", + "marking_pass/finite-stroke-admission.json", + "marking_pass/configuration-bank.json", + ]: + pa, pb = baseline / "run" / name, candidate / "run" / name + assert pa.is_file() and pb.is_file(), name + json_checks[name] = file_digest(pa) == file_digest(pb) + checks["decisions_and_primary_manifests_exact"] = all(json_checks.values()) + report = dict( + schema="missioncore.frozen-full-run-equivalence/v1", + baseline=baseline.name, + candidate=candidate.name, + baseline_summary_sha256=expected_baseline, + candidate_summary_sha256=expected_candidate, + changed_sources=changed, + checks=checks, + json_artifacts=json_checks, + artifact_count=len(rows), + baseline_artifact_bytes=sum(p.stat().st_size for p in left.values()), + packaging_only_differences=[ + r["path"] for r in rows if not r["file_exact"] and r["payload_exact"] + ], + payload_differences=[r["path"] for r in rows if not r["payload_exact"]], + artifacts=rows, + accuracy_or_recall_measured=False, + passed=all(checks.values()), + ) + output.write_text(json.dumps(report, indent=2)) + assert report["passed"], "Frozen runs differ; inspect the evidence report" + return report + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("baseline", type=Path) + parser.add_argument("candidate", type=Path) + parser.add_argument("baseline_sha256") + parser.add_argument("candidate_sha256") + parser.add_argument("output", type=Path) + args = parser.parse_args() + result = compare( + args.baseline, args.candidate, args.baseline_sha256, args.candidate_sha256, args.output + ) + print("FULL_EQUIVALENCE", result["passed"], result["artifact_count"], flush=True) diff --git a/simulation/urban-plan-research/evaluation/compare_pipeline_maps.py b/simulation/urban-plan-research/evaluation/compare_pipeline_maps.py new file mode 100644 index 00000000..fc2c219f --- /dev/null +++ b/simulation/urban-plan-research/evaluation/compare_pipeline_maps.py @@ -0,0 +1,59 @@ +"""Compare cold candidate geometry to an immutable algorithmic control. + +The control is not ground truth. Do not label these measurements recall or +precision of the real street. Split/join changes are measured as coverage as +well as object matches; counts alone cannot demonstrate preservation. +""" +from collections import Counter +import hashlib,json,sys +from pathlib import Path +import numpy as np,shapely +from shapely.geometry import shape + +def kind(f): + p=f['properties'];return p.get('subtype') if p['class']=='road_marking' else p['class'] + +def geometry(f):return shapely.force_2d(shape(f['geometry'])) + +def fraction(a,b,tolerance=0.): + if a.is_empty:return 0. + if a.area>0:return float(a.intersection(b.buffer(tolerance) if tolerance else b).area/a.area) + return float(a.intersection(b.buffer(max(tolerance,1e-7))).length/max(a.length,1e-9)) + +def compare(control,candidate): + old=control['features'];new=candidate['features'];by_class={};rows=[] + for cls in sorted({kind(f)for f in old+new}): + a=[f for f in old if kind(f)==cls];b=[f for f in new if kind(f)==cls] + A=shapely.union_all([geometry(f)for f in a]);B=shapely.union_all([geometry(f)for f in b]);matches=[] + for f in a: + p=geometry(f);scores=[] + for q in b: + g=geometry(q) + iou=p.intersection(g).area/max(p.union(g).area,1e-9) if p.area else fraction(p,g,.1) + scores.append((iou,q['id'],float(p.hausdorff_distance(g)),float(p.centroid.distance(g.centroid)))) + best=max(scores,default=(0,None,None,None));cover=fraction(p,B,.1) + # Symbols stay whole; linear paint may legitimately split or join. + matched=best[0]>=.5 if cls.endswith('_arrow')or cls in {'bicycle','letter_A'} else cover>=.95 + record=dict(class_name=cls,id=f['id'],best_iou_or_line_coverage=best[0],best_id=best[1],best_hausdorff_m=best[2],best_centroid_distance_m=best[3],covered_fraction_10cm=cover,covered_fraction_exact=fraction(p,B),matched=matched,bounds_xy=list(p.bounds)) + rows.append(record);matches.append(matched) + by_class[cls]=dict(control_objects=len(a),candidate_objects=len(b),matched_control_objects=sum(matches),control_retention_fraction=sum(matches)/len(a)if a else None,control_coverage_exact=fraction(A,B),control_coverage_5cm=fraction(A,B,.05),control_coverage_10cm=fraction(A,B,.1),candidate_coverage_by_control_10cm=fraction(B,A,.1)) + def line_quality(doc): + features=[f for f in doc['features']if kind(f)=='linear_marking'];area=0.;sums=Counter();unassessed=0;fully=0 + for f in features: + p=geometry(f);area+=p.area;ev=f['properties'].get('linear_support') + if not ev:unassessed+=1;continue + fully+=ev.get('measured_fraction',0)>=.98 + for k,v in ev.get('area_fractions',{}).items():sums[k]+=v*p.area + return dict(objects=len(features),fully_measured_objects=fully,unassessed_objects=unassessed,paint_area_m2=area,area_fractions={k:v/max(area,1e-9)for k,v in sums.items()}) + invalid=[] + for f in new: + p=shape(f['geometry']);xyz=shapely.get_coordinates(p,include_z=True) + if p.is_empty or not p.is_valid or not np.isfinite(xyz).all():invalid.append(f['id']) + return dict(reference_role='completed previous algorithm; not independently labelled ground truth',thresholds=dict(paint_coverage_tolerance_m=.1,paint_coverage_fraction=.95,whole_symbol_iou=.5),classes=by_class,rows=rows,unmatched_control_ids=[r['id']for r in rows if not r['matched']],invalid_candidate_ids=invalid,duplicate_candidate_ids=[i for i,n in Counter(f['id']for f in new).items()if n>1],control_linear_evidence=line_quality(control),candidate_linear_evidence=line_quality(candidate),complete_recall_measured=False) + +def main(): + a,b,out=map(Path,sys.argv[1:]);old=json.loads(a.read_text());new=json.loads(b.read_text()) + old=old.get('final_map',old);new=new.get('final_map',new) + result=compare(old,new);result['input_sha256']={str(p):hashlib.sha256(p.read_bytes()).hexdigest()for p in[a,b]} + out.write_text(json.dumps(result,indent=2,allow_nan=False));print(json.dumps({k:v for k,v in result.items()if k!='rows'},indent=2)) +if __name__=='__main__':main() diff --git a/simulation/urban-plan-research/evaluation/contract_preflight.py b/simulation/urban-plan-research/evaluation/contract_preflight.py new file mode 100644 index 00000000..afed33cb --- /dev/null +++ b/simulation/urban-plan-research/evaluation/contract_preflight.py @@ -0,0 +1,112 @@ +"""Empty-observation end-to-end contracts: exercise every downstream writer/reader.""" +from pathlib import Path +import json,shutil,hashlib + + +def qualify_numeric_invariants(root, modules, marker, profile, run_container): + """Keep identity and partition invariance mandatory for future candidates.""" + checked = [] + for name, entry in [ + ('observed-geometry-identity', 'test_observed_geometry.py'), + ('object-evidence-partition', 'test_object_evidence.py'), + ]: + assert (modules / 'marking_pass' / entry).is_file(), 'Missing numeric contract: ' + entry + output = root / name + output.mkdir() + run_container( + marker, 'contract-' + name, profile['mapper_image'], + [(modules / 'marking_pass', '/candidate', True), (output, '/out', False)], + ['-B', '/candidate/' + entry], output, lambda: None, 60, + gpu=False, executable='python3', readonly=True, + environment=dict(PYTHONPATH='/candidate', OPENBLAS_NUM_THREADS='3', OMP_NUM_THREADS='3'), + ) + checked.append(name) + print('CONTRACT_OK', name, flush=True) + return checked + + +def run(root,definition,modules,original,marker,profile,runtime,release,run_container,write_json): + preflight=root/'contracts';preflight.mkdir();primary=preflight/'primary';primary.mkdir() + empty=preflight/'empty';empty.mkdir();write_json(empty/'full-map.json',dict(type='FeatureCollection',features=[])) + digest=hashlib.sha256((original/'full_plan/fields.npz').read_bytes()).hexdigest() + for name,doc in { + 'observations.json':dict(paint=[],crossbars=[]), + 'search-proposals.json':dict(lines=[],glyphs=[],source_fields_sha256=digest), + 'catalog-proposals.json':dict(glyphs=[],source_fields_sha256=digest), + 'arrow-gates.json':[], 'crossing-seeds.json':[], + 'symbol-patches.json':dict(patches=[]), + }.items():write_json(primary/name,doc) + write_json(primary/'symbol-semantics.json',dict(records=[],patch_manifest_sha256=hashlib.sha256((primary/'symbol-patches.json').read_bytes()).hexdigest())) + previous=empty;results=[];locations={} + base=next(g for g in definition['groups']if g['group']=='base') + if 'test_initial_views.py'in base['files']: + coverage=preflight/'initial-views';coverage.mkdir() + run_container(marker,'contract-initial-views',profile['mapper_image'], + [(modules/'base','/candidate',True),(coverage,'/out',False)], + ['-B','/candidate/test_initial_views.py'],coverage,lambda:None,60,gpu=False,executable='python3', + environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True) + results.append('initial-view-cover');print('CONTRACT_OK initial-view-cover',flush=True) + if 'test_survey_index.py'in base['files']: + reader=preflight/'survey-index';reader.mkdir() + run_container(marker,'contract-survey-index',profile['mapper_image'], + [(modules/'base','/candidate',True),(reader,'/out',False)], + ['-B','/candidate/test_survey_index.py'],reader,lambda:None,60,gpu=False,executable='python3', + environment=dict(PYTHONPATH='/candidate'),readonly=True) + results.append('survey-manifest-identity');print('CONTRACT_OK survey-manifest-identity',flush=True) + primary_group=next(g for g in definition['groups']if g['group']=='primary_search') + if 'test_connected_ridges.py'in primary_group['files']: + branches=preflight/'connected-ridges';branches.mkdir() + run_container(marker,'contract-connected-ridges',profile['mapper_image'], + [(modules/'primary_search','/candidate',True),(branches,'/out',False)], + ['-B','/candidate/test_connected_ridges.py'],branches,lambda:None,60,gpu=False,executable='python3', + environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True) + results.append('connected-ridges');print('CONTRACT_OK connected-ridges',flush=True) + continuation=next(g for g in definition['groups']if g['group']=='continuation_pass') + if 'test_shared_surface_edges.py'in continuation['files']: + surface=preflight/'surface-structure';surface.mkdir() + run_container(marker,'contract-shared-surface-edges',profile['mapper_image'], + [(modules/'continuation_pass','/candidate',True),(surface,'/out',False)], + ['-B','/candidate/test_shared_surface_edges.py'],surface,lambda:None,60,gpu=False,executable='python3', + environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True) + results.append('shared-surface-edges');print('CONTRACT_OK shared-surface-edges',flush=True) + marking=next(g for g in definition['groups']if g['group']=='marking_pass') + if 'test_joint_choice.py'in marking['files']: + joint=preflight/'joint-assembly';joint.mkdir() + run_container(marker,'contract-joint-assembly',profile['mapper_image'], + [(modules/'marking_pass','/candidate',True),(joint,'/out',False)], + ['-B','/candidate/test_joint_choice.py'],joint,lambda:None,60,gpu=False,executable='python3', + environment=dict(PYTHONPATH='/candidate',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3'),readonly=True) + results.append('joint-assembly');print('CONTRACT_OK joint-assembly',flush=True) + results.extend(qualify_numeric_invariants(preflight,modules,marker,profile,run_container)) + fixture=Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/topdown-writer-queue-20261016101327/maroseyka/observations') + begin=next(i for i,g in enumerate(definition['groups'])if g['group']=='paint_assembly') + for group in definition['groups'][begin:]: + name=group['group'];out=preflight/name;out.mkdir() + if (previous/'crosswalk-standard-check.json').exists():shutil.copyfile(previous/'crosswalk-standard-check.json',out/'crosswalk-standard-check.json') + for stage in group['stages']: + mounts=[(modules/name,'/candidate',True),(previous,'/fullplan',True),(out,'/out',False), + (original/'full_plan','/evidence_plan',True),(original/'ortho/survey','/survey',True), + (original/'ortho','/ortho',True),(primary,'/primary',True), + (primary,'/symbolplan',True),(primary,'/gateplan',True),(primary,'/uniformplan',True),(primary,'/searchplan',True)] + if name=='primary_arrows': + mounts=[m for m in mounts if m[1]not in {'/ortho','/survey'}] + mounts += [(fixture,'/ortho',True),(fixture/'survey','/survey',True),(fixture/'native-geometry','/native_geometry',True)] + if 'primary_arrows'in locations:mounts.append((locations['primary_arrows'],'/primaryarrows',True)) + for wheel in (release/'simulation/urban-plan-research/pipeline/vendor').glob('*.whl'):mounts.append((wheel,'/candidate/'+wheel.name,True)) + env=dict(PYTHONPATH='/candidate:/candidate/mapping',SCENE='scene',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3',WINDOW_SOURCE='/candidate/linear_window_support.py') + if name=='primary_arrows' and stage==group['stages'][0]: + fixture_mounts=[m for m in mounts if m[1]!='/symbolplan']+[(primary,'/symbolplan',False)] + code="from pathlib import Path;import json,hashlib;from ground_observations import GroundObservations;p=Path('/symbolplan');d=json.loads((p/'symbol-patches.json').read_text());d['observation_snapshot']=GroundObservations().inventory()['snapshot'];(p/'symbol-patches.json').write_text(json.dumps(d));(p/'symbol-semantics.json').write_text(json.dumps(dict(records=[],patch_manifest_sha256=hashlib.sha256((p/'symbol-patches.json').read_bytes()).hexdigest())))" + run_container(marker,'contract-native-fixture',profile['mapper_image'],fixture_mounts,['-B','-c',code],out,lambda:None,180,gpu=False,executable='python3',environment=env,readonly=True) + entry='import runpy;' + + if stage=='final_symbol_admission':entry+="import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];" + entry+="runpy.run_path('/candidate/"+stage+".py',run_name='__main__')" + run_container(marker,'contract-'+stage,profile['mapper_image'],mounts,['-B','-c',entry],out,lambda:None,180 if name=='primary_arrows' else 60,gpu=False,executable='python3',environment=env,readonly=True) + results.append(stage);print('CONTRACT_OK',stage,flush=True) + if group.get('map_file'):shutil.copyfile(out/group['map_file'],out/'full-map.json') + assert json.loads((out/'full-map.json').read_text())['features']==[] + previous=out;locations[name]=out + write_json(preflight/'contract-fixture.json',dict(native_observations=fixture.as_posix(),read_only=True,scope='empty-observation contracts; not a cold result')) + write_json(preflight/'contract-report.json',dict(passed=True,stages=results,empty_input_remains_empty=True)) + return results diff --git a/simulation/urban-plan-research/evaluation/execution_profile.py b/simulation/urban-plan-research/evaluation/execution_profile.py new file mode 100644 index 00000000..a3bef4c6 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/execution_profile.py @@ -0,0 +1,139 @@ +"""Bounded external profiling; never wrap numeric or model operations. + +Container CPU/memory/I/O and host GPU utilization are observations, not GPU +kernel timings. Hash timing covers orchestration only. The sampler never +changes entrypoints, environments, resource limits, arrays, cameras or gates. +""" + +import datetime +import json +import subprocess +import threading +import time +from collections import Counter + + +class ExecutionProfile: + def __init__(self, root, pipeline, interval=5.0): + self.root = root + self.pipeline = pipeline + self.interval = interval + self.stages = [] + self.hashes = Counter() + self.samples = 0 + self.sample_seconds = 0.0 + self.errors = Counter() + self.phase = None + self.stop_event = threading.Event() + self.original_run = pipeline.run_container + self.original_checksum = pipeline.checksum + self.thread = None + + def start(self): + self.started = time.monotonic() + self.pipeline.run_container = self.run_container + self.pipeline.checksum = self.checksum + self.thread = threading.Thread(target=self.observe, daemon=True) + self.thread.start() + return self + + def checksum(self, path): + started = time.monotonic() + result = self.original_checksum(path) + self.hashes["calls"] += 1 + self.hashes["bytes"] += path.stat().st_size + self.hashes["seconds"] += time.monotonic() - started + return result + + def run_container(self, marker, phase, *args, **kwargs): + record = json.loads(marker.read_text()) + name = "ndc-infrastructure-" + record["key"][:16] + "-" + phase + self.phase = (phase, name) + started = time.monotonic() + row = dict( + phase=phase, + started_utc=datetime.datetime.now(datetime.UTC).isoformat(), + started_monotonic=started, + resources=kwargs.get("resources") or dict(cpus=4, memory_gib=16), + gpu=kwargs.get("gpu", True), + passed=False, + ) + try: + result = self.original_run(marker, phase, *args, **kwargs) + row["passed"] = True + return result + finally: + row["seconds"] = time.monotonic() - started + self.stages.append(row) + self.phase = None + (self.root / "stage-profile.json").write_text(json.dumps(self.stages, indent=2)) + + def command(self, args): + try: + result = subprocess.run(args, capture_output=True, text=True, timeout=3) + if result.returncode: + self.errors[args[0] + ":exit"] += 1 + return None + return result.stdout.strip() + except (OSError, subprocess.TimeoutExpired): + self.errors[args[0] + ":unavailable"] += 1 + return None + + def observe(self): + # At most 720 samples and a bounded lifetime, even after a caller error. + with (self.root / "resource-samples.jsonl").open("w") as output: + while self.samples < 720 and not self.stop_event.wait(self.interval): + phase = self.phase + if phase is None: + continue + begin = time.monotonic() + stats = self.command( + ["docker", "stats", "--no-stream", "--format", "{{json .}}", phase[1]] + ) + gpu = self.command( + [ + "nvidia-smi", + "--query-gpu=index,utilization.gpu,utilization.memory,memory.used,power.draw", + "--format=csv,noheader,nounits", + ] + ) + elapsed = time.monotonic() - begin + output.write( + json.dumps( + dict( + utc=datetime.datetime.now(datetime.UTC).isoformat(), + since_start_seconds=begin - self.started, + phase=phase[0], + same_phase_at_completion=self.phase == phase, + docker=stats, + gpu_host_csv=gpu, + observation_seconds=elapsed, + ) + ) + + "\n" + ) + output.flush() + self.samples += 1 + self.sample_seconds += elapsed + + def stop(self): + self.stop_event.set() + if self.thread is not None: + self.thread.join(timeout=10) + self.pipeline.run_container = self.original_run + self.pipeline.checksum = self.original_checksum + report = dict( + schema="missioncore.external-execution-profile/v1", + stages=self.stages, + orchestration_hashes=dict(self.hashes), + samples=self.samples, + observer_command_wall_seconds=self.sample_seconds, + errors=dict(self.errors), + sampler_stopped=self.thread is None or not self.thread.is_alive(), + numeric_functions_wrapped=False, + gpu_measurement_scope="host utilization; includes unrelated durable GPU services", + sample_interval_seconds=self.interval, + observer_wall_is_not_pipeline_overhead=True, + ) + (self.root / "execution-profile.json").write_text(json.dumps(report, indent=2)) + return report diff --git a/simulation/urban-plan-research/evaluation/explain_run_metadata.py b/simulation/urban-plan-research/evaluation/explain_run_metadata.py new file mode 100644 index 00000000..c127675f --- /dev/null +++ b/simulation/urban-plan-research/evaluation/explain_run_metadata.py @@ -0,0 +1,163 @@ +"""Explain elapsed-time metadata separately from exact physical evidence. + +No tolerance, array conversion, geometry normalization or generic field ignore +is allowed. The original failed raw-file comparison is retained unchanged. +""" + +import gzip +import hashlib +import json +import math +import pickle +import struct +from collections import Counter +from pathlib import Path + +import numpy as np + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def exact(a, b, counts, path="root"): + assert type(a) is type(b), (path, "type") + if isinstance(a, np.ndarray): + assert not a.dtype.hasobject, (path, "unqualified object array") + assert a.dtype == b.dtype and a.shape == b.shape and a.strides == b.strides, path + assert a.tobytes(order="A") == b.tobytes(order="A"), (path, "array bits") + counts["arrays"] += 1 + elif isinstance(a, np.generic): + assert a.dtype == b.dtype and a.tobytes() == b.tobytes(), (path, "scalar bits") + counts["numpy_scalars"] += 1 + elif type(a).__module__.startswith("shapely."): + assert a.wkb == b.wkb, (path, "geometry WKB") + counts["geometries"] += 1 + elif isinstance(a, dict): + assert list(a) == list(b), (path, "dictionary ordering") + for key in a: + exact(a[key], b[key], counts, path + "/" + str(key)) + elif isinstance(a, (tuple, list)): + assert len(a) == len(b), (path, "length") + for index, (x, y) in enumerate(zip(a, b, strict=True)): + exact(x, y, counts, path + "/" + str(index)) + elif isinstance(a, float): + assert struct.pack("!d", a) == struct.pack("!d", b), (path, "float bits") + counts["python_floats"] += 1 + elif a is None or isinstance(a, (str, bytes, int, bool)): + assert a == b, (path, "value") + counts["other_scalars"] += 1 + else: + raise TypeError((path, type(a))) + + +def elapsed(value): + assert type(value) is float and math.isfinite(value) and value >= 0 + return value + + +def proposal_data(document): + # observation_tiles.collect_tile writes exactly these monotonic durations. + result = {**document, "tile_reports": []} + times = [] + for row in document["tile_reports"]: + assert set(row["detectors"]) == {"linear", "appearance", "catalog", "compact", "crossing"} + times.append(dict( + tile=row["tile"], seconds=elapsed(row["seconds"]), + detectors={k: elapsed(v) for k, v in row["detectors"].items()}, + )) + result["tile_reports"].append({ + k: v for k, v in row.items() if k not in {"seconds", "detectors"} + }) + return result, times + + +def run(): + source = Path("/raw-proof") + proof = json.loads((source / "equivalence.json").read_text()) + assert not proof["passed"] + assert {k for k, v in proof["checks"].items() if not v} == { + "all_numeric_and_image_payloads_exact", "decisions_and_primary_manifests_exact", + } + assert proof["payload_differences"] == ["marking_pass/measured-bank.pkl.gz"] + assert {k for k, v in proof["json_artifacts"].items() if not v} == { + "primary_search/search-proposals.json", "primary_search/symbol-patches.json", + } + for name, key in [ + ("/baseline", "baseline_summary_sha256"), ("/candidate-run", "candidate_summary_sha256") + ]: + assert sha(Path(name) / "summary.json") == proof[key] + counts = Counter() + runs = [Path("/baseline/run"), Path("/candidate-run/run")] + proposals = [json.loads((r / "primary_search/search-proposals.json").read_text()) for r in runs] + physical, times = zip(*(proposal_data(d) for d in proposals), strict=True) + exact(physical[0], physical[1], counts, "search-proposals") + patches = [json.loads((r / "primary_search/symbol-patches.json").read_text()) for r in runs] + patch_times = [elapsed(p.pop("seconds")) for p in patches] + exact(patches[0], patches[1], counts, "symbol-patches") + manifests = [ + ("ortho/observation-coverage.json", "/ortho/observation-coverage.json", "solver"), + ( + "ortho/native-geometry/native-geometry.json", + "/ortho/native-geometry/native-geometry.json", None, + ), + ] + manifest_times = {} + for relative, _, parent in manifests: + documents = [json.loads((r / relative).read_text()) for r in runs] + manifest_times[relative] = [ + elapsed((d[parent] if parent else d).pop("seconds")) for d in documents + ] + exact(documents[0], documents[1], counts, relative) + bank_row = next(r for r in proof["artifacts"] if r["path"] == proof["payload_differences"][0]) + banks = [] + identities = [] + for root, key in zip(runs, ["baseline_sha256", "candidate_sha256"], strict=True): + path = root / bank_row["path"] + assert sha(path) == bank_row[key] + # Only our hash-verified qualification artifact is deserialized. + bank = pickle.loads(gzip.decompress(path.read_bytes())) + inputs = bank["observation_inputs"] + expected = hashlib.sha256(json.dumps(inputs, sort_keys=True).encode()).hexdigest() + assert bank["observation_identity"] == expected + timing_hashes = { + "/searchplan/search-proposals.json": sha(root / "primary_search/search-proposals.json") + } + timing_hashes.update({key: sha(root / relative) for relative, key, _ in manifests}) + for key, digest in timing_hashes.items(): + assert inputs[key] == digest + identities.append(dict(bank_identity=expected, verified_input_file_hashes=timing_hashes)) + physical_bank = {k: v for k, v in bank.items() if k != "observation_identity"} + physical_bank["observation_inputs"] = { + k: v for k, v in inputs.items() if k not in timing_hashes + } + banks.append(physical_bank) + exact(banks[0], banks[1], counts, "measured-bank") + assert counts["arrays"] and counts["geometries"] + report = dict( + schema="missioncore.elapsed-metadata-explanation/v1", + passed=True, raw_proof_sha256=sha(source / "equivalence.json"), + unchanged_numeric_image_artifacts=proof["artifact_count"] - 1, + measured_bank_physical_content_exact=True, comparison_counts=dict(counts), + proposal_timing_records=[len(t) for t in times], proposal_timings=times, + patch_elapsed_seconds=patch_times, manifest_elapsed_seconds=manifest_times, + verified_provenance_links=identities, + excluded_fields=[ + "search-proposals: tile_reports[i].seconds and .detectors (monotonic durations)", + "symbol-patches: seconds (monotonic duration)", + "observation-coverage: solver.seconds (monotonic duration)", + "native-geometry: seconds (monotonic duration)", + "bank: observation_inputs[/searchplan/search-proposals.json] (verified file hash)", + "bank: observation_inputs[/ortho/observation-coverage.json] (verified file hash)", + "bank: observation_inputs[/ortho/native-geometry/native-geometry.json] (verified hash)", + "bank: observation_identity (verified hash of all original observation_inputs)", + ], + unknown_differences_allowed=False, numeric_tolerance=None, artifacts_mutated=False, + model_or_acceptance_changed=False, + ) + Path("/out/metadata-explanation.json").write_text(json.dumps(report, indent=2)) + print("PHYSICAL_EVIDENCE_EXACT", json.dumps(dict(counts)), flush=True) + + +if __name__ == "__main__": + run() diff --git a/simulation/urban-plan-research/evaluation/geometry_metrics.py b/simulation/urban-plan-research/evaluation/geometry_metrics.py new file mode 100644 index 00000000..ad455746 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/geometry_metrics.py @@ -0,0 +1,52 @@ +"""Descriptive geometry metrics; these are not labeled accuracy measurements.""" +from collections import Counter + +import numpy as np +import shapely +from shapely.geometry import shape + + +def inspect(document): + rows = [(f, shape(f['geometry'])) for f in document['features']] + classes = sorted({f['properties']['class'] for f, _ in rows}) + result = dict(invalid_ids=[], nonfinite_ids=[], classes={}, + marking_subtypes=dict(Counter(f['properties'].get('subtype', 'unknown') + for f, _ in rows if f['properties']['class'] == 'road_marking')), + ground_truth_used=False) + for f, g in rows: + if g.is_empty or not g.is_valid: + result['invalid_ids'].append(f['id']) + coordinates = shapely.get_coordinates(g, include_z=g.has_z) + if not np.isfinite(coordinates).all(): + result['nonfinite_ids'].append(f['id']) + for cls in classes: + geometries = [shapely.force_2d(g) for f, g in rows + if f['properties']['class'] == cls and g.is_valid] + polygons = [g for g in geometries if g.geom_type in ('Polygon', 'MultiPolygon')] + union = shapely.union_all(polygons) + result['classes'][cls] = dict(features=len(geometries), + polygon_area_m2=float(sum(g.area for g in polygons)), + union_area_m2=float(union.area), + overlap_excess_m2=float(max(0, sum(g.area for g in polygons) - union.area)), + line_length_m=float(sum(g.length for g in geometries + if g.geom_type in ('LineString', 'MultiLineString'))), + holes=sum(len(p.interiors) for g in polygons + for p in (list(g.geoms) if g.geom_type == 'MultiPolygon' else [g]))) + return result + + +def difference(reference, candidate): + classes = {f['properties']['class'] for d in [reference, candidate] for f in d['features']} + result = {} + for cls in sorted(classes): + unions = [] + for doc in [reference, candidate]: + geometries = [shapely.force_2d(shape(f['geometry'])) for f in doc['features'] + if f['properties']['class'] == cls] + unions.append(shapely.union_all([g for g in geometries if g.is_valid])) + a, b = unions + delta = a.symmetric_difference(b) + result[cls] = dict(symmetric_difference_area_m2=float(delta.area), + symmetric_difference_length_m=float(delta.length), + union_equal=bool(a.equals(b))) + return result diff --git a/simulation/urban-plan-research/evaluation/probe_background_cause.py b/simulation/urban-plan-research/evaluation/probe_background_cause.py new file mode 100644 index 00000000..f7b16b24 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/probe_background_cause.py @@ -0,0 +1,248 @@ +"""Causal diagnostic on frozen rejected junctions, never a map producer. + +Change only the background operator. Preserve the original body coordinates, +readers, RGB, validity and the legacy contrast cut. A 2-D opening is an +experimental measurement, not a new acceptance rule. No search or fitting. +""" + +import gzip +import hashlib +import json +import pickle +import time +from pathlib import Path + +import cv2 +import numpy as np +import shapely +import stroke_observations +from beta_profiles import describe +from object_context import measure +from observation_cache import ObservationCache +from PIL import Image, ImageDraw +from scipy.ndimage import gaussian_filter1d +from shapely.geometry import mapping, shape + + +def digest(a): + return hashlib.sha256(a.tobytes()).hexdigest() + + +def qualify_operator(): + """A causal synthetic control, not an acceptance qualification.""" + yy, xx = np.mgrid[-60:61, -60:61] + base = np.full(xx.shape, 40, dtype=np.float32) + cases = {} + cases["empty"] = base.copy() + cases["straight"] = np.where(abs(xx) <= 2, 220, base).astype("float32") + cases["junction"] = np.where((abs(xx) <= 2) | (abs(yy) <= 2), 220, base).astype("float32") + cases["gap"] = np.where((abs(xx) <= 2) & (abs(yy) >= 9), 220, base).astype("float32") + cases["broad_bright_surface"] = np.where((abs(xx) <= 30) & (abs(yy) <= 30), 220, base).astype( + "float32" + ) + values = {} + for name, gray in cases.items(): + a = gray - cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((1, 35), np.uint8)) + b = gray - cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((35, 35), np.uint8)) + assert np.all(a[gray == 40] == 0) and np.all(b[gray == 40] == 0) + values[name] = dict(legacy_center=float(a[60, 60]), opening_2d_center=float(b[60, 60])) + assert values["junction"] == dict(legacy_center=0.0, opening_2d_center=180.0) + assert values["straight"] == dict(legacy_center=180.0, opening_2d_center=180.0) + for name in ["empty", "gap", "broad_bright_surface"]: + assert values[name] == dict(legacy_center=0.0, opening_2d_center=0.0) + return dict(passed=True, cases=values, real_world_accuracy_measured=False) + + +def support(mask, valid, contrast, cut, gray, background): + if not mask.any(): + return dict(samples=0) + return dict( + samples=int(mask.sum()), + valid=float(valid[mask].mean()), + paint=float((contrast[mask] > cut).mean()), + gray_median=float(np.median(gray[mask])), + background_median=float(np.median(background[mask])), + contrast_median=float(np.median(contrast[mask])), + ) + + +def probe(polygon, shared, object_region, reader, expected, output): + d = describe(polygon) + ts = np.arange(-d["length"] / 2 + 0.04, d["length"] / 2 - 0.04, 0.025) + ns = np.arange(-0.7, 0.701, 0.025) + normal = np.array([-d["axis"][1], d["axis"][0]]) + xy = d["origin"] + ts[:, None, None] * d["axis"] + ns[None, :, None] * normal + rgb, valid = reader(xy.reshape(-1, 2)) + rgb = rgb.reshape(len(ts), len(ns), 3).astype("uint8") + valid = valid.reshape(len(ts), len(ns)) + gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype("float32") + old_bg = cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((1, 35), np.uint8)) + old = gaussian_filter1d(np.maximum(gray - old_bg, 0), 0.8, axis=1) + core = abs(ns) <= max(0.025, min(0.04, d["width"] * 0.2)) + cut = max(15.0, 0.35 * float(np.median(np.median(old[:, core], axis=1)))) + body = np.broadcast_to(abs(ns) <= d["width"] / 2, gray.shape).copy() + body &= shapely.intersects_xy(polygon, xy[..., 0], xy[..., 1]) + joint = body & shapely.intersects_xy(shared, xy[..., 0], xy[..., 1]) + exterior = ~shapely.intersects_xy(object_region, xy[..., 0], xy[..., 1]) + assert np.array_equal((old[body] > cut), expected["paint"]) + assert np.array_equal(valid[body], expected["valid"]) + # Opening is erosion then dilation: 34 samples of context on each side + # avoid importing an artificial strip boundary into a 35x35 operator. + pad = 34 + + def extend(a): + return np.r_[a[0] - np.arange(pad, 0, -1) * 0.025, a, a[-1] + np.arange(1, pad + 1) * 0.025] + + et, en = extend(ts), extend(ns) + extended_xy = d["origin"] + et[:, None, None] * d["axis"] + en[None, :, None] * normal + extended_rgb, extended_valid = reader(extended_xy.reshape(-1, 2)) + extended_rgb = extended_rgb.reshape(len(et), len(en), 3).astype("uint8") + extended_valid = extended_valid.reshape(len(et), len(en)) + center = np.s_[pad:-pad, pad:-pad] + assert np.array_equal(extended_xy[center], xy) + assert np.array_equal(extended_rgb[center], rgb) + assert np.array_equal(extended_valid[center], valid) + extended_gray = cv2.cvtColor(extended_rgb, cv2.COLOR_RGB2GRAY).astype("float32") + extended_bg = cv2.morphologyEx(extended_gray, cv2.MORPH_OPEN, np.ones((35, 35), np.uint8)) + new_bg = extended_bg[center] + # Keep the same smoothing and crop as the legacy calculation. + new = gaussian_filter1d(np.maximum(gray - new_bg, 0), 0.8, axis=1) + # The final transverse Gaussian also reads three samples on either side. + context_valid = cv2.erode( + extended_valid.astype("uint8"), + np.ones((69, 75), np.uint8), + borderType=cv2.BORDER_CONSTANT, + borderValue=0, + )[center].astype(bool) + groups = { + "body": body, + "joint": joint, + "joint_with_valid_2d_context": joint & context_valid, + "body_with_valid_2d_context": body & context_valid, + "exterior": exterior, + "previously_dark_exterior": exterior & (old <= cut), + } + report = dict( + cut=cut, + original_geometry=mapping(polygon), + xy_sha256=digest(xy), + rgb_sha256=digest(rgb), + valid_sha256=digest(valid), + shared_samples_identical=True, + legacy_body_reproduced=True, + context_valid_in_joint=float(context_valid[joint].mean()) if joint.any() else None, + evidence={ + name: { + "legacy": support(mask, valid, old, cut, gray, old_bg), + "opening_2d": support(mask, valid, new, cut, gray, new_bg), + } + for name, mask in groups.items() + }, + ) + output.mkdir() + np.savez_compressed( + output / "observations.npz", + xy=xy, + rgb=rgb, + valid=valid, + gray=gray, + background_1d=old_bg, + background_2d=new_bg, + contrast_1d=old, + contrast_2d=new, + body=body, + joint=joint, + context_valid=context_valid, + ) + # A fixed physical margin around every joint, not a selected success crop. + if joint.any(): + ii, jj = np.where(joint) + crop = np.s_[ + max(0, ii.min() - 16) : min(len(ts), ii.max() + 17), + max(0, jj.min() - 16) : min(len(ns), jj.max() + 17), + ] + panels = [ + ("RGB", rgb[crop]), + ("background 1D", old_bg[crop]), + ("background 2D", new_bg[crop]), + ("contrast 1D", old[crop]), + ("contrast 2D", new[crop]), + ] + images = [] + for title, array in panels: + a = np.clip(array, 0, 255).astype("uint8") + image = Image.fromarray(a).convert("RGB") + pixels = np.asarray(image).copy() + edge = cv2.morphologyEx( + joint[crop].astype("uint8"), cv2.MORPH_GRADIENT, np.ones((3, 3), np.uint8) + ).astype(bool) + pixels[edge] = [255, 80, 80] + image = Image.fromarray(pixels).resize( + (image.width * 5, image.height * 5), Image.Resampling.NEAREST + ) + panel = Image.new("RGB", (image.width, image.height + 25), "black") + panel.paste(image, (0, 25)) + ImageDraw.Draw(panel).text((4, 6), title, fill="white") + images.append(panel) + sheet = Image.new( + "RGB", (sum(i.width for i in images), max(i.height for i in images)), "black" + ) + x = 0 + for image in images: + sheet.paste(image, (x, 0)) + x += image.width + sheet.save(output / "diagnostic.png") + return report + + +def run(): + out = Path("/out/background") + out.mkdir(exist_ok=False) + begin = time.monotonic() + synthetic = qualify_operator() + trace_path = Path("/trace/comparison/matrix-trace.json") + trace = json.loads(trace_path.read_text()) + raw = Path("/reference/run/marking_pass/measured-bank.pkl.gz").read_bytes() + bank = pickle.loads(gzip.decompress(raw)) + stroke_observations.initialize() + views = stroke_observations.views + views.inputs = ObservationCache(views.inputs, 6 * 1024**3) + reports = [] + for case, failure in enumerate(trace["failures"]): + shared = shape(failure["shared_geometry"]) + object_region = shapely.union_all([shape(m["geometry"]) for m in failure["members"]]) + record = dict(case=case, indices=failure["indices"], views=[]) + for member, index in enumerate(failure["indices"]): + r = bank["candidates"][index] + p = r["polygons"][0] + assert mapping(p) == mapping(shape(failure["members"][member]["geometry"])) + readers, used = views.readers(r["origin"], r["axis"]) + measured = measure(p, readers) + assert measured["legacy_evidence"] == failure["members"][member]["legacy_evidence"] + for view, reader in enumerate(readers): + name = f"case-{case:02d}-member-{member}-view-{view}" + report = probe( + p, shared, object_region, reader, measured["bodies"][view], out / name + ) + report.update(member=member, view=view, source_views=used[view], directory=name) + record["views"].append(report) + reports.append(record) + print("BACKGROUND", case + 1, "/", len(trace["failures"]), flush=True) + result = dict( + schema="missioncore.background-cause-probe/v1", + seconds=time.monotonic() - begin, + bank_sha256=hashlib.sha256(raw).hexdigest(), + trace_sha256=hashlib.sha256(trace_path.read_bytes()).hexdigest(), + fixed_cut=True, + map_produced=False, + production_admission_changed=False, + new_candidates=0, + independent_ground_truth=False, + synthetic=synthetic, + cases=reports, + ) + (out / "report.json").write_text(json.dumps(result, indent=2, allow_nan=False)) + + +if __name__ == "__main__": + run() diff --git a/simulation/urban-plan-research/evaluation/profile_frozen_assembly.py b/simulation/urban-plan-research/evaluation/profile_frozen_assembly.py new file mode 100644 index 00000000..2392eb35 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/profile_frozen_assembly.py @@ -0,0 +1,63 @@ +"""Locate repeated work on a frozen bank; profiled time is not a speed claim.""" + +import cProfile +import hashlib +import json +import runpy +import time +from pathlib import Path + + +def run(): + output = Path("/out") + profiler = cProfile.Profile() + begin = time.monotonic() + profiler.enable() + try: + runpy.run_path("/candidate/refine_markings.py", run_name="__main__") + finally: + profiler.disable() + profiler.dump_stats(str(output / "assembly-profile.pstats")) + rows = [] + for entry in profiler.getstats(): + code = entry.code + rows.append( + dict( + function=code if isinstance(code, str) else code.co_name, + file=None if isinstance(code, str) else code.co_filename, + line=None if isinstance(code, str) else code.co_firstlineno, + calls=entry.callcount, + recursive_calls=entry.reccallcount, + cumulative_seconds=entry.totaltime, + own_seconds=entry.inlinetime, + ) + ) + checks = {} + for name in [ + "full-map.json", + "marking-rows.json", + "finite-stroke-admission.json", + "configuration-bank.json", + ]: + actual = output / name + reference = Path("/reference/run/marking_pass") / name + checks[name] = dict( + exact=actual.read_bytes() == reference.read_bytes(), + actual_sha256=hashlib.sha256(actual.read_bytes()).hexdigest(), + reference_sha256=hashlib.sha256(reference.read_bytes()).hexdigest(), + ) + result = dict( + schema="missioncore.frozen-assembly-profile/v1", + seconds=time.monotonic() - begin, + profiling_enabled=True, + cold_pipeline=False, + checks=checks, + passed=all(c["exact"] for c in checks.values()), + functions=sorted(rows, key=lambda r: -r["cumulative_seconds"]), + ) + (output / "profile-report.json").write_text(json.dumps(result, indent=2)) + assert result["passed"], "Profiling changed frozen assembly results" + + +if __name__ == "__main__": + run() diff --git a/simulation/urban-plan-research/evaluation/qualify_control_tail.py b/simulation/urban-plan-research/evaluation/qualify_control_tail.py new file mode 100644 index 00000000..0b36cd45 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/qualify_control_tail.py @@ -0,0 +1,50 @@ +"""Reserve Worker and complete the frozen control tail in an owned sandbox.""" +from pathlib import Path +import base64 +import hashlib +import json +import subprocess +import sys +import uuid + +repo = Path(__file__).resolve().parents[3] +config = json.loads(Path(sys.argv[1]).read_text()) +session = config['session'] +if not session.startswith('pipeline-control-') or any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-' for c in session): + raise ValueError('Invalid session') +root = repo / '.runtime/simulation-qualifications' / session +root.mkdir(exist_ok=False) +worker = Path(__file__).with_name('run_control_tail.py').read_bytes() +(root/'worker.py').write_bytes(worker) +(root/'builder.py').write_bytes(Path(__file__).read_bytes()) +config['worker_sha256'] = hashlib.sha256(worker).hexdigest() +(root/'config.json').write_text(json.dumps(config,indent=2)) +sys.path.insert(0,str(repo/'src')) +from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue +queue = ObservatoryRecordedJobQueue(repo/'.runtime/mission-core', definitions=None) +owner = 'airun-' + uuid.uuid4().hex +queue.reserve_simulation(owner) +receipt = dict(owner=owner,state='reserved') +(root/'reservation.json').write_text(json.dumps(receipt)) +ssh = ['ssh','-T','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=12', + 'mission-gpu','D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -u -B -'] +code = 'import json,base64\nCONFIG=json.loads(base64.b64decode(' + repr(base64.b64encode(json.dumps(config).encode()).decode()) + '))\n' + worker.decode() +try: + p = subprocess.Popen(ssh,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,errors='replace') + p.stdin.write(code);p.stdin.close(); info=None + with (root/'execution.log').open('w') as log: + for line in p.stdout: + log.write(line);log.flush();print(line,end='',flush=True) + if line.startswith('COLLECTION '):info=json.loads(line[11:]) + if p.wait()!=0 or not info:raise RuntimeError('Control tail failed; see frozen evidence') + assert info['bytes'] < 20*1024**2 + target=root/'summary.json' + subprocess.run(['scp','-q','mission-gpu:'+info['path'].replace('\\','/'),str(target)],check=True) + assert hashlib.sha256(target.read_bytes()).hexdigest()==info['sha256'] + print('COLLECTED',root,flush=True) +finally: + check = subprocess.run(ssh,input="from pathlib import Path\nprint(Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"+session+"/active.json').exists())",capture_output=True,text=True,timeout=30) + if check.returncode==0 and check.stdout.strip()=='False': + queue.release_simulation(owner);receipt['state']='released' + else:receipt['state']='cleanup-unconfirmed' + (root/'reservation.json').write_text(json.dumps(receipt)) diff --git a/simulation/urban-plan-research/evaluation/qualify_execution_reuse.py b/simulation/urban-plan-research/evaluation/qualify_execution_reuse.py new file mode 100644 index 00000000..3f1d81cc --- /dev/null +++ b/simulation/urban-plan-research/evaluation/qualify_execution_reuse.py @@ -0,0 +1,58 @@ +"""Exact-output qualification of scheduling changes on one frozen real run. + +Reference outputs are read only after candidate execution. These benchmark +outputs never enter a subsequent cold run or a published urban map. +""" +from pathlib import Path +import hashlib,json,time,shutil + + +def run(root,modules,reference,expected_sha,marker,profile,runtime,artifact,run_container,write_json): + digest=lambda p:hashlib.sha256(p.read_bytes()).hexdigest() + assert digest(reference/'summary.json')==expected_sha + prior=json.loads((reference/'summary.json').read_text()) + assert prior['cold_run'] and prior['completed_stages']==30 + source=reference/'run';out=root/'execution-reuse';out.mkdir() + search=out/'search';search.mkdir() + env=dict(PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon',SCENE='scene', + OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='2',OBSERVATION_WORKERS='4', + HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HOME='/tmp/hf',TORCH_HOME='/tmp/torch') + started=time.monotonic() + run_container(marker,'parallel-extraction',profile['mapper_image'], + [(modules/'primary_search','/candidate',True),(source/'ortho','/ortho',True), + (source/'ortho/survey','/survey',True),(source/'full_plan','/evidence_plan',True),(search,'/out',False)], + ['-B','/candidate/extract_observations.py'],search,lambda:None,900,gpu=False,executable='python3', + environment=env,readonly=True,resources=dict(cpus=8,memory_gib=24)) + parallel_seconds=time.monotonic()-started + checks={} + for name in ['search-proposals.json','catalog-proposals.json','compact-seeds.json','crossing-seeds.json','observations.json']: + a=json.loads((source/'primary_search'/name).read_text());b=json.loads((search/name).read_text()) + # Timing is deliberately excluded; order, geometry, scores, source + # identities and candidate ownership must be exactly unchanged. + if isinstance(a,dict):a.pop('tile_reports',None);b.pop('tile_reports',None) + checks[name]=a==b + report=dict(reference=reference.name,reference_sha256=expected_sha,outputs_used_by_cold_run=False, + extraction=dict(seconds=parallel_seconds,files_equal=checks)) + write_json(out/'execution-qualification.json',report) + assert all(checks.values()),'Parallel extraction changed candidate evidence' + symbols=out/'symbols';symbols.mkdir() + shutil.copy2(source/'primary_search/symbol-patches.json',symbols/'symbol-patches.json') + started=time.monotonic() + run_container(marker,'semantic-lifecycle',profile['semantic_image'], + [(modules/'primary_search','/candidate',True),(artifact,'/release',True), + (runtime/profile['semantic_model'],'/assets',True),(symbols,'/out',False), + (source/'primary_search/symbol-patches','/out/symbol-patches',True)], + ['-B','/candidate/semantic_symbols.py'],symbols,lambda:None,900,gpu=True,executable='python3', + environment=env,readonly=True) + semantic_seconds=time.monotonic()-started + a=json.loads((source/'primary_search/symbol-semantics.json').read_text()) + b=json.loads((symbols/'symbol-semantics.json').read_text()) + same=a['records']==b['records'] + hashes=all(r['sha256'] is None or digest(symbols/'symbol-masks'/(r['id']+'.npz'))==r['sha256'] for r in b['records']) + report['semantics']=dict(seconds=semantic_seconds,patches=len(b['records']),records_equal=same,masks_sha256_verified=hashes, + cuda_peak_allocated_bytes=b.get('cuda_peak_allocated_bytes'),host_peak_rss_bytes=b.get('host_peak_rss_bytes')) + report['passed']=all(checks.values()) and same and hashes + write_json(out/'execution-qualification.json',report) + assert report['passed'],'Semantic scheduling changed masks, classes or scores' + print('EXACT_EXECUTION_QUALIFIED',json.dumps(report),flush=True) + return report diff --git a/simulation/urban-plan-research/evaluation/qualify_shared_survey.py b/simulation/urban-plan-research/evaluation/qualify_shared_survey.py new file mode 100644 index 00000000..610a7ec0 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/qualify_shared_survey.py @@ -0,0 +1,116 @@ +"""Run frozen control/shared semantics with the Core's exclusive GPU owner.""" + +import base64 +import hashlib +import json +import subprocess +import sys +import uuid +from pathlib import Path + +repo = Path(__file__).resolve().parents[3] +module = repo / "simulation/urban-plan-research" +config = json.loads(Path(sys.argv[1]).read_text()) +session = config["session"] +if not session.startswith("shared-survey-") or any( + c not in "abcdefghijklmnopqrstuvwxyz0123456789-" for c in session +): + raise ValueError("Invalid qualification session") +root = repo / ".runtime/simulation-qualifications" / session +root.mkdir(exist_ok=False) +aliases = {p.name: p for p in (module / "shared_survey").glob("*.py")} +aliases["legacy_ortho_segment.py"] = module / "orthophoto/ortho_segment.py" +aliases["legacy_semantic_layers.py"] = module / "full_plan/semantic_layers.py" +aliases["ortho_windows.py"] = module / "orthophoto/ortho_windows.py" +files = {} +for name, path in aliases.items(): + data = path.read_bytes() + files[name] = dict( + source=path.relative_to(repo).as_posix(), + sha256=hashlib.sha256(data).hexdigest(), + content=base64.b64encode(data).decode(), + ) +config["files"] = files +worker = module / "evaluation/run_shared_survey_worker.py" +worker_bytes = worker.read_bytes() +(root / "worker.py").write_bytes(worker_bytes) +(root / "builder.py").write_bytes(Path(__file__).read_bytes()) +config["worker_sha256"] = hashlib.sha256(worker_bytes).hexdigest() +(root / "source-manifest.json").write_text( + json.dumps({k: {n: v[n] for n in ["source", "sha256"]} for k, v in files.items()}, indent=2) +) +(root / "config.json").write_text( + json.dumps({k: v for k, v in config.items() if k != "files"}, indent=2) +) +sys.path.insert(0, str(repo / "src")) +from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue # noqa: E402 + +queue = ObservatoryRecordedJobQueue(repo / ".runtime/mission-core", definitions=None) +owner = "airun-" + uuid.uuid4().hex +queue.reserve_simulation(owner) +receipt = dict(owner=owner, state="reserved") +(root / "reservation.json").write_text(json.dumps(receipt)) +ssh = [ + "ssh", + "-T", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ConnectTimeout=15", + "mission-gpu", + "D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -", +] +code = ( + "import json,base64\nCONFIG=json.loads(base64.b64decode(" + + repr(base64.b64encode(json.dumps(config).encode()).decode()) + + "))\n" + + worker_bytes.decode() +) +try: + p = subprocess.Popen( + ssh, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + errors="replace", + ) + p.stdin.write(code) + p.stdin.close() + info = None + with (root / "execution.log").open("w") as log: + for line in p.stdout: + log.write(line) + log.flush() + print(line, end="", flush=True) + if line.startswith("COLLECTION "): + info = json.loads(line[11:]) + if p.wait() != 0 or not info: + raise RuntimeError("Qualification failed; inspect owned evidence") + assert info["bytes"] < 10 * 1024**2 + summary = root / "summary.json" + subprocess.run(["scp", "-q", "mission-gpu:" + info["path"], str(summary)], check=True) + assert hashlib.sha256(summary.read_bytes()).hexdigest() == info["sha256"] + print("COLLECTED", root, flush=True) +finally: + try: + check = subprocess.run( + ssh, + input="from pathlib import Path\nprint(Path(" + "'C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/" + + session + + "/active.json').exists())", + text=True, + capture_output=True, + timeout=30, + ) + if check.returncode == 0 and check.stdout.strip() == "False": + queue.release_simulation(owner) + receipt["state"] = "released" + else: + receipt["state"] = "cleanup-unconfirmed" + except subprocess.SubprocessError: + receipt["state"] = "cleanup-unconfirmed" + (root / "reservation.json").write_text(json.dumps(receipt)) diff --git a/simulation/urban-plan-research/evaluation/qualify_stroke_execution.py b/simulation/urban-plan-research/evaluation/qualify_stroke_execution.py new file mode 100644 index 00000000..eada75a2 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/qualify_stroke_execution.py @@ -0,0 +1,31 @@ +"""Execute all measured axes concurrently; compare the complete serial result.""" +from pathlib import Path +import json,time +from infrastructure_sources import checksum +from infrastructure_containers import run_container +from local_state import write_json + + +def run(root,modules,reference,expected_sha,marker,profile): + assert checksum(reference/'summary.json')==expected_sha + prior=json.loads((reference/'summary.json').read_text()) + observations=Path(prior.get('observation_run',str(reference/'run'))) + assert observations.resolve().is_relative_to(reference.parent.resolve()) + source=reference/'run';out=root/'stroke-execution';out.mkdir() + mounts=[(modules/'marking_pass','/candidate',True),(out,'/out',False), + (observations/'ortho','/ortho',True),(observations/'ortho/survey','/survey',True), + (observations/'full_plan','/evidence_plan',True),(observations/'primary_search','/searchplan',True), + (observations/'primary_search','/primary',True),(source/'bicycles','/fullplan',True)] + start=time.monotonic() + run_container(marker,'parallel-strokes',profile['mapper_image'],mounts,['-B','/candidate/refine_markings.py'],out,lambda:None,1200, + gpu=False,executable='python3',environment=dict(PYTHONPATH='/candidate:/candidate/mapping',SCENE='scene',OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='2',STROKE_WORKERS='4'),readonly=True,resources=dict(cpus=8,memory_gib=24)) + seconds=time.monotonic()-start + checks={name:json.loads((out/name).read_text())==json.loads((source/'marking_pass'/name).read_text()) + for name in ['full-map.json','marking-rows.json','finite-stroke-admission.json']} + a=json.loads((out/'marking-report.json').read_text());b=json.loads((source/'marking_pass/marking-report.json').read_text()) + a.pop('seconds');b.pop('seconds');checks['marking-report.json']=a==b + report=dict(reference=reference.name,reference_sha256=expected_sha,seconds=seconds,checks=checks,passed=all(checks.values()),outputs_used_by_cold_run=False) + write_json(out/'execution-qualification.json',report) + print('STROKE_EXECUTION_QUALIFIED',json.dumps(report),flush=True) + assert report['passed'],'Parallel measurements changed geometry or admission evidence' + return report diff --git a/simulation/urban-plan-research/evaluation/qualify_systematic.py b/simulation/urban-plan-research/evaluation/qualify_systematic.py new file mode 100644 index 00000000..fd8a63c2 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/qualify_systematic.py @@ -0,0 +1,54 @@ +"""Freeze a candidate source closure, reserve Worker, run and collect evidence.""" +from pathlib import Path +import base64,hashlib,json,subprocess,sys,uuid,ast +repo=Path(__file__).resolve().parents[3];module=repo/'simulation/urban-plan-research' +config=json.loads(Path(sys.argv[1]).read_text());session=config['session'] +if not session.startswith('systematic-')or any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-'for c in session):raise ValueError('Invalid session') +root=repo/'.runtime/simulation-qualifications'/session;root.mkdir(exist_ok=False) +definition=json.loads((module/'systematic/definition.json').read_text());paths={v for g in definition['groups']for v in g['files'].values()} +paths.add('evaluation/contract_preflight.py') +paths.add('evaluation/execution_profile.py') +paths.add('evaluation/qualify_execution_reuse.py') +paths.add('evaluation/run_frozen_tail.py') +paths.add('evaluation/qualify_stroke_execution.py') +paths.add('systematic/qualify_primary_plan.py') +paths.update('pipeline/'+p for p in ['config-ortho.json','config-mv.json','worker-profile.json']) +files={} +for relative in sorted(paths): + path=module/relative + assert not path.is_symlink() and path.resolve().is_relative_to(module.resolve()) + data=path.read_bytes() + if path.suffix=='.py':ast.parse(data) + files['simulation/urban-plan-research/'+relative]=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode()) +for relative in ['simulation/ai-polygon/infrastructure_containers.py','simulation/ai-polygon/infrastructure_pipeline.py']: + data=(repo/relative).read_bytes();ast.parse(data) + files[relative]=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode()) +data=(module/'systematic/definition.json').read_bytes() +files['simulation/urban-plan-research/pipeline/definition.json']=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode()) +config['files']=files +worker=Path(__file__).with_name('run_systematic_worker.py').read_bytes();config['worker_sha256']=hashlib.sha256(worker).hexdigest() +(root/'worker.py').write_bytes(worker);(root/'builder.py').write_bytes(Path(__file__).read_bytes()) +(root/'config.json').write_text(json.dumps({k:v for k,v in config.items()if k!='files'},indent=2)) +(root/'source-manifest.json').write_text(json.dumps({k:v['sha256']for k,v in files.items()},indent=2)) +sys.path.insert(0,str(repo/'src')) +from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue +queue=ObservatoryRecordedJobQueue(repo/'.runtime/mission-core',definitions=None);owner='airun-'+uuid.uuid4().hex +queue.reserve_simulation(owner);receipt=dict(owner=owner,state='reserved');(root/'reservation.json').write_text(json.dumps(receipt)) +ssh=['ssh','-T','-o','BatchMode=yes','-o','StrictHostKeyChecking=yes','-o','ConnectTimeout=15','-o','ServerAliveInterval=15','-o','ServerAliveCountMax=8','mission-gpu','D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -u -B -'] +code='import json,base64\nCONFIG=json.loads(base64.b64decode('+repr(base64.b64encode(json.dumps(config).encode()).decode())+'))\n'+worker.decode() +try: + p=subprocess.Popen(ssh,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True,errors='replace');p.stdin.write(code);p.stdin.close();info=None + with (root/'execution.log').open('w')as log: + for line in p.stdout: + log.write(line);log.flush();print(line,end='',flush=True) + if line.startswith('COLLECTION '):info=json.loads(line[11:]) + if p.wait()!=0 or not info:raise RuntimeError('Candidate failed; see frozen evidence') + assert info['bytes']<30*1024**2 + target=root/'summary.json';subprocess.run(['scp','-q','mission-gpu:'+info['path'].replace('\\','/'),str(target)],check=True) + assert hashlib.sha256(target.read_bytes()).hexdigest()==info['sha256'] + print('COLLECTED',root,flush=True) +finally: + check=subprocess.run(ssh,input="from pathlib import Path\nprint(Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"+session+"/active.json').exists())",text=True,capture_output=True,timeout=30) + if check.returncode==0 and check.stdout.strip()=='False':queue.release_simulation(owner);receipt['state']='released' + else:receipt['state']='cleanup-unconfirmed' + (root/'reservation.json').write_text(json.dumps(receipt)) diff --git a/simulation/urban-plan-research/evaluation/qualify_topdown.py b/simulation/urban-plan-research/evaluation/qualify_topdown.py new file mode 100644 index 00000000..6b959f8a --- /dev/null +++ b/simulation/urban-plan-research/evaluation/qualify_topdown.py @@ -0,0 +1,127 @@ +"""Build a bounded import closure and run one owned Worker006 qualification. + +Usage: repository .venv/bin/python evaluation/qualify_topdown.py CONFIG.json +Config names a fresh session, pinned worker release/definition and development +scene observation paths. Optional symbols path replays saved inference inputs. +""" +from pathlib import Path +import ast +import base64 +import hashlib +import json +import subprocess +import sys +import tarfile +import uuid + +repo = Path(__file__).resolve().parents[3] +module = repo/'simulation/urban-plan-research' +config = json.loads(Path(sys.argv[1]).read_text()) +session = config['session'] +if not session.startswith('topdown-') or any(c not in 'abcdefghijklmnopqrstuvwxyz0123456789-' for c in session): + raise ValueError('Invalid qualification session') +root = repo/'.runtime/simulation-qualifications'/session +root.mkdir(exist_ok=False) +definition = json.loads((module/'pipeline/definition.json').read_text()) +aliases = next(g for g in definition['groups'] if g['group'] == 'uniform_arrows')['files'].copy() +aliases.update({p.name: p.relative_to(module).as_posix() for p in (module/'topdown').glob('*.py')}) +pending = ['verify_topdown.py','reconstruct_topdown.py','prepare_topdown.py','semantic_symbols.py','test_topdown.py','merge_arrow_artwork.json'] +if any(s.get('render_native_geometry') or s.get('render_parallel_observations') for s in config['scenes']): + pending.append('render_native_geometry.py') +if config.get('audit') or any(s.get('audit') for s in config['scenes']): + pending.append('audit_topdown.py') +if any(s.get('contract_audit') for s in config['scenes']): + pending.append('audit_contract.py') +if any(s.get('assemble_from') for s in config['scenes']): + pending.append('assemble_reviewed_state.py') +if any(s.get('conditional_contract_audit') for s in config['scenes']): + pending.append('conditional_contract_audit.py') +if any(s.get('pose_domain_audit') for s in config['scenes']): + pending.append('pose_domain_audit.py') +if any(s.get('endpoint_cause_audit') for s in config['scenes']): + pending.append('endpoint_cause_audit.py') +if any(s.get('depth_audit') for s in config['scenes']): + pending.append('depth_audit.py') +if any(s.get('feasibility_audit') for s in config['scenes']): + pending.append('feasibility_audit.py') +if config.get('camera_tests'): + pending.append('test_orthographic_colour.py') +if config.get('retire_mapper_builds'): + aliases['retire_mapper_builds.py']='evaluation/retire_mapper_builds.py' + pending.append('retire_mapper_builds.py') +if config.get('queue_canary'): + aliases.update({'queue_worker_canary.py':'evaluation/queue_worker_canary.py', + 'queue_persistence.py':'../../src/k1link/simulation/ai_polygon/worlds.py', + 'infrastructure_jobs.py':'../../src/k1link/simulation/ai_polygon/infrastructure_jobs.py', + 'infrastructure_progress.py':'../../src/k1link/simulation/ai_polygon/infrastructure_progress.py'}) + pending.extend(['queue_worker_canary.py','queue_persistence.py','infrastructure_jobs.py','infrastructure_progress.py']) +files = {} +while pending: + name = pending.pop() + if name in files: + continue + path = module/aliases[name]; data = path.read_bytes() + files[name] = dict(source=path.relative_to(module).as_posix(), sha256=hashlib.sha256(data).hexdigest(), + content=base64.b64encode(data).decode()) + if path.suffix == '.py': + for node in ast.walk(ast.parse(data)): + imports = ([node.module] if isinstance(node, ast.ImportFrom) and node.module + else [a.name for a in node.names] if isinstance(node, ast.Import) else []) + for imported in imports: + dependency = imported.split('.')[0]+'.py' + if dependency in aliases: + pending.append(dependency) +for spec in config['scenes']: + if spec.get('confirmed_reference_path'): + data=Path(spec.pop('confirmed_reference_path')).read_bytes() + spec['confirmed_reference']=dict(sha256=hashlib.sha256(data).hexdigest(),content=base64.b64encode(data).decode()) +config['files'] = files +builder_bytes=Path(__file__).read_bytes() +worker_bytes=(module/'evaluation/run_topdown_worker.py').read_bytes() +(root/'builder.py').write_bytes(builder_bytes);(root/'worker.py').write_bytes(worker_bytes) +config['builder_sha256'] = hashlib.sha256(builder_bytes).hexdigest() +config['worker_sha256'] = hashlib.sha256(worker_bytes).hexdigest() +(root/'source-manifest.json').write_text(json.dumps({k:{n:v[n] for n in ['source','sha256']} for k,v in files.items()}, indent=2)) +(root/'config.json').write_text(json.dumps({k:v for k,v in config.items() if k != 'files'}, indent=2)) +sys.path.insert(0, str(repo/'src')) +from k1link.observatory.recorded_jobs import ObservatoryRecordedJobQueue +queue = ObservatoryRecordedJobQueue(repo/'.runtime/mission-core', definitions=None) +owner = 'airun-'+uuid.uuid4().hex +queue.reserve_simulation(owner) +receipt = dict(owner=owner, state='reserved') +(root/'reservation.json').write_text(json.dumps(receipt)) +ssh = ['ssh', '-T', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', 'mission-gpu', + 'D:/NDC_MISSIONCORE/runtime/simulation/isaac-sim-6.1.0/kit/python/python.exe -'] +worker = module/'evaluation/run_topdown_worker.py' +code = 'import json,base64\nCONFIG=json.loads(base64.b64decode('+repr(base64.b64encode(json.dumps(config).encode()).decode())+'))\n'+worker_bytes.decode() +try: + p = subprocess.Popen(ssh, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, errors='replace') + p.stdin.write(code); p.stdin.close(); info = None + with (root/'execution.log').open('w') as log: + for line in p.stdout: + log.write(line); log.flush(); print(line, end='', flush=True) + if line.startswith('COLLECTION '): + info = json.loads(line[11:]) + if p.wait() != 0 or not info: + raise RuntimeError('Worker qualification failed; inspect execution.log') + assert info['bytes'] < 100*1024**2 + archive = root/'evidence.tgz' + subprocess.run(['scp', '-q', 'mission-gpu:'+info['path'], str(archive)], check=True) + assert hashlib.sha256(archive.read_bytes()).hexdigest() == info['sha256'] + evidence = root/'evidence'; evidence.mkdir() + with tarfile.open(archive) as tar: + for member in tar.getmembers(): + assert member.isfile() and (evidence/member.name).resolve().is_relative_to(evidence) + tar.extractall(evidence, filter='data') + for name, digest in json.loads((evidence/'collection.json').read_text()).items(): + assert hashlib.sha256((evidence/name).read_bytes()).hexdigest() == digest + print('COLLECTED', root, flush=True) +finally: + check = subprocess.run(ssh, input="from pathlib import Path\nprint(Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/"+session+"/active.json').exists())", + text=True, capture_output=True, timeout=30) + if check.returncode == 0 and check.stdout.strip() == 'False': + queue.release_simulation(owner); receipt['state'] = 'released' + else: + receipt['state'] = 'cleanup-unconfirmed' + (root/'reservation.json').write_text(json.dumps(receipt)) diff --git a/simulation/urban-plan-research/evaluation/queue_worker_canary.py b/simulation/urban-plan-research/evaluation/queue_worker_canary.py new file mode 100644 index 00000000..b8350f61 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/queue_worker_canary.py @@ -0,0 +1,166 @@ +"""Real bounded Docker lifecycle with the candidate durable FIFO, isolated from operator jobs.""" + +import hashlib +import importlib.util +import json +import sys +import time +from pathlib import Path + + +def run(root, sources, release, profile): + from infrastructure_containers import docker, run_container + from infrastructure_preparer import reconcile + from local_state import write_json + + package = "k1link.simulation.ai_polygon." + for name in ["infrastructure_progress", "infrastructure_jobs"]: + spec = importlib.util.spec_from_file_location(package + name, sources / (name + ".py")) + mod = importlib.util.module_from_spec(spec) + sys.modules[package + name] = mod + spec.loader.exec_module(mod) + candidate = sys.modules[package + "infrastructure_jobs"] + candidate.provider_identity = lambda: "f" * 64 + # Load the exact Core atomic-write function without importing its unrelated + # Gaussian/Numpy reader on the native Windows coordinator. No I/O mock. + import ast + import os + import uuid + + persistence = sources / "queue_persistence.py" + tree = ast.parse(persistence.read_text(encoding="utf-8")) + function = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "write_json" + ) + namespace = dict(Path=Path, json=json, os=os, uuid4=uuid.uuid4) + exec(compile(ast.Module(body=[function], type_ignores=[]), str(persistence), "exec"), namespace) + candidate.write_json = namespace["write_json"] + store = candidate.InfrastructureJobs(root / "data") + rows = [ + store.request( + dict( + world_id="qualification-" + str(i), + sha256=format(i, "064x"), + collider_sha256=None, + local_scene={"fixture": True}, + ) + ) + for i in range(1, 21) + ] + marker = root / "queue-active.json" + events = [] + cancelled = False + + class Lease: + owner = None + + def reserve_simulation(self, owner): + assert self.owner in (None, owner) + self.owner = owner + + lease = Lease() + + class Client: + instance = "qualification-worker" + + def request(self, path, body): + row = store.update(path.rsplit("/", 1)[-1], body, self.instance) + if body.get("action") == "release": + assert lease.owner == "aicache-" + row["key"] + lease.owner = None + return row + + client = Client() + store.cancel(rows[7]["key"]) + for i, expected in enumerate(rows): + if i == 7: + continue + row = store.pending() + assert row["key"] == expected["key"] + key = row["key"] + claimed = store.dispatch(client.instance, lease, "f" * 64) + assert claimed["key"] == key + out = root / str(i) + out.mkdir() + write_json(marker, dict(key=key, owner=client.instance, containers=[])) + + def pulse(i=i, store=store, key=key): + nonlocal cancelled + if i == 1 and not cancelled: + store.cancel(key) + cancelled = True + store.update( + key, dict(action="progress", phase="survey", completed=0, total=1), client.instance + ) + + start = time.monotonic() + outcome = "ready" + failure_type = None + try: + # Failure and cancellation use actual containers, no inferred release. + code = ( + "raise SystemExit(7)" + if i == 0 + else "import time; time.sleep(30)" + if i in (1, 3) + else "print('QUEUE_OK')" + ) + run_container( + marker, + "queue-canary", + profile["mapper_image"], + [], + ["-B", "-c", code], + out, + pulse, + 0.5 if i == 3 else 60, + gpu=False, + executable="python3", + readonly=True, + ) + store.update(key, dict(action="complete", result={}), client.instance) + except (RuntimeError, TimeoutError) as exc: + failure_type = type(exc).__name__ + assert i in (0, 1, 3) + if i == 0: + assert json.loads((out / "queue-canary-exit.json").read_text())["ExitCode"] == 7 + if i == 1: + assert store.get(key).get("cancel_requested") + if i == 3: + assert isinstance(exc, TimeoutError) + store.update(key, dict(action="fail"), client.instance) + outcome = "cancelled" if i == 1 else "failed" + finally: + assert store.pending()["key"] == key + reconcile(client, marker) + assert store.get(key)["released"] and not marker.exists() and lease.owner is None + assert not docker( + "ps", "-aq", "--filter", "label=com.nodedc.analysis=" + key + ).stdout.strip() + events.append( + dict( + sequence=i + 1, + key=key, + status=outcome, + failure_type=failure_type, + seconds=time.monotonic() - start, + containers_remaining=0, + ) + ) + if i == 2: + store = candidate.InfrastructureJobs(root / "data") + assert store.pending() is None + report = dict( + submitted=20, + waiting_cancelled=1, + events=events, + finished=True, + persistence_source_sha256=hashlib.sha256(persistence.read_bytes()).hexdigest(), + scope=( + "isolated queue store with real bounded Worker containers; no operator maps or requests" + ), + after_failure_next=events[1]["sequence"] == 2, + after_cancel_next=events[2]["sequence"] == 3, + ) + write_json(root / "queue-canary.json", report) + print("QUEUE_CANARY", json.dumps(report), flush=True) diff --git a/simulation/urban-plan-research/evaluation/render_spatial_control.py b/simulation/urban-plan-research/evaluation/render_spatial_control.py new file mode 100644 index 00000000..19361b02 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/render_spatial_control.py @@ -0,0 +1,106 @@ +"""Project a qualified map onto predeclared, hash-pinned Gaussian observations.""" + +import hashlib +import json +from collections import Counter +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import shapely +from fit_scene import project +from matplotlib.lines import Line2D +from PIL import Image +from shapely.geometry import box, shape + +COLORS = { + "road_boundary": "#ff981f", + "pedestrian_boundary": "#00e5a8", + "pedestrian_area": "#00e5a8", + "building_facade": "#52a8ff", + "road_marking": "#fff02a", +} + + +def sha(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def draw(ax, geometry, camera, scale, color): + if geometry.geom_type == "Polygon": + for ring in [geometry.exterior, *geometry.interiors]: + uv = (project(np.asarray(ring.coords), camera) + 0.5) * scale - 0.5 + ax.plot(uv[:, 0], uv[:, 1], color=color, linewidth=0.8) + elif geometry.geom_type in {"LineString", "LinearRing"}: + uv = (project(np.asarray(geometry.coords), camera) + 0.5) * scale - 0.5 + ax.plot(uv[:, 0], uv[:, 1], color=color, linewidth=0.8) + else: + for part in getattr(geometry, "geoms", []): + draw(ax, part, camera, scale, color) + + +def run(): + root, output = Path("/control"), Path("/out") + controls = json.loads((root / "control.json").read_text()) + result = json.loads((root / "final-map.json").read_text()) + features = [(f, shape(f["geometry"])) for f in result["features"]] + records = [] + for item in controls["controls"]: + name = item["source_tile"] + camera_path = Path("/controlsource/ortho/survey") / name / "top.geometry.npz" + assert sha(camera_path) == item["camera_sha256"] + with np.load(camera_path) as arrays: + camera = {key: arrays[key] for key in arrays.files} + domain = box(*item["bounds_xy"][0], *item["bounds_xy"][1]) + selected = [(f, g) for f, g in features if shapely.force_2d(g).intersects(domain)] + counts = Counter( + f["properties"].get("subtype", f["properties"]["class"]) for f, _ in selected + ) + fig, axes = plt.subplots(2, 2, figsize=(12, 12), squeeze=False) + for row, kind in enumerate(["ground", "context"]): + image_path = Path("/controlsource/ortho/evidence") / (name + "." + kind + ".png") + assert sha(image_path) == item["files"][kind]["sha256"] + with Image.open(image_path) as original: + image = original.convert("RGB") + image.thumbnail((1024, 1024), Image.Resampling.LANCZOS) + pixels = np.asarray(image).copy() + image.close() + h, w = pixels.shape[:2] + scale = w / camera["alpha"].shape[1] + for column in [0, 1]: + ax = axes[row, column] + ax.imshow(pixels) + ax.set_xlim(-0.5, w - 0.5) + ax.set_ylim(h - 0.5, -0.5) + ax.axis("off") + ax.set_title(kind + (" / original" if column == 0 else " / qualified map")) + for feature, geometry in selected: + color = COLORS.get(feature["properties"]["class"], "white") + draw(axes[row, 1], geometry, camera, scale, color) + fig.suptitle("Frozen control " + item["control_id"] + " / " + name) + fig.legend( + handles=[Line2D([0], [0], color=color, label=kind) for kind, color in COLORS.items()], + loc="lower center", ncol=3, + ) + fig.tight_layout(rect=(0, 0.05, 1, 0.97)) + target = output / (item["control_id"] + ".png") + fig.savefig(target, dpi=130) + plt.close(fig) + records.append(dict( + control_id=item["control_id"], source_tile=name, bounds_xy=item["bounds_xy"], + feature_ids=[f["id"] for f, _ in selected], counts=dict(counts), + camera_sha256=sha(camera_path), image_sha256=sha(target), + )) + (output / "review.json").write_text(json.dumps(dict( + schema="missioncore.frozen-spatial-review/v1", controls=records, + source_map_sha256=sha(root / "final-map.json"), + selection_manifest_sha256=sha(root / "control.json"), + geometry_mutated=False, evaluation_only=True, independent_ground_truth=False, + ), indent=2)) + + +if __name__ == "__main__": + run() diff --git a/simulation/urban-plan-research/evaluation/retire_mapper_builds.py b/simulation/urban-plan-research/evaluation/retire_mapper_builds.py new file mode 100644 index 00000000..4d0b44b0 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/retire_mapper_builds.py @@ -0,0 +1,48 @@ +"""Retire duplicate compiler build caches after a qualified runtime is retained.""" + +import hashlib +import json +import shutil +from pathlib import Path + + +def run(receipt_path, sessions, destination): + receipt_path = Path(receipt_path) + base = receipt_path.parents[2] + receipt = json.loads(receipt_path.read_text(encoding="utf-8")) + retained = receipt_path.parent / "gsplat_cuda.so" + digest = hashlib.sha256(retained.read_bytes()).hexdigest() + assert digest == receipt["compiled"]["sha256"] + retired = [] + for session in sessions: + assert session in ( + "topdown-performance-20261016093055", + "topdown-performance-20261016093417", + ) + root = base / session + assert root != receipt_path.parent.parent and not (root / "active.json").exists() + manifest = json.loads((root / "manifest.json").read_text(encoding="utf-8")) + assert manifest["session"] == session + assert manifest["images"]["mapper_image"] == receipt["base_image"] + binary = root / "mapper-runtime/gsplat_cuda.so" + assert hashlib.sha256(binary.read_bytes()).hexdigest() == digest + cache = root / "mapper-runtime/extensions" + cache_bytes = sum(p.stat().st_size for p in cache.rglob("*") if p.is_file()) + retired.append( + dict( + session=session, + duplicate_binary_sha256=digest, + bytes=binary.stat().st_size + cache_bytes, + ) + ) + if cache.exists(): + shutil.rmtree(cache) + binary.unlink() + result = dict( + retained_binary=str(retained), + retained_image=receipt["image"], + retired=retired, + historical_manifests_and_logs_retained=True, + ) + destination.write_text(json.dumps(result, indent=2), encoding="utf-8") + return result diff --git a/simulation/urban-plan-research/evaluation/run_control_tail.py b/simulation/urban-plan-research/evaluation/run_control_tail.py new file mode 100644 index 00000000..81fa1520 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/run_control_tail.py @@ -0,0 +1,137 @@ +"""Frozen, isolated completion of a cancelled control. Never a cold-run claim.""" +from pathlib import Path +import datetime +import hashlib +import json +import shutil +import sys +import time + +CONFIG = globals()['CONFIG'] +sys.stdout.reconfigure(encoding='utf-8') +runtime = Path('D:/NDC_MISSIONCORE/runtime/simulation') +release = runtime / 'releases' / ('ai-polygon-' + CONFIG['release']) +original = Path(CONFIG['original_job']) +root = Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications') / CONFIG['session'] +assert not root.exists() +assert not list((runtime / 'state').glob('*active.json')) +assert shutil.disk_usage(root.parent).free > 40 * 1024**3 +sys.path[:0] = [str(release / 'simulation/ai-polygon')] +from infrastructure_containers import run_container, cleanup +from infrastructure_pipeline import SEMANTIC_STAGES, output_inventory +from infrastructure_sources import checksum +from local_state import write_json + +module = release / 'simulation/urban-plan-research' +definition_path = module / 'pipeline/definition.json' +assert checksum(definition_path) == CONFIG['definition_sha256'] +definition = json.loads(definition_path.read_text()) +profile = json.loads((module / 'pipeline/worker-profile.json').read_text()) +source_manifest = json.loads((original / 'source-manifest.json').read_text()) +assert source_manifest['snapshot'] == CONFIG['snapshot'] +modules = original / 'modules' / source_manifest['snapshot'] +groups = definition['groups'] +start = next(i for i, g in enumerate(groups) if g['group'] == 'uniform_fixed_refit') +assert [g['group'] for g in groups[start:]] == CONFIG['tail_groups'] +for group in groups: + for alias, relative in group['files'].items(): + assert checksum(modules / group['group'] / alias) == source_manifest['files'][relative] +root.mkdir() +marker = root / 'active.json' +write_json(marker, dict(key=hashlib.sha256(CONFIG['session'].encode()).hexdigest(), + owner=CONFIG['session'], containers=[])) +write_json(root / 'manifest.json', CONFIG | dict(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), + reuse_scope='Immutable completed prefix; fresh remaining control stages', + published=False, cold_run=False)) +locations = {g['group']: original / g['group'] for g in groups[:start] if (original / g['group']).exists()} +previous = original / 'zigzag_terminals' +source = json.loads((original / 'request.json').read_text())['source'] +package = runtime / 'state/infrastructure-sources' / source['adapter_key'] +assert checksum(package / source['ply']) == source['sha256'] +journal = [] +inputs = {} + +def frozen(path): + """Bind tree content before first use; don't copy or mutate the saved prefix.""" + if path.is_file(): + inputs[str(path)] = checksum(path) + else: + for p in path.rglob('*'): + if p.is_file() and p.suffix in {'.json', '.npz', '.png'}: + inputs.setdefault(str(p), checksum(p)) + +try: + for group in groups[start:]: + name = group['group'] + out = root / name + out.mkdir() + if (previous / 'crosswalk-standard-check.json').exists(): + shutil.copyfile(previous / 'crosswalk-standard-check.json', out / 'crosswalk-standard-check.json') + for stage in group['stages']: + mounts = [(modules / name, '/candidate', True), (package, '/input', True), + (original / 'base-survey', '/base_survey', True), + (original / 'ortho', '/ortho', True), (original / 'ortho/survey', '/survey', True), + (original / 'geometry', '/base', True), (original / 'multiview', '/multiview', True), + (previous, '/fullplan', True), (out, '/out', False)] + for producer, alias in definition['aliases'].items(): + if producer != name and producer in locations: + mounts.append((locations[producer], '/' + alias, True)) + for destination, relative in group.get('input_files', {}).items(): + assert relative in locations + mounts = [m for m in mounts if m[1] != destination] + mounts.append((locations[relative], destination, True)) + if stage in group.get('self_symbol_stages', []): + mounts = [m for m in mounts if m[1] != '/symbolplan'] + mounts.append((out, '/symbolplan', True)) + for wheel in (module / 'pipeline/vendor').glob('*.whl'): + mounts.append((wheel, '/candidate/' + wheel.name, True)) + semantic = stage in SEMANTIC_STAGES + if semantic: + mounts += [(release, '/release', True), (runtime / profile['semantic_model'], '/assets', True)] + env = dict(SCENE='scene', ORTHO_SCENE='scene', MV_MODEL='mapillary', + PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon', + OPENBLAS_NUM_THREADS='3', OMP_NUM_THREADS='3', HF_HUB_OFFLINE='1', + TRANSFORMERS_OFFLINE='1', HF_HOME='/tmp/hf', MPLCONFIGDIR='/tmp/matplotlib', + XDG_CACHE_HOME='/tmp/cache', TORCH_HOME='/tmp/torch', + WINDOW_SOURCE='/candidate/linear_window_support.py') + env.update(group.get('environment', {})) + entry = 'import runpy;' + if stage == 'final_symbol_admission': + entry += "import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];" + entry += "runpy.run_path('/candidate/" + stage + ".py',run_name='__main__')" + if stage == 'semantic_compact_symbols' and not json.loads((out/'symbol-patches.json').read_text())['patches']: + write_json(out/'symbol-semantics.json', dict(records=[],patch_manifest_sha256=checksum(out/'symbol-patches.json'), + class_labels=['bicycle'],prompts=['bicycle','bike symbol','bicycle road marking'],class_ids=[0,0,0],manual_rois=[],empty_search=True)) + journal.append(dict(group=name, stage=stage, seconds=0, skipped='empty manifest')) + continue + started = time.monotonic() + print('BEGIN', name, stage, flush=True) + run_container(marker, name + '-' + stage, profile['semantic_image' if semantic else 'mapper_image'], + mounts, ['-B', '-c', entry], out, lambda: None, 1200, + gpu=semantic, executable='python3', environment=env, readonly=True) + journal.append(dict(group=name, stage=stage, seconds=time.monotonic()-started)) + write_json(root/'journal.json', journal) + print('END', name, stage, round(journal[-1]['seconds'], 3), flush=True) + if group.get('map_file'): + shutil.copyfile(out/group['map_file'], out/'full-map.json') + locations[name] = out + previous = out + final = json.loads((previous/'full-map.json').read_text()) + summary = dict(session=CONFIG['session'], published=False, cold_run=False, + prefix_job=CONFIG['original_job'], prefix_completed_stages=77, + tail_stages=journal, tail_seconds=sum(r['seconds'] for r in journal), + final_map=final, final_map_sha256=checksum(previous/'full-map.json'), + source_manifest=source_manifest['snapshot'], input_gaussian_sha256=source['sha256']) + write_json(root/'summary.json', summary) + print('SUMMARY', json.dumps({k:v for k,v in summary.items() if k not in ['final_map','tail_stages']}), flush=True) +except Exception: + for p in root.rglob('*.log'): + print('LOG', str(p), p.read_text(encoding='utf-8', errors='replace')[-2500:], flush=True) + raise +finally: + cleanup(marker) + if not json.loads(marker.read_text())['containers']: + marker.unlink() +if (root/'summary.json').exists(): + p=root/'summary.json' + print('COLLECTION', json.dumps(dict(path=str(p),bytes=p.stat().st_size,sha256=checksum(p))), flush=True) diff --git a/simulation/urban-plan-research/evaluation/run_frozen_tail.py b/simulation/urban-plan-research/evaluation/run_frozen_tail.py new file mode 100644 index 00000000..137eafce --- /dev/null +++ b/simulation/urban-plan-research/evaluation/run_frozen_tail.py @@ -0,0 +1,92 @@ +"""Replay a declared suffix against read-only fresh-candidate observations. + +Engineering qualification only. This does not restore a production cache, +claim cold timing, or feed reference-map geometry to discovery. +""" +from pathlib import Path +import json,time,shutil +from infrastructure_containers import run_container +from infrastructure_pipeline import SEMANTIC_STAGES,prepare_layout,output_inventory +from infrastructure_sources import checksum +from local_state import write_json + + +def run(root,module,marker,profile,runtime,source,package,config): + reference=root.parent/config['replay_prefix'] + assert checksum(reference/'summary.json')==config['replay_prefix_sha256'] + proof=json.loads((reference/'summary.json').read_text()) + assert proof['cold_run'] and proof['gaussian_sha256']==source['sha256'] + original=reference/'run';output=root/'run' + definition,modules,snapshot=prepare_layout(output,module) + prior=json.loads((original/'source-manifest.json').read_text()) + start=next(i for i,g in enumerate(definition['groups'])if g['group']==config.get('replay_from','paint_assembly')) + assert start>=3 + prefix=definition['groups'][:start] + # Declare every changed producer rather than silently treating its outputs + # as those of the new implementation. They are fixed experimental inputs. + changed={rel for g in prefix for rel in g['files'].values()if prior['files'].get(rel)!=checksum(module/rel)} + write_json(root/'prefix-provenance.json',dict(session=reference.name,summary_sha256=config['replay_prefix_sha256'], + frozen_inputs_from_changed_producers=sorted(changed),cold_run=False,old_geometry_as_input=False)) + locations={g['group']:original/('geometry'if g['group']=='base'else g['group'])for g in prefix} + previous=next(locations[g['group']]for g in reversed(prefix)if g.get('map_output',True)and g['group']!='base') + journal=[];started=time.monotonic() + def resolve(relative): + name,*parts=Path(relative).parts + return (locations[name]/Path(*parts))if name in locations else original/relative + for group in definition['groups'][start:]: + name=group['group'];out=output/name;out.mkdir(exist_ok=True) + assert not group.get('stage_outputs') and not group.get('extra_coverage') + if (previous/'crosswalk-standard-check.json').exists():shutil.copyfile(previous/'crosswalk-standard-check.json',out/'crosswalk-standard-check.json') + stages=group['stages'][:1]if name=='primary_search'and config.get('replay_primary_observations')else group['stages'] + for stage in stages: + mounts=[(modules/name,'/candidate',True),(package,'/input',True),(original/'base-survey','/base_survey',True), + (original/'ortho','/ortho',True),(original/'ortho/survey','/survey',True),(original/'geometry','/base',True), + (original/'multiview','/multiview',True),(previous,'/fullplan',True),(out,'/out',False)] + for producer,alias in definition['aliases'].items(): + if producer!=name and producer in locations:mounts.append((locations[producer],'/'+alias,True)) + for destination,relative in group.get('input_files',{}).items(): + mounts=[m for m in mounts if m[1]!=destination];mounts.append((resolve(relative),destination,True)) + if stage in group.get('self_symbol_stages',[]): + mounts=[m for m in mounts if m[1]!='/symbolplan'];mounts.append((out,'/symbolplan',True)) + for wheel in(module/'pipeline/vendor').glob('*.whl'):mounts.append((wheel,'/candidate/'+wheel.name,True)) + semantic=stage in SEMANTIC_STAGES + if semantic:mounts.extend([(module.parents[1],'/release',True),(runtime/profile['semantic_model'],'/assets',True)]) + env=dict(SCENE='scene',ORTHO_SCENE='scene',MV_MODEL='mapillary',PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon', + OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HOME='/tmp/hf', + MPLCONFIGDIR='/tmp/matplotlib',XDG_CACHE_HOME='/tmp/cache',TORCH_HOME='/tmp/torch',WINDOW_SOURCE='/candidate/linear_window_support.py') + env.update(group.get('environment',{})) + entry='import runpy;' + if stage=='final_symbol_admission':entry+="import sys;sys.argv=['final_symbol_admission','/fullplan/full-map.json','/candidate/symbol_rules.py','/out'];" + entry+="runpy.run_path('/candidate/"+stage+".py',run_name='__main__')" + t=time.monotonic();print('BEGIN',name,stage,flush=True) + run_container(marker,name+'-'+stage,profile['semantic_image'if semantic else'mapper_image'],mounts,['-B','-c',entry],out,lambda:None,1200, + gpu=semantic,executable='python3',environment=env,readonly=True,resources=group.get('stage_resources',{}).get(stage)) + receipt=dict(group=name,stage=stage,seconds=time.monotonic()-t,exit_code=0,snapshot=snapshot) + journal.append(receipt);write_json(out/(stage+'-execution.json'),receipt);write_json(root/'journal.json',journal) + print('END',name,stage,round(receipt['seconds'],3),flush=True) + if name=='primary_search'and config.get('replay_primary_observations'): + original_primary=original/'primary_search' + for filename in ['compact-seeds.json','catalog-proposals.json','crossing-seeds.json','observations.json']: + a=json.loads((out/filename).read_text());b=json.loads((original_primary/filename).read_text()) + if isinstance(a,dict):a.pop('tile_reports',None);b.pop('tile_reports',None) + assert a==b,'Symbol observation inputs changed: '+filename + copied={} + for filename in ['symbol-patches.json','symbol-semantics.json','ground-observation-inventory.json','coverage-ledger.json']: + shutil.copy2(original_primary/filename,out/filename);copied[filename]=checksum(out/filename) + for folder in ['symbol-patches','symbol-masks']: + shutil.copytree(original_primary/folder,out/folder) + write_json(root/'reused-symbol-observations.json',dict(session=reference.name,reason='identical compact seeds, native observations and semantic proposal inputs',files=copied,cold_run=False)) + locations[name]=out + if group.get('map_output',True): + if group.get('map_file'):shutil.copyfile(out/group['map_file'],out/'full-map.json') + previous=out;write_json(out/'group-inventory.json',dict(files=output_inventory(out))) + final=previous/'full-map.json' + summary=dict(session=root.name,cold_run=False,published=False,replay_prefix=reference.name, + prefix_summary_sha256=config['replay_prefix_sha256'],observation_run=original.as_posix(), + wall_seconds=time.monotonic()-started,stage_seconds=sum(r['seconds']for r in journal),completed_stages=len(journal), + source_snapshot=snapshot,gaussian_sha256=source['sha256'],poses_sha256=source['poses_sha256'], + final_map=json.loads(final.read_text()),final_map_sha256=checksum(final),receipts=journal, + reports={p.relative_to(output).as_posix():json.loads(p.read_text())for p in output.glob('*/*.json') + if p.name.endswith(('report.json','audit.json'))and p.stat().st_size<4*1024**2}) + write_json(root/'summary.json',summary) + print('TAIL_COMPLETE',summary['wall_seconds'],len(journal),summary['final_map_sha256'],flush=True) diff --git a/simulation/urban-plan-research/evaluation/run_shared_survey_worker.py b/simulation/urban-plan-research/evaluation/run_shared_survey_worker.py new file mode 100644 index 00000000..8386a78b --- /dev/null +++ b/simulation/urban-plan-research/evaluation/run_shared_survey_worker.py @@ -0,0 +1,243 @@ +"""Frozen, artifact-owned control/candidate comparison on Worker 006.""" + +import base64 +import datetime +import hashlib +import json +import shutil +import sys +import time +from pathlib import Path + +CONFIG = globals()["CONFIG"] + +sys.stdout.reconfigure(encoding="utf-8") +runtime = Path("D:/NDC_MISSIONCORE/runtime/simulation") +release = runtime / "releases" / ("ai-polygon-" + CONFIG["release"]) +root = Path("C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications") / CONFIG["session"] +assert not root.exists(), "Session already exists" +assert not list((runtime / "state").glob("*active.json")), "Active simulation workflow" +assert shutil.disk_usage(root.parent).free > 40 * 1024**3 +sys.path[:0] = [str(release / "simulation/ai-polygon"), str(release / "src")] +from infrastructure_containers import ( # noqa: E402 - installed release selected above + cleanup, + run_container, +) +from infrastructure_sources import checksum # noqa: E402 - installed release selected above +from local_state import write_json # noqa: E402 - installed release selected above + +module = release / "simulation/urban-plan-research" +assert checksum(module / "pipeline/definition.json") == CONFIG["definition_sha256"] +profile = json.loads((module / "pipeline/worker-profile.json").read_text()) +root.mkdir() +sources = root / "modules" +sources.mkdir() +for name, entry in CONFIG["files"].items(): + assert Path(name).name == name + data = base64.b64decode(entry["content"]) + assert hashlib.sha256(data).hexdigest() == entry["sha256"] + (sources / name).write_bytes(data) +for wheel in (module / "pipeline/vendor").glob("*.whl"): + (sources / wheel.name).touch() +write_json( + root / "manifest.json", + {k: v for k, v in CONFIG.items() if k != "files"} + | dict( + files={k: dict(source=v["source"], sha256=v["sha256"]) for k, v in CONFIG["files"].items()}, + utc=datetime.datetime.now(datetime.UTC).isoformat(), + images=profile, + published=False, + ), +) +marker = root / "active.json" +write_json( + marker, + dict( + key=hashlib.sha256(CONFIG["session"].encode()).hexdigest(), + owner=CONFIG["session"], + containers=[], + ), +) +journal = [] + + +def stage(name, entry, out, mounts=(), semantic=False): + out.mkdir(exist_ok=True, parents=True) + bindings = [(sources, "/candidate", True), (out, "/out", False), *mounts] + bindings += [ + (p, "/candidate/" + p.name, True) for p in (module / "pipeline/vendor").glob("*.whl") + ] + if semantic: + bindings += [ + (release, "/release", True), + (runtime / profile["semantic_model"], "/assets", True), + ] + env = dict( + SCENE="scene", + ORTHO_SCENE="scene", + PYTHONPATH="/candidate:/release/simulation/ai-polygon", + OPENBLAS_NUM_THREADS="3", + OMP_NUM_THREADS="3", + HF_HUB_OFFLINE="1", + TRANSFORMERS_OFFLINE="1", + HF_HOME="/tmp/hf", + MPLCONFIGDIR="/tmp/matplotlib", + XDG_CACHE_HOME="/tmp/cache", + TORCH_HOME="/tmp/torch", + SURVEY_EVIDENCE_INPUT="/input_evidence", + ) + started = time.monotonic() + print("BEGIN", name, flush=True) + try: + run_container( + marker, + name, + profile["semantic_image" if semantic else "mapper_image"], + bindings, + ["-B", "-c", entry], + out, + lambda: None, + 2400, + gpu=semantic, + executable="python3", + environment=env, + readonly=True, + ) + except Exception: + for p in out.glob("*.log"): + print(p.read_text(errors="replace")[-4500:], flush=True) + raise + journal.append(dict(stage=name, seconds=time.monotonic() - started)) + write_json(root / "journal.json", journal) + print("END", name, round(journal[-1]["seconds"], 2), flush=True) + + +try: + if CONFIG.get("tests", True): + stage( + "tests", + "import unittest; r=unittest.TextTestRunner(verbosity=2).run(" + "unittest.defaultTestLoader.loadTestsFromName('test_semantic_survey')); " + "assert r.wasSuccessful()", + root / "tests", + ) + for spec in CONFIG["scenes"]: + ortho = Path(spec["ortho"]) + case = root / spec["name"] + case.mkdir() + control = case / "control" + candidate = case / "candidate" + control.mkdir() + candidate.mkdir() + idx = json.loads((ortho / "survey/tile-index.json").read_text()) + tiles = [t for t in idx["tiles"] if t["status"] == "surveyed"] + if spec.get("tile_limit"): + tiles = tiles[: spec["tile_limit"]] + write_json(case / "tile-index.json", {**idx, "tiles": tiles}) + frozen = [] + copies = [] + for dest in [control, candidate]: + (dest / "ortho/evidence").mkdir(parents=True) + (dest / "layers").mkdir() + shutil.copyfile(ortho / "config.json", dest / "ortho/config.json") + try: + for tile in tiles: + for suffix in [".context.png", ".ground.png", ".ground-dc.geometry.npz"]: + src = ortho / "evidence" / (tile["id"] + suffix) + dst = control / "ortho/evidence" / src.name + digest = checksum(src) + shutil.copyfile(src, dst) + assert checksum(dst) == digest + frozen.append(dict(path=str(src), sha256=digest, bytes=src.stat().st_size)) + copies.append(dst) + geo = ortho / "survey" / tile["id"] / "top.geometry.npz" + frozen.append(dict(path=str(geo), sha256=checksum(geo), bytes=geo.stat().st_size)) + write_json( + case / "input-manifest.json", + dict( + files=frozen, + tile_index=checksum(case / "tile-index.json"), + config=checksum(ortho / "config.json"), + ), + ) + shared = [ + (ortho / "survey", "/survey", True), + (case / "tile-index.json", "/survey/tile-index.json", True), + ] + stage( + spec["name"] + "-control-surfaces", + "import runpy;runpy.run_path('/candidate/legacy_ortho_segment.py'," + "run_name='__main__')", + control / "ortho", + [ + *shared, + (control / "ortho", "/run", False), + (control / "ortho/evidence", "/evidence", False), + ], + True, + ) + stage( + spec["name"] + "-control-layers", + "import runpy;runpy.run_path('/candidate/legacy_semantic_layers.py'," + "run_name='__main__')", + control / "layers", + [*shared, (ortho, "/ortho", True)], + True, + ) + finally: + # Only this run's verified input copies; retain all newly computed evidence. + for p in copies: + p.unlink() + stage( + spec["name"] + "-shared", + "import semantic_survey_stage;semantic_survey_stage.run()", + candidate, + [ + *shared, + (candidate / "ortho", "/run", False), + (candidate / "ortho/evidence", "/evidence", False), + (candidate / "layers", "/layers", False), + (ortho / "evidence", "/input_evidence", True), + ], + True, + ) + stage( + spec["name"] + "-compare", + "import compare_semantic_survey;compare_semantic_survey.run()", + case / "comparison", + [(control, "/control", True), (candidate, "/candidate_result", True)], + ) + for row in frozen: + assert checksum(Path(row["path"])) == row["sha256"], "Input changed" + result = json.loads((case / "comparison/comparison.json").read_text()) + print("COMPARISON", spec["name"], json.dumps(result), flush=True) + if CONFIG.get("consumer_comparison"): + sys.path.insert(0, str(sources)) + import semantic_consumers + + semantic_consumers.run(stage, root, runtime, release, profile, CONFIG) +finally: + cleanup(marker) + marker.unlink() +# Keep full evidence remotely, return bounded reports and execution receipts only. +collected = {} +for p in root.rglob("*"): + if ( + p.is_file() + and p.suffix == ".json" + and "modules" not in p.parts + and p.stat().st_size < 2 * 1024**2 + ): + collected[p.relative_to(root).as_posix()] = json.loads(p.read_text()) +write_json(root / "summary.json", collected) +print( + "COLLECTION", + json.dumps( + dict( + path=(root / "summary.json").as_posix(), + sha256=checksum(root / "summary.json"), + bytes=(root / "summary.json").stat().st_size, + ) + ), + flush=True, +) diff --git a/simulation/urban-plan-research/evaluation/run_systematic_worker.py b/simulation/urban-plan-research/evaluation/run_systematic_worker.py new file mode 100644 index 00000000..7390cc14 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/run_systematic_worker.py @@ -0,0 +1,170 @@ +"""Execute a frozen whole-pipeline candidate in an isolated Worker directory.""" +from pathlib import Path +import base64,datetime,hashlib,json,shutil,sys,time +CONFIG=globals()['CONFIG'];sys.stdout.reconfigure(encoding='utf-8') +runtime=Path('D:/NDC_MISSIONCORE/runtime/simulation') +release=runtime/'releases'/('ai-polygon-'+CONFIG['release']) +root=Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications')/CONFIG['session'] +assert not root.exists();assert not list((runtime/'state').glob('*active.json')) +assert shutil.disk_usage(root.parent).free>40*1024**3 +sys.path.insert(0,str(release/'simulation/ai-polygon')) +from infrastructure_sources import checksum +from local_state import write_json +original=Path(CONFIG['original_job']);source=json.loads((original/'request.json').read_text())['source'] +assert source['sha256']==CONFIG['gaussian_sha256'] +package=runtime/'state/infrastructure-sources'/source['adapter_key'] +assert checksum(package/source['ply'])==source['sha256'] +assert checksum(package/'poses.json')==source['poses_sha256'] +root.mkdir();artifact=root/'artifact';module=artifact/'simulation/urban-plan-research' +for name,item in CONFIG['files'].items(): + path=Path(name) + assert not path.is_absolute()and '..'not in path.parts and '\\'not in name + data=base64.b64decode(item['content']);assert hashlib.sha256(data).hexdigest()==item['sha256'] + target=artifact/path;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data) +sys.path.insert(0,str(artifact/'simulation/ai-polygon')) +from infrastructure_containers import run_container,cleanup +from infrastructure_pipeline import run_pipeline,prepare_layout +# Pinned immutable model-loading support and wheels from the installed release. +for rel in ['simulation/ai-polygon/sam3-research','simulation/urban-plan-research/pipeline/vendor']: + assert (release/rel).is_dir() + shutil.copytree(release/rel,artifact/rel) +profile=json.loads((module/'pipeline/worker-profile.json').read_text()) +profile['maximum_stage_seconds']=1200;profile['maximum_seconds']=3600 +marker=root/'active.json';write_json(marker,dict(key=hashlib.sha256(CONFIG['session'].encode()).hexdigest(),owner=CONFIG['session'],containers=[])) +manifest={k:v for k,v in CONFIG.items()if k!='files'} +manifest.update(utc=datetime.datetime.now(datetime.timezone.utc).isoformat(),cold_run=not CONFIG.get('preflight_only',False)and not CONFIG.get('replay_prefix')and not CONFIG.get('execution_only'),published=False,old_geometry_as_input=False,source_files={k:v['sha256']for k,v in CONFIG['files'].items()}) +write_json(root/'manifest.json',manifest) +output=root/'run';output.mkdir();last=None;started=time.monotonic();execution_observer=None +def pulse(): + global last + p=output/'progress.json' + if p.exists(): + d=json.loads(p.read_text()) + if d!=last:print('PROGRESS',json.dumps(d),flush=True);last=d +try: + # Runtime smoke exercises the new pure tile detectors on a frozen control + # observation. Its outputs are isolated and never inputs to the cold run. + definition,modules,snapshot=prepare_layout(output,module) + if CONFIG.get('execution_only'): + sys.path.insert(0,str(module/'evaluation')) + from qualify_stroke_execution import run as qualify_stroke_execution + checked=qualify_stroke_execution(root,modules,root.parent/CONFIG['execution_stroke_reference'],CONFIG['execution_stroke_reference_sha256'],marker,profile) + write_json(root/'summary.json',dict(session=root.name,cold_run=False,published=False,execution_only=True,stroke_execution=checked)) + else: + if not CONFIG.get('qualified_preflight'): + smoke=root/'smoke';smoke.mkdir() + mounts=[(modules/'primary_search','/candidate',True),(original/'full_plan','/evidence_plan',True), + (original/'ortho/survey','/survey',True),(original/'ortho','/ortho',True),(smoke,'/out',False)] + code=""" + import json,numpy as np + from pathlib import Path + from search_views import SearchViews + from paint_observations import collect as paint + from catalog_observations import collect as catalog + from compact_observations import collect as compact + from crossing_discovery import primitives + with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds'] + tiles=[t for t in json.loads(Path('/survey/tile-index.json').read_text())['tiles']if t['status']=='surveyed'] + v=SearchViews(tiles,labels,low,high,None);t=tiles[len(tiles)//2];n=t['id'];g=v.geometry(n);rgb,vehicle=v.inputs(n) + with np.load('/evidence_plan/evidence/'+n+'.npz')as z:marking=z['road marking'];cross=z['crosswalk'] + a,b=paint(rgb,vehicle,g,marking,cross,labels==1,low,high,t) + c=catalog(rgb,vehicle,g,labels,low,high,n);d=compact(rgb,vehicle,g,labels,low,high,n);e=primitives(rgb,cross,vehicle,g,labels,low,high) + print('SMOKE_OK',n,len(a),len(b),len(c),len(d),len(e)) + """ + code=__import__('textwrap').dedent(code) + env=dict(PYTHONPATH='/candidate:/candidate/mapping',SCENE='scene',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3') + run_container(marker,'detector-smoke',profile['mapper_image'],mounts,['-B','-c',code],smoke,lambda:None,180,gpu=False,executable='python3',environment=env,readonly=True) + print('SMOKE_OK',flush=True) + # Reordering visibility work may improve I/O only; selected windows and + # pixels must match the previously qualified planner exactly. + fixture=Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/topdown-writer-queue-20261016101327/maroseyka') + plancheck=root/'plan-contract';plancheck.mkdir() + mounts=[(modules/'primary_search','/candidate',True),(module/'systematic/qualify_primary_plan.py','/qualify.py',True), + (fixture/'observations','/ortho',True),(fixture/'observations/native-geometry','/native_geometry',True), + (fixture/'survey','/reference-symbols',True),(plancheck,'/out',False)] + run_container(marker,'primary-plan-contract',profile['mapper_image'],mounts,['-B','/qualify.py'],plancheck,lambda:None,300, + gpu=False,executable='python3',environment=env,readonly=True) + print('PRIMARY_PLAN_CONTRACT_OK',flush=True) + + sys.path.insert(0,str(module/'evaluation')) + from contract_preflight import run as preflight + checked=preflight(root,definition,modules,original,marker,profile,runtime,release,run_container,write_json) + unit=root/'initial-contract';unit.mkdir() + run_container(marker,'initial-observation-contract',profile['mapper_image'],[(modules/'primary_search','/candidate',True),(unit,'/out',False)],['-B','/candidate/qualify_initial_observations.py'],unit,lambda:None,90,gpu=False,executable='python3',environment=env,readonly=True) + print('INITIAL_OBSERVATION_CONTRACT_OK',flush=True) + crossing_unit=root/'crossing-fit-contract';crossing_unit.mkdir() + crossing_env={**env,'PYTHONPATH':'/candidate:/candidate/mapping'} + run_container(marker,'crossing-fit-contract',profile['mapper_image'],[(modules/'paint_assembly','/candidate',True),(crossing_unit,'/out',False)],['-B','/candidate/qualify_crossing_fit.py'],crossing_unit,lambda:None,90,gpu=False,executable='python3',environment=crossing_env,readonly=True) + print('CROSSING_FIT_CONTRACT_OK',flush=True) + stroke_unit=root/'stroke-contract';stroke_unit.mkdir() + run_container(marker,'stroke-contract',profile['mapper_image'],[(modules/'marking_pass','/candidate',True),(stroke_unit,'/out',False)],['-B','/candidate/qualify_strokes.py'],stroke_unit,lambda:None,90,gpu=False,executable='python3',environment=env,readonly=True) + print('STROKE_CONTRACT_OK',flush=True) + + else: + qualified=root.parent/CONFIG['qualified_preflight'] + prior=json.loads((qualified/'summary.json').read_text()) + proof=json.loads((qualified/'manifest.json').read_text()) + needed={relative for group in definition['groups'] if group['group']!='base' for relative in group['files'].values()} + needed.update(['evaluation/contract_preflight.py','systematic/qualify_primary_plan.py']) + for relative in needed: + name='simulation/urban-plan-research/'+relative + assert proof['source_files'][name]==CONFIG['files'][name]['sha256'], 'Preflight source changed: '+relative + assert (prior.get('preflight_only')or(prior.get('replay_prefix')and not prior['cold_run'])) and json.loads((qualified/'contracts/contract-report.json').read_text())['passed'] + assert json.loads((qualified/'plan-contract/primary-plan-qualification.json').read_text())['passed'] + checked=prior['contracts'] + write_json(root/'reused-preflight.json',dict(session=qualified.name,summary_sha256=checksum(qualified/'summary.json'), + unchanged_contract_sources=len(needed),outputs_used_by_cold_run=False)) + print('QUALIFIED_PREFLIGHT_REUSED',qualified.name,flush=True) + if CONFIG.get('preflight_only'): + concept=root/'concepts';concept.mkdir() + mounts=[(modules/'primary_search','/candidate',True),(release,'/release',True),(runtime/profile['semantic_model'],'/assets',True),(original/'uniform_search','/symbolplan',True),(concept,'/out',False)] + env=dict(PYTHONPATH='/candidate:/release/simulation/ai-polygon',OPENBLAS_NUM_THREADS='3',OMP_NUM_THREADS='3',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1',HF_HOME='/tmp/hf',TORCH_HOME='/tmp/torch') + run_container(marker,'concept-qualification',profile['semantic_image'],mounts,['-B','/candidate/qualify_concept_decoding.py'],concept,lambda:None,180,gpu=True,executable='python3',environment=env,readonly=True) + execution=None + if CONFIG.get('execution_reference'): + from qualify_execution_reuse import run as qualify_execution + execution=qualify_execution(root,modules,root.parent/CONFIG['execution_reference'],CONFIG['execution_reference_sha256'],marker,profile,runtime,artifact,run_container,write_json) + stroke_execution=None + if CONFIG.get('execution_stroke_reference'): + from qualify_stroke_execution import run as qualify_stroke_execution + stroke_execution=qualify_stroke_execution(root,modules,root.parent/CONFIG['execution_stroke_reference'],CONFIG['execution_stroke_reference_sha256'],marker,profile) + summary=dict(session=CONFIG['session'],cold_run=False,preflight_only=True,contracts=checked,concepts=json.loads((concept/'concept-qualification.json').read_text()),execution_reuse=execution,stroke_execution=stroke_execution,published=False) + write_json(root/'summary.json',summary) + elif CONFIG.get('replay_prefix'): + sys.path.insert(0,str(module/'evaluation')) + from run_frozen_tail import run as replay_tail + replay_tail(root,module,marker,profile,runtime,source,package,CONFIG) + summary=json.loads((root/'summary.json').read_text());summary['contracts']=checked;write_json(root/'summary.json',summary) + else: + if CONFIG.get('profile_execution'): + sys.path.insert(0,str(module/'evaluation')) + import infrastructure_pipeline + from execution_profile import ExecutionProfile + execution_observer=ExecutionProfile(root,infrastructure_pipeline).start() + started=time.monotonic() + final,snapshot=run_pipeline(package,source,output,marker,profile,runtime,pulse,module=module) + elapsed=time.monotonic()-started + execution_profile=execution_observer.stop() if execution_observer else None + execution_observer=None + receipts=[dict(group=p.parent.name,**json.loads(p.read_text()))for p in output.glob('*/*-execution.json')] + reports={} + for p in output.glob('*/*.json'): + if p.name.endswith(('report.json','audit.json')) and p.stat().st_size<4*1024**2:reports[p.relative_to(output).as_posix()]=json.loads(p.read_text()) + summary=dict(session=CONFIG['session'],cold_run=True,published=False,wall_seconds=elapsed,stage_seconds=sum(r['seconds']for r in receipts),completed_stages=len(receipts),source_snapshot=snapshot,gaussian_sha256=source['sha256'],poses_sha256=source['poses_sha256'],final_map=json.loads(final.read_text()),final_map_sha256=checksum(final),receipts=receipts,reports=reports,execution_profile=execution_profile) + write_json(root/'summary.json',summary) + print('COMPLETE',elapsed,len(receipts),checksum(final),flush=True) +except Exception: + for p in root.rglob('*-execution.json'): + try: + rec=json.loads(p.read_text()) + if rec.get('exit_code'):print('FAILED_RECEIPT',p,json.dumps(rec),flush=True) + except Exception:pass + logs=sorted(root.rglob('*.log'),key=lambda p:p.stat().st_mtime) + for p in logs[-2:]:print('LOG',p,p.read_text(errors='replace')[-5000:],flush=True) + raise +finally: + if execution_observer is not None:execution_observer.stop() + cleanup(marker) + if not json.loads(marker.read_text())['containers']:marker.unlink() +if (root/'summary.json').exists(): + p=root/'summary.json';print('COLLECTION',json.dumps(dict(path=p.as_posix(),bytes=p.stat().st_size,sha256=checksum(p))),flush=True) diff --git a/simulation/urban-plan-research/evaluation/run_topdown_worker.py b/simulation/urban-plan-research/evaluation/run_topdown_worker.py new file mode 100644 index 00000000..3c948bc3 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/run_topdown_worker.py @@ -0,0 +1,234 @@ +"""Artifact-owned Worker006 qualification. CONFIG is injected by the local builder.""" +from pathlib import Path +import base64 +import datetime +import hashlib +import json +import shutil +import sys +import tarfile +import time + +sys.stdout.reconfigure(encoding='utf-8') +runtime = Path('D:/NDC_MISSIONCORE/runtime/simulation') +release = runtime/'releases'/('ai-polygon-'+CONFIG['release']) +root = Path('C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications')/CONFIG['session'] +assert not root.exists(), 'Immutable session already exists' +assert not list((runtime/'state').glob('*active.json')), 'Active simulation workflow' +assert shutil.disk_usage(root.parent).free > 8*1024**3 +sys.path[:0] = [str(release/'simulation/ai-polygon'), str(release/'src')] +from infrastructure_sources import checksum +from infrastructure_containers import run_container, cleanup +from local_state import write_json + +module = release/'simulation/urban-plan-research' +assert checksum(module/'pipeline/definition.json') == CONFIG['definition_sha256'] +profile = json.loads((module/'pipeline/worker-profile.json').read_text(encoding='utf-8')) +root.mkdir(); sources = root/'modules'; sources.mkdir() +for name, entry in CONFIG['files'].items(): + assert Path(name).name == name + data = base64.b64decode(entry['content']) + assert hashlib.sha256(data).hexdigest() == entry['sha256'] + (sources/name).write_bytes(data) +for wheel in (module/'pipeline/vendor').glob('*.whl'): + (sources/wheel.name).touch() +write_json(root/'manifest.json', {k:v for k,v in CONFIG.items() if k != 'files'} | dict( + files={k:dict(source=v['source'], sha256=v['sha256']) for k,v in CONFIG['files'].items()}, + utc=datetime.datetime.now(datetime.timezone.utc).isoformat(), monotonic=time.monotonic(), + images={k:profile[k] for k in ['mapper_image','semantic_image']}, published=False)) +marker = root/'active.json' +write_json(marker, dict(key=hashlib.sha256(CONFIG['session'].encode()).hexdigest(), + owner=CONFIG['session'], containers=[])) +journal = [] + + +def stage(name, entry, out, extra=(), semantic=False, timeout=1200, gpu=False): + out.mkdir(parents=True, exist_ok=True) + mounts = [(sources, '/candidate', True), (out, '/out', False)] + list(extra) + mounts += [(p, '/candidate/'+p.name, True) for p in (module/'pipeline/vendor').glob('*.whl')] + if semantic: + mounts += [(release, '/release', True), (runtime/profile['semantic_model'], '/assets', True)] + env = dict(SCENE='scene', ORTHO_SCENE='scene', PYTHONPATH='/candidate:/candidate/mapping:/release/simulation/ai-polygon', + OPENBLAS_NUM_THREADS='3', OMP_NUM_THREADS='3', HF_HUB_OFFLINE='1', TRANSFORMERS_OFFLINE='1', + HF_HOME='/tmp/hf', MPLCONFIGDIR='/tmp/matplotlib', XDG_CACHE_HOME='/tmp/cache', TORCH_HOME='/tmp/torch') + begin = time.monotonic(); utc = datetime.datetime.now(datetime.timezone.utc).isoformat() + print('BEGIN', name, flush=True) + try: + run_container(marker, name, profile['semantic_image' if semantic else 'mapper_image'], mounts, + ['-B', '-c', entry], out, lambda: None, timeout, gpu=semantic or gpu, + executable='python3', environment=env, readonly=True) + except Exception: + for log in out.glob('*.log'): + print(log.read_text(encoding='utf-8', errors='replace')[-7000:], flush=True) + raise + row = dict(stage=name, utc=utc, monotonic=begin, seconds=time.monotonic()-begin) + journal.append(row); write_json(root/'journal.json', journal) + print('END', name, round(row['seconds'], 2), flush=True) + + +try: + if CONFIG.get('prepared_mapper_runtime'): + prior=Path(CONFIG['prepared_mapper_runtime']);receipt=json.loads(prior.read_text()) + assert receipt['base_image']==profile['mapper_image'] + assert checksum(prior.parent/'gsplat_cuda.so')==receipt['compiled']['sha256'] + from infrastructure_containers import docker + assert docker('image','inspect',receipt['image'],'--format','{{.Id}}').stdout.strip()==receipt['image'] + profile['mapper_image']=receipt['image'] + write_json(root/'effective-runtime.json',dict(mapper_image=profile['mapper_image'],semantic_image=profile['semantic_image'])) + if CONFIG.get('queue_canary'): + sys.path.insert(0,str(sources)) + import queue_worker_canary + canary=root/'queue-canary';canary.mkdir() + queue_worker_canary.run(canary,sources,release,profile) + if CONFIG.get('retire_mapper_builds'): + sys.path.insert(0,str(sources)) + import retire_mapper_builds + retire_mapper_builds.run(CONFIG['prepared_mapper_runtime'],CONFIG['retire_mapper_builds'],root/'build-retention.json') + if CONFIG.get('runtime_probe'): + stage('runtime-probe', "import importlib.util,pathlib,json; p=pathlib.Path(importlib.util.find_spec('gsplat').origin).parent; print((p/'cuda/_backend.py').read_text())", root/'runtime-probe') + if CONFIG.get('precompile_mapper'): + # Owned one-time build artifact, excluded from per-location inference. + # Same upstream compiler flags and base image; only library packaging changes. + import subprocess,os + target=root/'mapper-runtime';target.mkdir() + compile_code="""import os,pathlib,json,hashlib,shutil,time +os.environ['TORCH_EXTENSIONS_DIR']='/out/extensions' +t=time.monotonic() +from gsplat.cuda._backend import _C +assert _C is not None +p=pathlib.Path(_C.__file__);shutil.copyfile(p,'/out/gsplat_cuda.so') +pathlib.Path('/out/compiled.json').write_text(json.dumps(dict(seconds=time.monotonic()-t,sha256=hashlib.sha256(p.read_bytes()).hexdigest(),architecture='8.9'))) +""" + if CONFIG.get('compiled_runtime'): + prior=Path(CONFIG['compiled_runtime']);receipt=json.loads((prior/'compiled.json').read_text()) + assert checksum(prior/'gsplat_cuda.so')==receipt['sha256'] + assert json.loads((prior.parent/'manifest.json').read_text())['images']['mapper_image']==profile['mapper_image'] + for filename in ['gsplat_cuda.so','compiled.json']:shutil.copyfile(prior/filename,target/filename) + else: + stage('mapper-runtime-compile',compile_code,target,gpu=True,timeout=900) + base_tag='ndc-mission-core-mapper-base:'+profile['mapper_image'].split(':')[1][:16] + subprocess.run(['docker','tag',profile['mapper_image'],base_tag],check=True) + assert subprocess.check_output(['docker','image','inspect',base_tag,'--format','{{.Id}}'],text=True).strip()==profile['mapper_image'] + (target/'csrc.py').write_text("import importlib.util,sys\nspec=importlib.util.spec_from_file_location('gsplat_cuda','/opt/ndc/gsplat_cuda.so')\nmodule=importlib.util.module_from_spec(spec)\nspec.loader.exec_module(module)\nsys.modules[__name__]=module\n") + dockerfile="FROM "+base_tag+"\nLABEL com.nodedc.product=mission-core com.nodedc.stack=urban-mapping com.nodedc.role=prepared-mapper com.nodedc.managed-by=qualification-artifact\nCOPY gsplat_cuda.so /opt/ndc/gsplat_cuda.so\nCOPY csrc.py /opt/ndc/csrc.py\nRUN python3 -c \"import importlib.util,pathlib,shutil; p=pathlib.Path(importlib.util.find_spec('gsplat').origin).parent; assert not (p/'csrc.py').exists(); shutil.copyfile('/opt/ndc/csrc.py',p/'csrc.py')\"\n" + (target/'Dockerfile').write_text(dockerfile) + (target/'.dockerignore').write_text('*\n!Dockerfile\n!csrc.py\n!gsplat_cuda.so\n') + tag='ndc-mission-core-prepared-mapper:'+CONFIG['session'] + result=subprocess.run(['docker','build','--network=none','--pull=false','-t',tag,str(target)],capture_output=True,text=True,timeout=120,env={**os.environ,'DOCKER_BUILDKIT':'0'}) + (target/'build.log').write_text(result.stdout+result.stderr) + if result.returncode:raise RuntimeError('Prepared mapper image build failed') + image_id=subprocess.check_output(['docker','image','inspect',tag,'--format','{{.Id}}'],text=True).strip() + write_json(target/'runtime.json',dict(base_image=profile['mapper_image'],image=image_id,tag=tag,compiled= json.loads((target/'compiled.json').read_text()))) + profile['mapper_image']=image_id + write_json(root/'effective-runtime.json',dict(mapper_image=image_id,semantic_image=profile['semantic_image'])) + # A new read-only container has no compilation cache. Import must succeed + # directly through the packaged binary, not JIT or a previous session. + stage('mapper-runtime-check',"import pathlib,json; from gsplat.cuda._backend import _C; assert _C.__file__=='/opt/ndc/gsplat_cuda.so'; print('PRECOMPILED',_C.__file__)",root/'mapper-runtime-check',gpu=True) + if CONFIG.get('tests', True): + stage('tests', "import unittest; r=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromName('test_topdown')); assert r.wasSuccessful()", root/'tests') + if CONFIG.get('camera_tests'): + stage('camera-tests','import test_orthographic_colour; test_orthographic_colour.run()',root/'camera-tests',gpu=True) + for spec in CONFIG['scenes']: + name = spec['name']; ortho = Path(spec['ortho']) + assert ortho.is_dir() + scene = root/name + confirmed_mount=[] + if spec.get('confirmed_reference'): + scene.mkdir(parents=True,exist_ok=True) + data=base64.b64decode(spec['confirmed_reference']['content']) + assert hashlib.sha256(data).hexdigest()==spec['confirmed_reference']['sha256'] + reference=scene/'confirmed-reference.json';reference.write_bytes(data) + confirmed_mount=[(reference,'/confirmed-reference.json',True)] + if spec.get('assemble_from'): + previous=Path(spec['assemble_from']) + stage(name+'-assemble','import assemble_reviewed_state; assemble_reviewed_state.run()',scene/'assembly', + [(Path(spec['base_map']),'/base-map.json',True),(previous/'reconstruction','/result',True), + (previous/'verification','/verification',True)]+confirmed_mount) + continue + geometry_mount=[] + if spec.get('render_parallel_observations'): + generated=scene/'observations' + stage(name+'-orthographic-observations','import render_native_geometry; render_native_geometry.run(parallel_rays=True)',generated, + [(ortho,'/ortho',True),(Path(spec['input']),'/input',True)],gpu=True,timeout=1800) + ortho=generated + geometry_mount=[(generated/'native-geometry','/native_geometry',True)] + elif spec.get('render_native_geometry'): + native=scene/'native-geometry' + stage(name+'-native-geometry', 'import render_native_geometry; render_native_geometry.run()',native, + [(ortho,'/ortho',True),(Path(spec['input']),'/input',True)],gpu=True,timeout=1800) + if spec.get('native_only'):continue + geometry_mount=[(native,'/native_geometry',True)] + elif spec.get('native_geometry'): + native=Path(spec['native_geometry']);assert json.loads((native/'native-geometry.json').read_text())['complete'] + geometry_mount=[(native,'/native_geometry',True)] + if spec.get('conditional_contract_audit'): + stage(name+'-conditional-contract','import conditional_contract_audit; conditional_contract_audit.run('+repr(spec['focus_groups'])+')',scene/'conditional-contract', + [(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True), + (Path(spec['depth_audit_path']),'/depth_audit',True)]+geometry_mount) + continue + if spec.get('pose_domain_audit'): + stage(name+'-pose-domain','import pose_domain_audit; pose_domain_audit.run('+repr(spec['focus_groups'])+')',scene/'pose-domain', + [(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True)]+geometry_mount,timeout=900) + continue + if spec.get('endpoint_cause_audit'): + stage(name+'-endpoint-cause','import endpoint_cause_audit; endpoint_cause_audit.run('+repr(spec['focus_groups'][0])+')',scene/'endpoint-cause', + [(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True), + (Path(spec['pose_audit']),'/pose_audit',True),(Path(spec['input']),'/input',True)]+geometry_mount,gpu=True,timeout=900) + continue + if spec.get('depth_audit'): + stage(name+'-depth-audit','import depth_audit; depth_audit.run('+repr(spec['tiles'])+')',scene/'depth-audit', + [(ortho,'/ortho',True),(Path(spec['input']),'/input',True)]+geometry_mount,gpu=True,timeout=900) + continue + if spec.get('feasibility_audit'): + stage(name+'-feasibility-audit','import feasibility_audit; feasibility_audit.run('+repr(spec['focus_groups'])+')',scene/'feasibility-audit', + [(ortho,'/ortho',True),(Path(spec['result']),'/result',True),(Path(spec['symbols']),'/symbolplan',True)]+geometry_mount,timeout=900) + continue + if spec.get('contract_audit'): + stage(name+'-contract-audit', 'import audit_contract; audit_contract.run(focus_groups='+repr(spec.get('focus_groups'))+')',scene/'contract-audit', + [(ortho,'/ortho',True),(Path(spec['result']),'/result',True), + (Path(spec['reference']),'/reference.json',True)]+geometry_mount) + continue + if CONFIG.get('audit') or spec.get('audit'): + stage(name+'-audit', "import audit_topdown; audit_topdown.audit()", scene/'audit', + [(ortho, '/ortho', True), (Path(spec['symbols']), '/symbolplan', True), + (Path(spec['result']), '/result', True), (Path(spec['reference']), '/reference.json', True)] + geometry_mount + + ([(Path(spec['previous']), '/previous.json', True)] if spec.get('previous') else [])) + continue + if spec.get('result'): + stage(name+'-verify', "import verify_topdown; verify_topdown.verify_result()", scene/'verification', + [(ortho, '/ortho', True), (Path(spec['symbols']), '/symbolplan', True), + (Path(spec['result']), '/result', True)] + confirmed_mount + geometry_mount + + ([(Path(spec.get('preservation_base',spec['reference'])), '/reference.json', True)] if spec.get('reference') else [])) + continue + if spec.get('symbols'): + symbols = Path(spec['symbols']) + else: + symbols = scene/'survey' + stage(name+'-survey', "import prepare_topdown; prepare_topdown.prepare('/out')", symbols, + [(ortho, '/ortho', True)]+geometry_mount) + stage(name+'-semantic', "import runpy; runpy.run_path('/candidate/semantic_symbols.py', run_name='__main__')", symbols, semantic=True) + extra = [(ortho, '/ortho', True), (symbols, '/symbolplan', True)]+geometry_mount + if spec.get('registry'): + extra.append((Path(spec['registry']), '/registry.json', True)) + entry = "import reconstruct_topdown; reconstruct_topdown.run(registry_path=" + ("'/registry.json'" if spec.get('registry') else 'None') + ", focus_groups=" + repr(spec.get('focus_groups')) + ")" + stage(name+'-reconstruct', entry, scene/'reconstruction', extra, timeout=1800) + verify_mounts = [(ortho, '/ortho', True), (symbols, '/symbolplan', True), (scene/'reconstruction', '/result', True)] + if spec.get('reference'): + verify_mounts.append((Path(spec.get('preservation_base',spec['reference'])), '/reference.json', True)) + stage(name+'-verify', "import verify_topdown; verify_topdown.verify_result()", scene/'verification', verify_mounts+confirmed_mount+geometry_mount) + +finally: + for queue_marker in root.glob('queue-canary/queue-active.json'): + cleanup(queue_marker);queue_marker.unlink() + cleanup(marker) + marker.unlink() + +files = [p for p in root.rglob('*') if p.is_file() and p.suffix in ['.json', '.log', '.png'] and 'symbol-patches' not in p.parts + and 'modules' not in p.parts and not (p.suffix=='.png' and 'observations' in p.relative_to(root).parts) + and p.stat().st_size < 20*1024**2] +write_json(root/'collection.json', {p.relative_to(root).as_posix(): checksum(p) for p in files}) +files.append(root/'collection.json'); archive = root/'evidence.tgz' +with tarfile.open(archive, 'w:gz') as tar: + for p in files: + tar.add(p, arcname=p.relative_to(root).as_posix(), recursive=False) +print('COLLECTION', json.dumps(dict(path=archive.as_posix(), sha256=checksum(archive), bytes=archive.stat().st_size)), flush=True) diff --git a/simulation/urban-plan-research/evaluation/test_array_serialization.py b/simulation/urban-plan-research/evaluation/test_array_serialization.py new file mode 100644 index 00000000..cf167df3 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/test_array_serialization.py @@ -0,0 +1,38 @@ +"""Numeric archive identity includes signed zeros, NaN bits and array layout.""" + +import importlib.util +import zipfile +from pathlib import Path + +import numpy as np +import pytest + +_path = Path(__file__).resolve().parents[1] / "systematic/array_archive.py" +_spec = importlib.util.spec_from_file_location("qualified_array_archive", _path) +_module = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_module) + + +def test_compression_changes_no_npy_payload_bits(tmp_path): + arrays = { + "float32": np.array([0, 0x80000000, 0x7FC00001, 0x7FC00123], np.uint32).view(np.float32), + "float16": np.array([0, -0.0, np.inf, -np.inf, np.nan], np.float16), + "fortran": np.asfortranarray(np.arange(24, dtype=np.float64).reshape(4, 6)), + "strided": np.arange(36, dtype=np.int16).reshape(6, 6)[::2, ::2], + "big_endian": np.arange(8, dtype=">f8"), + "empty": np.empty((0, 4), dtype=np.float32), + "scalar": np.array(True), + } + legacy, candidate = tmp_path / "legacy.npz", tmp_path / "candidate.npz" + np.savez_compressed(legacy, **arrays) + _module.save(candidate, **arrays) + with zipfile.ZipFile(legacy) as a, zipfile.ZipFile(candidate) as b: + assert a.namelist() == b.namelist() + assert all(a.read(name) == b.read(name) for name in a.namelist()) + + +def test_archive_rejects_objects_and_escaped_member_names(tmp_path): + with pytest.raises(ValueError, match="Object arrays"): + _module.save(tmp_path / "objects.npz", value=np.array([object()], dtype=object)) + with pytest.raises(ValueError, match="Invalid array key"): + _module.save(tmp_path / "escaped.npz", **{"../value": np.zeros(1)}) diff --git a/simulation/urban-plan-research/evaluation/test_execution_profile.py b/simulation/urban-plan-research/evaluation/test_execution_profile.py new file mode 100644 index 00000000..8939d1b7 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/test_execution_profile.py @@ -0,0 +1,43 @@ +import hashlib +import json +from types import SimpleNamespace + +from execution_profile import ExecutionProfile + + +def test_profiler_preserves_arguments_result_and_exception(tmp_path): + token = object() + calls = [] + + def run(*args, **kwargs): + calls.append((args, kwargs)) + if kwargs.get("fail"): + raise ValueError("original failure") + return token + + def checksum(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + pipeline = SimpleNamespace(run_container=run, checksum=checksum) + marker = tmp_path / "active.json" + marker.write_text(json.dumps(dict(key="abcdef0123456789abcd"))) + payload = tmp_path / "data.bin" + payload.write_bytes(b"unchanged physical observations") + profile = ExecutionProfile(tmp_path, pipeline, interval=60).start() + try: + assert pipeline.run_container(marker, "stage", token, gpu=False) is token + assert calls[-1] == ((marker, "stage", token), dict(gpu=False)) + assert pipeline.checksum(payload) == checksum(payload) + try: + pipeline.run_container(marker, "failed", fail=True) + except ValueError as error: + assert str(error) == "original failure" + else: + raise AssertionError("Profiler hid an original failure") + finally: + report = profile.stop() + assert pipeline.run_container is run and pipeline.checksum is checksum + assert report["sampler_stopped"] + assert [r["passed"] for r in report["stages"]] == [True, False] + assert report["orchestration_hashes"]["bytes"] == payload.stat().st_size + assert not report["numeric_functions_wrapped"] diff --git a/simulation/urban-plan-research/evaluation/test_metadata_equivalence.py b/simulation/urban-plan-research/evaluation/test_metadata_equivalence.py new file mode 100644 index 00000000..c3e3ec79 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/test_metadata_equivalence.py @@ -0,0 +1,45 @@ +from collections import Counter + +import numpy as np +import pytest +from explain_run_metadata import exact, proposal_data + + +def test_exact_bank_comparison_rejects_float_and_array_bit_changes(): + with pytest.raises(AssertionError): + exact(0.0, -0.0, Counter()) + a = np.array([0.0, -0.0], dtype="float32") + b = np.array([0.0, 0.0], dtype="float32") + with pytest.raises(AssertionError): + exact(a, b, Counter()) + with pytest.raises(AssertionError): + exact(a, a.astype("float64"), Counter()) + + +def test_timing_separation_keeps_geometry_counts_and_field_order_exact(): + def document(seconds=1.0, length=2.0, count=1): + return dict(lines=[dict(length=length)], tile_reports=[dict( + tile="tile-a", seconds=seconds, linear=count, + detectors={ + k: seconds for k in ["linear", "appearance", "catalog", "compact", "crossing"] + }, + )]) + + baseline, _ = proposal_data(document()) + changed_time, _ = proposal_data(document(seconds=2.0)) + exact(baseline, changed_time, Counter()) + for changed in [document(length=2.000001), document(count=2)]: + physical, _ = proposal_data(changed) + with pytest.raises(AssertionError): + exact(baseline, physical, Counter()) + with pytest.raises(AssertionError): + exact(dict(a=1, b=2), dict(b=2, a=1), Counter()) + + +def test_unknown_or_invalid_timing_field_fails_closed(): + with pytest.raises(AssertionError): + proposal_data(dict(tile_reports=[dict(tile="a", seconds=1.0, detectors={"quality": 0.9})])) + with pytest.raises(AssertionError): + proposal_data(dict(tile_reports=[dict(tile="a", seconds=float("nan"), detectors={ + k: 1.0 for k in ["linear", "appearance", "catalog", "compact", "crossing"] + })])) diff --git a/simulation/urban-plan-research/evaluation/test_run_equivalence.py b/simulation/urban-plan-research/evaluation/test_run_equivalence.py new file mode 100644 index 00000000..f0504263 --- /dev/null +++ b/simulation/urban-plan-research/evaluation/test_run_equivalence.py @@ -0,0 +1,41 @@ +import zipfile + +import numpy as np +from compare_frozen_runs import payload_digest + + +def test_packaging_changes_do_not_hide_or_create_a_numeric_difference(tmp_path): + source = tmp_path / "source.npz" + repacked = tmp_path / "repacked.npz" + changed = tmp_path / "changed.npz" + values = np.array([0x00000000, 0x80000000, 0x7FC00001], dtype="uint32").view("float32") + np.savez_compressed(source, values=values) + with zipfile.ZipFile(source) as original, zipfile.ZipFile(repacked, "w") as target: + for name in original.namelist(): + target.writestr(name, original.read(name), compress_type=zipfile.ZIP_STORED) + assert source.read_bytes() != repacked.read_bytes() + assert payload_digest(source) == payload_digest(repacked) + different_bits = values.copy() + different_bits[1] = 0.0 + np.savez_compressed(changed, values=different_bits) + np.testing.assert_array_equal(values, different_bits) + assert payload_digest(source) != payload_digest(changed) + + +def test_dtype_and_memory_order_remain_part_of_the_comparison(tmp_path): + a, b, c = [tmp_path / name for name in ["a.npz", "b.npz", "c.npz"]] + values = np.arange(12, dtype="float32").reshape(3, 4) + np.savez(a, values=values) + np.savez(b, values=values.astype("float64")) + np.savez(c, values=np.asfortranarray(values)) + assert payload_digest(a) != payload_digest(b) + assert payload_digest(a) != payload_digest(c) + + +def test_archive_iteration_order_is_preserved(tmp_path): + a, b = tmp_path / "a.npz", tmp_path / "b.npz" + np.savez(a, road=np.arange(3), paint=np.arange(4)) + with zipfile.ZipFile(a) as source, zipfile.ZipFile(b, "w") as target: + for name in reversed(source.namelist()): + target.writestr(name, source.read(name)) + assert payload_digest(a) != payload_digest(b) diff --git a/simulation/urban-plan-research/families_pass/README.rst b/simulation/urban-plan-research/families_pass/README.rst new file mode 100644 index 00000000..3dfe1f8d --- /dev/null +++ b/simulation/urban-plan-research/families_pass/README.rst @@ -0,0 +1,107 @@ +Gaussian-only crosswalk and short-dash families +============================================= + +Status +------ +Research increment families-pass-20261012, source 482ae9e8118b3145a6c2. +Same code and metric policy on Maroseyka, Pokrovka and Smolensk. No manual +geometry, processing ROIs, scene-specific thresholds or point-cloud inputs. +This is downstream paint reconstruction over the accepted continuation-pass +candidate. It is not a complete new end-to-end run or production deployment. + +Inputs and outputs +------------------ +/fullplan/full-map.json is the immutable continuation-pass baseline, not the +older full-plan map. /evidence_plan contains cached semantic fields and depth; +/ortho, /survey and /input supply native detailed Gaussian ground RGB, vehicle +masks and calibrated transforms. Upstream semantic models are not rerun. + +/out/full-map.json preserves all untouched features, including roads, +pedestrian polygons, facades and symbol templates. Reports distinguish image +observations, retained seed observations and inferred internal dash slots. +Crosswalk replacement removes the previous stripe objects as a group, so old +and new rectangles are not stacked on top of one another. + +Method +------ +1. Group seeded crossing stripes by direction, relative size and proximity. + Fit shared orientation and robust linear end envelopes using SciPy + least_squares. Adapt the existing recover_stripes brightness-profile idea + from parametric-fit-20261010/fit_scene.py to the current whole-map output. +2. Sample Gaussian RGB at 0.025 m transverse spacing over the middle 60 percent + of stripe length with OpenCV remap. Mask vehicles. Within confirmed crossing + extent, a semantic road-mask hole does not erase image paint evidence. + Unknown samples may interpolate the analysis signal but never count as a + new observation. +3. SciPy find_peaks and peak_widths recover observed stripes. Locate centers + between both half-prominence edges rather than at the brightest pixel. + Use white/yellow color profiles where both colors have repeated support. + Limit exterior search to 2 m and require observed, compatible evidence. + Weak peaks are suppressed; unseen periodic slots do not generate crosswalks. +4. Fit shared rectangular stripe geometry, retaining parent IDs and marking + seed centers without fresh image matches. Width is a shared median bounded + to avoid overlaps. Shared ends and width are still approximate, not measured + independently for each stripe. +5. For short dashed lines, reuse robust OpenCV Huber fitting. Require at least + three observed intervals, consistent lengths, period and phase. Only fill + internal slots within the observed range; veto crosswalk overlap and + incompatible road domain. Repeated dashes never become a solid line. + +Results +------- +Maroseyka: 16 crossing families, 111 -> 120 stripes, 1 internal dash added. +Pokrovka: 19 crossing families, 136 -> 144 stripes, 2 internal dashes added. +Smolensk: 2 crossing families, 18 -> 19 stripes, no dash added. +Total: 37 crossing families, 18 additional stripe objects, 3 inferred dash slots. +Numbers describe output objects, not measured recall or accuracy. + +All 11 controlled checks passed, including rotation/translation invariance, +vehicle exclusion, missing observations, color alternation, center stability, +nonoverlap and dash/crosswalk exclusion. Real-scene audit checks untouched +features, valid XYZ, provenance, observed recovery centers and nonoverlap. +All 37 crossing comparisons and 8 dash-family comparisons were visually read. + +Known limitations and next work +------------------------------ +Seeded families are required: completely undetected crossings are not found. +Some inferred shared ends remain too long or short; some widths are visibly +narrower than paint. Maroseyka crossing 15 still misses exterior stripes. +Smolensk's white/yellow family remains incomplete and retains uncertain seed +centers. New observed centers are not equivalent to verified entire polygons. +No independent metric ground truth or blind new-scene qualification is claimed. +Curbs, pedestrian silhouettes, facades and symbols are unchanged by this pass; +their previously recorded gaps and offsets remain. Next tests should improve +shared-end/width estimation and crossing discovery, then the planned joint +road/pedestrian boundary reconstruction. Review IDs are diagnostics only and +must not enter geometry settings or scene-specific exception tables. + +Reproduction and ownership +-------------------------- +Canonical source: simulation/urban-plan-research/families_pass/bundle.json. +Resolve each files entry relative to simulation/urban-plan-research and stage +as a flat directory, checking the SHA-256 entries. The output source ZIP is +already flat. It has ten Python files, README and bundle manifest. +review-font.ttf is a rendering-only external font, not bundled in the source +ZIP. The exact qualified copy and SHA are retained in qualification source and +source-sha256.json; computation and audit do not depend on this font. + +Qualification: .runtime/simulation-qualifications/families-pass-20261012/operator. +Worker: C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/families-pass-20261012. +The replay folder preserves runner, collector, verifier, scene registry and +source identity. This operator replay requires the existing Mission Core +checkout, queue API, SSH alias mission-gpu, pinned baseline maps, private survey +caches, config-v8.json and workspace layout. It is not a standalone public CLI. + +Runner stages: refine_paint, test_families, audit_families, render_families, +render_plan. Set URBAN_SOURCE_BUNDLE to the immutable qualified flat directory. +Run refine before audit/render and collect after completion. Accepted baseline +SHA comes from urban-plan-refinement-20261012/verification.json. +All numerical work, tests and rendering run on Worker006. Local operations +only orchestrate, verify hashes, copy artifacts and review images. + +Pinned worker image: +sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0 +Bounded stage: 4 CPU, 20 GiB RAM, read-only root, network none, 1 GiB tmpfs, +1800 s timeout. Queue reservation precedes execution; cleanup removes only the +owned ndc-families container and releases ownership after confirmation. +No runtime installation, live-map publication, source commit or Ops write. diff --git a/simulation/urban-plan-research/families_pass/audit_families.py b/simulation/urban-plan-research/families_pass/audit_families.py new file mode 100644 index 00000000..319f22aa --- /dev/null +++ b/simulation/urban-plan-research/families_pass/audit_families.py @@ -0,0 +1,18 @@ +from pathlib import Path +import json,hashlib,numpy as np,shapely +from shapely.geometry import shape +O=Path('/out');old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());report=json.loads((O/'crosswalk-families.json').read_text());accepted=[r for r in report if r['accepted']] +changed={i for r in accepted for i in r['source_ids']};newstripes=[f for f in new['features']if f['properties'].get('method')=='observed-profile-crosswalk-family'];newids={f['id']for f in newstripes} +lines=json.loads((O/'line-families.json').read_text());lineparents={i for r in lines for i in r['source_ids']};changed|=lineparents +newids|={f['id']for f in new['features']if f['properties'].get('method')=='periodic-dash-family'and set(f['properties'].get('source_ids',[]))<=lineparents} +checks=dict(untouched_features_preserved={f['id']:f for f in old['features']if f['id']not in changed}=={f['id']:f for f in new['features']if f['id']not in newids},unique_feature_ids=len(new['features'])==len({f['id']for f in new['features']}),finite_valid_3d=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])) +geometries=[shapely.force_2d(shape(f['geometry']))for f in new['features']if f['properties'].get('subtype')=='crosswalk'];bad=[] +for i,a in enumerate(geometries): + for j,b in enumerate(geometries[:i]): + if a.intersection(b).area>.02:bad.append([i,j,float(a.intersection(b).area)]) +checks['crosswalks_do_not_overlap']=not bad +checks['recovered_centers_have_image_evidence']=all(f['properties']['observed_center']for f in newstripes if f['properties']['recovered_stripe']) +checks['parent_provenance_complete']=set(x for f in newstripes for x in f['properties']['source_ids'])|lineparents==changed +checks['all_accepted_groups_materialized']=set(f['properties']['crosswalk_family']for f in newstripes)==set(r['group']for r in accepted) +result=dict(passed=all(checks.values()),checks=checks,crossing_count=len(accepted),overlaps=bad,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),full_map_sha256=hashlib.sha256((O/'full-map.json').read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_detection_measured=False) +(O/'family-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed'] diff --git a/simulation/urban-plan-research/families_pass/bundle.json b/simulation/urban-plan-research/families_pass/bundle.json new file mode 100644 index 00000000..4e107d2c --- /dev/null +++ b/simulation/urban-plan-research/families_pass/bundle.json @@ -0,0 +1,36 @@ +{ + "schema": "missioncore.offline-plan-bundle/v1", + "root": "simulation/urban-plan-research", + "files": { + "audit_families.py": "families_pass/audit_families.py", + "crossing_completion.py": "families_pass/crossing_completion.py", + "crosswalk_family.py": "full_plan/crosswalk_family.py", + "fit_scene.py": "full_plan/fit_scene.py", + "layer_common.py": "full_plan/layer_common.py", + "line_family_completion.py": "families_pass/line_family_completion.py", + "refine_paint.py": "families_pass/refine_paint.py", + "render_families.py": "families_pass/render_families.py", + "render_plan.py": "continuation_pass/render_plan.py", + "test_families.py": "families_pass/test_families.py" + }, + "reference_qualification": "families-pass-20261012", + "source_snapshot": "482ae9e8118b3145a6c2", + "source_sha256": { + "audit_families.py": "8159b6c208c5a5d7dbb5aef720b5d0ef847032f96cc418e7c0969241999b29b4", + "crossing_completion.py": "6e75ae4b65e8d6447acae57ae17ca088a427fda39f438271bc0f1b0ca84641fb", + "crosswalk_family.py": "68ee6327a7a24ab74e77bdbbc9c504562f6997cfb7f0e6082095b3e2eb32fc2d", + "fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8", + "layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59", + "line_family_completion.py": "4267dc01d7442bc1c8782dd104ff3c5d8ac67f9551711b29ffe7f748424dd37c", + "refine_paint.py": "99a262cececbf23b46a0ceb17f99af13a7a1148bbbb2e0b17e656b157a359019", + "render_families.py": "772631ff02f65022e0ca800ae8cc4ebea8b57e5b953411ea86701c8f41757a2d", + "render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064", + "test_families.py": "d213eca861031cb105ea250c49d44bbc2630367f9d6447d1a7c5a6da6d3d50c9" + }, + "external_review_font": { + "name": "review-font.ttf", + "sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9", + "purpose": "rendering only; qualified file retained under qualification source; omitted from public source ZIP" + }, + "deployment": false +} \ No newline at end of file diff --git a/simulation/urban-plan-research/families_pass/crossing_completion.py b/simulation/urban-plan-research/families_pass/crossing_completion.py new file mode 100644 index 00000000..9042f874 --- /dev/null +++ b/simulation/urban-plan-research/families_pass/crossing_completion.py @@ -0,0 +1,106 @@ +"""Crossing-level reconstruction using the existing brightness-profile method. + +SciPy peak detection supplies observed stripe centres. Robust shared ends and +widths give rectangular paint. No site coordinates or arbitrary missing slots. +""" +import numpy as np,cv2,shapely +from shapely.geometry import shape,Polygon +from scipy.ndimage import gaussian_filter1d +from scipy.signal import find_peaks,peak_widths +from scipy.optimize import least_squares +from crosswalk_family import rectangle_info + +def observations(features): + out=[] + for f in features: + if f['properties'].get('subtype')!='crosswalk':continue + p=shapely.force_2d(shape(f['geometry'])) + if p.geom_type!='Polygon':continue + box,c,u,v=rectangle_info(np.asarray(p.exterior.coords));a=(box-c)@u;b=(box-c)@v;L=np.ptp(a);W=np.ptp(b) + if L>1 and .122:out.append(dict(f=f,p=p,box=box,center=c,u=u,v=v,L=L,W=W)) + return out + +def groups(obs): + parent=list(range(len(obs))) + def root(i): + while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i] + return i + for i,a in enumerate(obs): + for j,b in enumerate(obs[:i]): + delta=b['center']-a['center'] + if abs(a['u']@b['u'])max(1.2,.25*max(a['L'],b['L'])):continue + if abs(delta@a['v'])>6 or abs(a['L']-b['L'])>.55*max(a['L'],b['L']):continue + parent[root(i)]=root(j) + result={} + for i in range(len(obs)):result.setdefault(root(i),[]).append(obs[i]) + return list(result.values()) + +def model(group): + angles=np.array([np.arctan2(o['u'][1],o['u'][0])for o in group]);theta=.5*np.arctan2(np.sin(2*angles).sum(),np.cos(2*angles).sum());u=np.array([np.cos(theta),np.sin(theta)]);v=np.array([-u[1],u[0]]);origin=np.mean([o['center']for o in group],axis=0) + centers=np.array([(o['center']-origin)@v for o in group]);lo=np.array([((o['box']-origin)@u).min()for o in group]);hi=np.array([((o['box']-origin)@u).max()for o in group]) + def fit(y): + A=np.c_[np.ones(len(centers)),centers];x=np.linalg.lstsq(A,y,rcond=None)[0];x[1]=np.clip(x[1],-.35,.35) + return least_squares(lambda x:A@x-y,x,bounds=([-np.inf,-.35],[np.inf,.35]),loss='soft_l1',f_scale=.12).x + left,right=fit(lo),fit(hi);width=float(np.median([o['W']for o in group])) + return dict(origin=origin,u=u,v=v,left=left,right=right,width=width,centers=centers) + +def recover(m,sampler): + """sampler(xy) returns Gaussian RGB and vehicle/road/crosswalk support.""" + step=.025;c=m['centers'];s=np.arange(c.min()-2.,c.max()+2.+step,step);left=m['left'][0]+m['left'][1]*s;right=m['right'][0]+m['right'][1]*s + t=left[:,None]+(right-left)[:,None]*np.linspace(.2,.8,48)[None,:];xy=m['origin']+t[:,:,None]*m['u']+s[:,None,None]*m['v'] + rgb,veh,road,cross=sampler(xy.reshape(-1,2));rgb=rgb.reshape(len(s),48,3).astype('uint8');gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY).astype(float) + interior=(s>=c.min()-.3)&(s<=c.max()+.3) + valid=(veh.reshape(len(s),48)<.3)&((road.reshape(len(s),48)>.5)|interior[:,None]);values=np.where(valid,gray,np.nan) + count=np.sum(valid,axis=1);signal=np.divide(np.nansum(values,axis=1),count,out=np.zeros(len(s)),where=count>0) + known=count>=32 + # Unknown samples must not become artificial black troughs with bright peaks + # on their sides. Interpolation is used only for signal analysis, not evidence. + signal=np.interp(s,s[known],signal[known])if known.any()else np.zeros(len(s));signal=gaussian_filter1d(signal,1.) + peaks,props=find_peaks(signal,prominence=10,distance=int(.6/step));width_info=peak_widths(signal,peaks,rel_height=.5);widths=width_info[0]*step;midpoints=s[0]+(width_info[2]+width_info[3])*.5*step + candidates=[] + for j,k in enumerate(peaks): + if not .20<=widths[j]<=.95 or count[k]<32:continue + candidates.append(dict(center=float(midpoints[j]),width=float(widths[j]),prominence=float(props['prominences'][j]),observed=True,cross_support=float(np.mean(cross.reshape(len(s),48)[k]>.2)))) + # Alternating white/yellow crossings need colour evidence: luminance peaks + # alone merge adjacent colours or keep only the brighter white bands. + hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);bright=hsv[:,:,1][(gray>100)&valid];sat=float(cv2.threshold(bright,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[0])if len(bright)else 70;sat=float(np.clip(sat,35,85));yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>sat)&(hsv[:,:,2]>100)&valid + ys=gaussian_filter1d(np.mean(yellow,axis=1),1.);yp,yprop=find_peaks(ys,prominence=.3,height=.45,distance=int(.35/step));yw=peak_widths(ys,yp,rel_height=.5) + yellows=[] + for j,k in enumerate(yp): + width=yw[0][j]*step;center=s[0]+(yw[2][j]+yw[3][j])*.5*step + if .2<=width<=.85 and count[k]>=32:yellows.append(dict(center=float(center),width=float(width),prominence=float(yprop['prominences'][j]*100),observed=True,color_evidence='yellow',cross_support=float(np.mean(cross.reshape(len(s),48)[k]>.2)))) + if len(yellows)>=3: + gval=gray[valid].astype('uint8');bright_threshold=float(cv2.threshold(gval,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[0])if len(gval)else 115 + white=(~yellow)&(gray>max(100,bright_threshold))&valid;ws=gaussian_filter1d(np.mean(white,axis=1),1.);wp,wprop=find_peaks(ws,prominence=.3,height=.45,distance=int(.35/step));ww=peak_widths(ws,wp,rel_height=.5);whites=[] + for j,k in enumerate(wp): + width=ww[0][j]*step;center=s[0]+(ww[2][j]+ww[3][j])*.5*step + if .2<=width<=.85 and count[k]>=32:whites.append(dict(center=float(center),width=float(width),prominence=float(wprop['prominences'][j]*100),observed=True,color_evidence='white',cross_support=float(np.mean(cross.reshape(len(s),48)[k]>.2)))) + if len(whites)>=3:candidates=sorted(whites+yellows,key=lambda p:p['center']) + if candidates: + threshold=max(10,.3*np.median([p['prominence']for p in candidates]));candidates=[p for p in candidates if p['prominence']>=threshold] + inside=[p for p in candidates if c.min()-.2<=p['center']<=c.max()+.2];positions=np.array(sorted(p['center']for p in inside));deltas=np.diff(positions);deltas=deltas[(deltas>.65)&(deltas<1.7)];period=float(np.median(deltas))if len(deltas)>=2 else None + def exterior_allowed(p): + if c.min()-.2<=p['center']<=c.max()+.2:return True + if period is None:return p['cross_support']>.6 + distance=float(np.min(abs(positions-p['center'])));slots=round(distance/period) + return 1<=slots<=2 and abs(distance-slots*period)<.18 and p['prominence']>max(15,.3*np.median([r['prominence']for r in inside])) + candidates=[p for p in candidates if exterior_allowed(p)] + # Align retained observations to actual peaks, deduplicating previous overlaps. + result=[];observed_width=float(np.median([p['width']for p in candidates]))if candidates else m['width'];separation=max(.25,.85*observed_width) + for seed in sorted(c): + near=min(candidates,key=lambda p:abs(p['center']-seed),default=None) + rec=near.copy()if near and abs(near['center']-seed)<.42 else dict(center=float(seed),width=m['width'],observed=False) + if any(abs(rec['center']-x['center'])1:width=min(width,.95*min(np.diff([r['center']for r in result]))) + for r in result: + s0=r['center'];lo=m['left'][0]+m['left'][1]*s0;hi=m['right'][0]+m['right'][1]*s0 + uv=np.array([[lo,s0-width/2],[hi,s0-width/2],[hi,s0+width/2],[lo,s0+width/2],[lo,s0-width/2]]) + r['polygon']=Polygon(m['origin']+uv[:,0,None]*m['u']+uv[:,1,None]*m['v']) + return result,dict(observed_peaks=len(candidates),new_stripes=sum(r['new']for r in result),input_observations=len(c),output_stripes=len(result),width_m=width,yellow_peaks=len(yellows),saturation_threshold=sat,peak_prominences=[r.get('prominence')for r in result],centers=[dict(center=r['center'],observed=r['observed'],new=r['new'],color=r.get('color_evidence','luminance'))for r in result],matched_observations=sum(r['observed']and not r['new']for r in result)) diff --git a/simulation/urban-plan-research/families_pass/line_family_completion.py b/simulation/urban-plan-research/families_pass/line_family_completion.py new file mode 100644 index 00000000..3c7d29b4 --- /dev/null +++ b/simulation/urban-plan-research/families_pass/line_family_completion.py @@ -0,0 +1,60 @@ +"""Complete periodic dash families, including short intersection guide dashes. + +OpenCV robust line fits and median period/width estimates; no site constants. +Only bounded internal slots may be reconstructed, never a new exterior lane. +""" +import numpy as np,cv2,shapely +from shapely.geometry import shape,Polygon,LineString +from layer_common import feature + +def normalize(features,lift,admit): + records=[];untouched=[] + for f in features: + g=shapely.force_2d(shape(f['geometry'])) + if f['properties'].get('subtype')!='linear_marking' or g.geom_type!='Polygon':untouched.append(f);continue + rect=cv2.minAreaRect(np.asarray(g.exterior.coords,np.float32));box=cv2.boxPoints(rect);edges=np.roll(box,-1,axis=0)-box;k=np.argmax(np.linalg.norm(edges,axis=1));L=np.linalg.norm(edges[k]);W=min(rect[1]);u=edges[k]/L + if not( .252.5 and g.area/(L*W)>.68):untouched.append(f);continue + records.append(dict(f=f,g=g,center=np.array(rect[0]),axis=u,L=L,W=W)) + parent=list(range(len(records))) + def root(i): + while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i] + return i + for i,a in enumerate(records): + u=a['axis'];n=np.array([-u[1],u[0]]) + for j,b in enumerate(records[:i]): + delta=b['center']-a['center'] + if abs(u@b['axis']).18:continue + gap=abs(delta@u)-(a['L']+b['L'])/2 + if gap>12 or abs(delta@u)>55:continue + parent[root(i)]=root(j) + groups={} + for i in range(len(records)):groups.setdefault(root(i),[]).append(i) + output=list(untouched);audit=[] + for ids in groups.values(): + originals=[records[i]['f']for i in ids] + if len(ids)<2:output.extend(originals);continue + samples=np.concatenate([records[i]['center']+np.linspace(-records[i]['L']/2,records[i]['L']/2,max(3,int(records[i]['L']/.5)))[:,None]*records[i]['axis']for i in ids]) + fit=cv2.fitLine(samples.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=fit[:2];o=fit[2:];n=np.array([-u[1],u[0]]) + if np.max(abs((samples-o)@n))>.24:output.extend(originals);continue + ranges=sorted([((records[i]['center']-o)@u-records[i]['L']/2,(records[i]['center']-o)@u+records[i]['L']/2)for i in ids]);merged=[] + for a,b in ranges: + if merged and a<=merged[-1][1]+.15:merged[-1][1]=max(b,merged[-1][1]) + else:merged.append([a,b]) + widths=[records[i]['W']for i in ids];width=float(np.median(widths));lengths=np.array([b-a for a,b in merged]);centers=np.array([(a+b)/2 for a,b in merged]);gaps=np.array([b[0]-a[1]for a,b in zip(merged[:-1],merged[1:])]) + intervals=None;mode=None;added=0 + if len(merged)>=3 and np.std(lengths)/np.mean(lengths)<.35: + deltas=np.diff(centers);period=float(np.median(deltas[deltas<=np.quantile(deltas,.65)]));L=float(np.median(lengths)) + if period>L*1.3 and period<15: + slots=np.rint((centers-centers[0])/period).astype(int);phase=float(np.median(centers-slots*period)) + residual=np.max(abs(centers-(phase+slots*period))) + if residual.02:return False + ring=shapely.force_2d(p).exterior;xy=np.array([ring.interpolate(t).coords[0]for t in np.linspace(0,ring.length,max(5,int(ring.length/.2)))]) + return float(np.mean(sample(labels,xy,low,high)==1))>.8 +features,line_audit=normalize(features,lift,admit_line) +(O/'line-families.json').write_text(json.dumps(line_audit,indent=2,allow_nan=False)) +result={**old,'features':features,'review_status':'unreviewed','paint_refinement':'crosswalk-brightness-profile-v1'} +(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'crosswalk-families.json').write_text(json.dumps(reports,indent=2,allow_nan=False)) +report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),groups=len(reports),accepted_groups=sum(r['accepted']for r in reports),replaced_stripes=len(changes),result_stripes=len(added),recovered_stripes=sum(r.get('new_stripes',0)for r in reports if r['accepted']),manual_geometry=False,manual_rois=[],policy_version='crosswalk-brightness-profile-v1') +report.update(periodic_line_families=len(line_audit),filled_dash_slots=sum(r['added_internal_m_or_slots']for r in line_audit)) +(O/'paint-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True) diff --git a/simulation/urban-plan-research/families_pass/render_families.py b/simulation/urban-plan-research/families_pass/render_families.py new file mode 100644 index 00000000..e38eded5 --- /dev/null +++ b/simulation/urban-plan-research/families_pass/render_families.py @@ -0,0 +1,37 @@ +from pathlib import Path +import json,os,shutil +from datetime import datetime,timezone +import numpy as np +from PIL import Image,ImageDraw,ImageFont +from layer_common import O,S +from fit_scene import project +old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=json.loads((O/'crosswalk-families.json').read_text());font=ImageFont.truetype('/candidate/review-font.ttf',23) +for p in O.glob('crosswalk-*.jpg'): + history=O/'attempts'/('crosswalk-render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));history.mkdir(parents=True,exist_ok=True);shutil.move(p,history/p.name) +def draw(im,g,features,subtypes=('crosswalk',)): + im=im.copy();d=ImageDraw.Draw(im);scale=im.width/1200 + for f in features: + if f['properties'].get('subtype')not in subtypes:continue + for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*scale],fill='#f1c300',width=max(3,int(scale*2))) + return im +pages=[];frames=[] +for rec in groups: + if not rec['accepted']:continue + gi=rec['group'];name=rec['source_tile'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');scale=raw.width/1200 + x0,y0,x1,y1=rec['bounds_xy'];uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*scale;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*2.5/60;bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До: '+str(rec['input_stripes'])),(draw(raw,g,new['features']),'После: '+str(rec['output_stripes']))]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640') + fn='crosswalk-%02d.jpg'%gi;frame.save(O/fn,quality=95);frames.append(frame);pages.append(dict(group=gi,file=fn,new_stripes=rec['new_stripes'],source_tile=name)) +for start in range(0,len(frames),4): + part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white') + for k,im in enumerate(part):sheet.paste(im,(0,k*655)) + sheet.save(O/('crosswalk-proof-%02d.jpg'%(start//4+1)),quality=95) +(O/'crosswalk-visual-manifest.json').write_text(json.dumps(pages,indent=2));print('RENDERED',len(pages),'crossings') +tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];line_pages=[] +for gi,rec in enumerate(json.loads((O/'line-families.json').read_text())): + x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');scale=raw.width/1200 + uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*scale;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*3/60;bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame) + for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features'],('crosswalk','linear_marking')),'До'),(draw(raw,g,new['features'],('crosswalk','linear_marking')),'После')]): + frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),'Штрихи '+str(gi)+' · '+label,font=font,fill='#263640') + fn='line-family-%02d.jpg'%gi;frame.save(O/fn,quality=95);line_pages.append(dict(group=gi,file=fn,source_tile=name,added_slots=rec['added_internal_m_or_slots'])) +(O/'line-visual-manifest.json').write_text(json.dumps(line_pages,indent=2));print('RENDERED',len(line_pages),'line families') diff --git a/simulation/urban-plan-research/families_pass/test_families.py b/simulation/urban-plan-research/families_pass/test_families.py new file mode 100644 index 00000000..4079f698 --- /dev/null +++ b/simulation/urban-plan-research/families_pass/test_families.py @@ -0,0 +1,38 @@ +import numpy as np,cv2,json +from pathlib import Path +from shapely.geometry import Polygon,mapping,shape +from crossing_completion import observations,groups,model,recover +checks={} +def fixture(centers,seed_ids,angle=0,offset=(0,0),occluded=(),black=(),yellow=(),gradient=False): + a=angle;R=np.array([[np.cos(a),-np.sin(a)],[np.sin(a),np.cos(a)]]);o=np.array(offset);fs=[] + for j in seed_ids: + p=np.array([[-2,centers[j]-.25],[2,centers[j]-.25],[2,centers[j]+.25],[-2,centers[j]+.25]])@R.T+o + fs.append(dict(id=str(j),geometry=mapping(Polygon(p)),properties=dict(subtype='crosswalk'))) + m=model(observations(fs)) + def sampler(xy): + uv=(xy-o)@R;white=np.zeros(len(xy),bool);veh=np.zeros(len(xy)) + for j,s in enumerate(centers): + stripe=(abs(uv[:,1]-s)<.25)&(abs(uv[:,0])<2) + if j not in black:white|=stripe + if j in occluded:veh[stripe]=1 + rgb=np.repeat(np.where(white,220,65)[:,None],3,axis=1).astype('uint8') + for j,s in enumerate(centers): + stripe=(abs(uv[:,1]-s)<.25)&(abs(uv[:,0])<2) + if j in yellow:rgb[stripe]=[235,190,55] + elif gradient:rgb[stripe]=np.repeat((180+120*(uv[stripe,1]-s+.25))[:,None],3,axis=1).astype('uint8') + return rgb,veh,np.ones(len(xy)),np.zeros(len(xy)) + return recover(m,sampler) +r,stats=fixture(np.arange(9),[0,1,3,4,7,8]);checks['three_observed_missing_stripes_recovered']=stats['new_stripes']==3 and len(r)==9 +r,stats=fixture(np.arange(9),[0,1,3,4,7,8],black=[2,5,6]);checks['no_invisible_stripes_invented']=stats['new_stripes']==0 +r,stats=fixture(np.arange(9),[0,1,3,4,7,8],occluded=[2,5,6]);checks['vehicle_is_not_paint']=stats['new_stripes']==0 +r,stats=fixture(np.arange(9),[0,1,3,4,7,8],angle=.72,offset=(500,-300));checks['rigid_transform_invariant']=stats['new_stripes']==3 and len(r)==9 +checks['rectangles_do_not_overlap']=not any(a['polygon'].intersection(b['polygon']).area>1e-6 for i,a in enumerate(r)for b in r[:i]) +r,stats=fixture(np.arange(9),[0,1,3,4,7,8]);checks['no_invisible_exterior_generation']=len(r)==9 and all(-.2