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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -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.
@@ -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']
@@ -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
}
@@ -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 .26<L<=10.5 or not 1.1*L<P<8*L:continue
if abs(d['length']-L)>max(.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)<POLICY['min_family_anchors']or ids in seen:continue
seen.add(ids);xy=np.array([r['origin']for r in c]);line=cv2.fitLine(xy.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();v=line[:2].astype(float);v/=np.linalg.norm(v)
if v@u<0:v=-v
o=xy.mean(0);n=np.array([-v[1],v[0]]);t=(xy-o)@v
if np.max(abs((xy-o)@n))>.10 or abs(v@u)<np.cos(np.deg2rad(3))or np.ptp(t)>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']<paint['contrast']*POLICY['max_gap_paint_ratio'])
def slot(seed,index,readers,debug=None):
if len(readers)!=2:return None
o,u=seed['origin'],seed['axis'];P,L,W=seed['period'],seed['length'],seed['width'];c=index*P;step=POLICY['step_m'];ext=min(P/2,L/2+max(.4,.25*L));ts=np.arange(c-ext,c+ext+step/2,step);ns=np.arange(-.70,.701,step);ev=[]
for read in readers:
contrast,allowed=strip(o,u,ts,ns,read);core=abs(ts-c)<.3*L
transverse=np.median(np.where(allowed[core],contrast[core],0),axis=0)
peaks,_=find_peaks(transverse,height=22,prominence=10,distance=4);peaks=[k for k in peaks if abs(ns[k])<=POLICY['max_slot_offset_m']]
if not peaks:
if debug is not None:debug.update(reason='no-ridge',peak=float(transverse.max()))
return None
k=min(peaks,key=lambda k:abs(ns[k]));width=float(peak_widths(transverse,[k],rel_height=.5)[0][0]*step)
if not .045<=width<=.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.median(sig[core]));cut=max(15.,.35*level);paint=(sig>cut)&valid
for a,b in runs(~paint):
if a>0 and b<len(ts)and(b-a)*step<=.125 and valid[a:b].all():paint[a:b]=True
options=[(a,b)for a,b in runs(paint)if a>0 and b<len(ts)and abs((ts[a]+ts[b-1])/2-c)<=POLICY['max_family_phase_m']and abs((b-a)*step-L)<=max(POLICY['slot_length_absolute_error_m'],POLICY['slot_length_relative_error']*L)]
# A short dash may sit above worn paint. Reuse measured peak widths;
# a continuous line without a prominent bounded peak still fails.
if not options and L<1.45:
pk,_=find_peaks(np.where(valid,sig,0),prominence=22,distance=max(1,int(.45/step)))
ws=peak_widths(np.where(valid,sig,0),pk,rel_height=.5)
options=[(int(round(ws[2][j])),int(round(ws[3][j]))+1)for j,kp in enumerate(pk)if abs(ts[kp]-c)<=POLICY['max_family_phase_m']and abs(ws[0][j]*step-L)<=max(POLICY['slot_length_absolute_error_m'],POLICY['slot_length_relative_error']*L)]
options=[(a,b)for a,b in options if a>0 and b<len(ts)]
if not options:
if debug is not None:debug.update(reason='no-bounded-stroke',level=level,intervals=[(float(ts[a]-c),float(ts[b-1]-c))for a,b in runs(paint)])
return None
a,b=min(options,key=lambda ab:abs((ts[ab[0]]+ts[ab[1]-1])/2-c));lo,hi=float(ts[a]-step/2),float(ts[b-1]+step/2);center=(lo+hi)/2
inside=(ts>=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<cut).mean()),contrast=float(np.median(ss)),q80=float(np.quantile(ss,.8)),full_corridor=True))
if not supported(positive)or not all(gap_supported(g,positive)for g in gaps):
if debug is not None:debug.update(reason='paint-or-gap-evidence',paint=positive,gaps=gaps)
return None
ev.append(dict(edges=[lo,hi],offset=float(ns[k]),width=width,paint=positive,gaps=gaps))
if abs(ev[0]['offset']-ev[1]['offset'])>.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'])<np.cos(np.deg2rad(4)):return None
# Tolerance is geometric pixel-scale uncertainty, not a traffic standard.
cut=bar.buffer(.025,join_style=2);part=source.intersection(cut)
if part.is_empty or part.area<.06:return None
tt=(np.asarray(bar.exterior.coords)-a['center'])@a['axis'];lo=max(-a['L']/2,float(tt.min()));hi=min(a['L']/2,float(tt.max()))
if hi-lo<.6:return None
common=source.intersection(rectangle(a['center'],a['axis'],lo,hi,4))
if common.is_empty or common.intersection(bar).area/common.area<.9:return None
return cut
def bar_supported(evidence):
# Paint outside the retained bar is not removed by this operation. Its
# unexplained-paint recall must not veto removal of an internal duplicate.
return len(evidence)==2 and all(e['valid']>=.98 and e['support']>=.85 for e in evidence)
@@ -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).area<POLICY['min_material_change_m2']:return False
if novel.intersection(protected).area>POLICY['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['min_anchor_reobserved']:continue
extension=min(POLICY['max_extension_slots'],int(POLICY['max_extension_distance_m']/g['period']))
targets=[list(range(0,g['max_index']+1)),list(range(-1,-extension-1,-1)),list(range(g['max_index']+1,g['max_index']+extension+1))]
additions=[];evidence=[]
for sequence in targets:
missed=0
for index in sequence:
debug={};r=slot(g,index,readers,debug)
diagnostics.append(dict(stage='slot',family=fi,index=index,passed=r is not None,**debug))
if r is None:
missed+=1
if sequence is not targets[0]and missed>=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)<np.cos(np.deg2rad(3))or abs((d['origin']-origin)@n)>.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)
@@ -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))
@@ -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<missing[1])]=False
return rgb,valid
return read
read=reader(range(-5,6));r=slot(seed,4,[read,read]);checks['single_outside_slot_observed']=r is not None
checks['row_axis_and_dimensions_preserved']=r is not None and r['polygon'].symmetric_difference(rectangle(o,u,3.75,4.25,.12)).area<1e-9
checks['one_view_not_enough']=slot(seed,4,[read])is None
absent=reader([0,1,2]);checks['period_does_not_invent_paint']=slot(seed,4,[read,absent])is None
unknown=reader(range(-5,6),missing=(3.8,4.1));checks['occluded_slot_not_filled']=slot(seed,4,[read,unknown])is None
boundary=reader(range(-5,6),missing=(4.3,4.6));checks['unknown_gap_not_dark_asphalt']=slot(seed,4,[read,boundary])is None
solid=reader([],solid=True);checks['solid_not_cut_into_dashes']=slot(seed,4,[solid,solid])is None
neighbor=reader(range(-5,6),offset=.3);checks['nearby_lane_not_claimed']=slot(seed,4,[neighbor,neighbor])is None
shifted=reader(range(-5,6),offset=.08);checks['two_view_ridge_disagreement_rejected']=slot(seed,4,[read,shifted])is None
records=[(str(i),rectangle(o,u,i-.25,i+.25,.12),dict(line_kind='dashed',period_m=1.,dash_length_m=.5))for i in [0,1,3,4]]
g=families(records);checks['missing_internal_slot_keeps_family']=len(g)==1 and g[0]['max_index']==4
checks['two_anchors_insufficient']=not families(records[:2])
checks['neighbor_parallel_rows_separate']=len(families(records+[(f'b{i}',rectangle(np.array([0,.8]),u,i-.25,i+.25,.12),p)for i,(_,_,p)in enumerate(records)]))==2
checks['two_views_same_offset_cannot_draw_wrong_axis']=slot(seed,4,[shifted,shifted])is None
worn=reader(range(-5,6),underlay=40);checks['bounded_peaks_over_worn_underlay']=slot(seed,4,[worn,worn])is not None
checks['underlay_alone_is_not_dash']=slot(seed,4,[reader([],underlay=40),reader([],underlay=40)])is None
from shapely.geometry import Polygon
ang=.72;R=np.array([[np.cos(ang),-np.sin(ang)],[np.sin(ang),np.cos(ang)]]);shift=np.array([100,-70]);sr={**seed,'origin':shift,'axis':R@u};rr=lambda xy:read((xy-shift)@R)
rot=slot(sr,4,[rr,rr]);checks['rigid_transform_equivalent']=rot is not None and abs(rot['polygon'].area-r['polygon'].area)<1e-8
long=describe(rectangle(o,u,0,20,.12))
def tail(xy):
x,y=xy.T;center=np.where(x<15,-.1,0);on=(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']