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,48 @@
# Semantic-local recall pass
This offline Gaussian-only pass consumes the accepted coverage-audit map.
It changes no road, pedestrian or façade geometry. It preserves prior review
provenance and proposes additional clean bicycle/arrow presets.
## Candidate assembly
The previous component pass could discard a correct semantic mask when its
paint belonged to a larger connected background component. A failed global
component selection also skipped the independent mask-local proposal path.
`recall_targets.py` retains the existing proposal method and adds metric
3 cm / 10 cm mask-local paint windows at the existing two scales. These are
candidate transforms only: the semantic mask never supplies final geometry or
crops the image used for acceptance. The existing licensed presets and SciPy
fitters remain in use. Every available full view, negative space, contextual
lane evidence and foreign-marking overlap must still pass.
## Evidence options under qualification
The component evidence helpers accept opt-in ground-only Otsu calibration and
metric morphological opening for arrow connectivity. Default callers retain
the earlier behavior. Calibration uses observed valid surface, never a fitted
preset; white unobserved/background regions cannot determine paint contrast.
Opening removes pixel-width bridges before the whole-connected-object test;
positive paint, head/tail/branch checks and end probes use the original paint.
Bicycle connectivity is not opened because its real strokes are thin.
The qualified bundle and policy record which options are admitted.
## Reproducibility and acceptance
Use Worker006 and the bounded reservation/container runner in
`.runtime/simulation-qualifications/recall-pass-20261014/operator`.
Freeze the complete source bundle and run tests, refinement, geometry audit,
visual rendering and full-map rendering on all three scenes. Human review of
all additions is a publication gate, not an inference input. No scene identity,
manual processing ROI, coordinate whitelist or point-cloud evidence is used.
The comparison scenes are development/regression data, not an independent
unseen-map accuracy measurement.
Use the canonical qualified-map publisher only after verification and visual
review. Publication status and counts are defined by the final verification
and publication receipts, not this README or experimental images. Existing
zebras remain unchanged in this pass; the previous failed rail extrapolation
must not be reintroduced. This is a research pipeline connected through its
qualified maps, not a new one-click product computation workflow.
Whole-semantic-object admission rejects a head-only child mask when a parent mask contains the shaft. Curved 1.19 presets use Major Alexey's artwork (CC BY-SA 4.0), sampled and metrically normalized; the source digest is in recall_templates.py. This is a visual preset, not verification of regulatory dimensions.
@@ -0,0 +1,38 @@
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 recall_templates import template
from recall_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
from component_targets import vector
from recall_extent import semantic_extent,semantic_recall,EXTENT_POLICY
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/'recall-rows.json').read_text());report=json.loads((O/'recall-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']};ci=0 if kind=='bicycle'else 1;spec=next(v for v in patches['patches']if v['id']==r['patch']);seed=shapely.union_all([vector(z['masks'][i],spec)for i in r['masks']]);regions=[(i,vector(m,spec))for i,(m,s,cl)in enumerate(zip(z['masks'],z['scores'],z['classes']))if cl==ci and s>=(.30 if ci==0 else .50)];extent,indices=semantic_extent(seed,regions);complete=semantic_recall(q,extent)
checks['semantic_trace']&=indices==r['semantic_extent_masks']==p['semantic_extent_masks']and abs(complete-r['semantic_recall'])<1e-9 and complete>=EXTENT_POLICY['min_semantic_recall']
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['recall_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/'recall-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,158 @@
{
"source_snapshot": "3a3fc952c86cf7505764",
"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",
"recall_extent.py": "recall_pass/recall_extent.py",
"render_recall.py": "recall_pass/render_recall.py",
"refine_recall.py": "recall_pass/refine_recall.py",
"recall_rules.py": "recall_pass/recall_rules.py",
"recall_templates.py": "recall_pass/recall_templates.py",
"diagnose_recall.py": "recall_pass/diagnose_recall.py",
"recall_targets.py": "recall_pass/recall_targets.py",
"test_recall.py": "recall_pass/test_recall.py",
"audit_recall.py": "recall_pass/audit_recall.py"
}
}
@@ -0,0 +1,26 @@
from pathlib import Path
import json,cv2,numpy as np,shapely,hashlib,collections
from PIL import Image,ImageDraw,ImageFont
from component_targets import targets,vector
from layer_common import parts
I=Path('/symbolplan');O=Path('/out');cv2.setNumThreads(3)
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());font=ImageFont.truetype('/candidate/review-font.ttf',16);rows=[];panels=[]
for rec in sem['records']:
if not rec['detections']:continue
p=patches[rec['id']];im=np.asarray(Image.open(I/'symbol-patches'/(p['id']+'.png')).convert('RGB'))
with np.load(I/'symbol-masks'/(p['id']+'.npz'))as z:masks=z['masks'];scores=z['scores'];classes=z['classes']
ps=targets(im,p,masks,scores,classes)
for j,(m,score,ci) in enumerate(zip(masks,scores,classes)):
region=vector(m,p);gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV);k=int(.72/p['mpp'])//2*2+1;ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)));white=(ridge>12)&(gray>100)&(hsv[:,:,1]<100)&~((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>65))
chosen=[v for v in ps if j in v['masks']and v['ci']==ci]
row=dict(patch=p['id'],mask=j,ci=int(ci),score=float(score),semantic_area=region.area,white_area=float((white&m.astype(bool)).sum()*p['mpp']**2),gray_quantiles=np.quantile(gray[m>0],[0,.1,.5,.9,1]).tolist(),ridge_quantiles=np.quantile(ridge[m>0],[0,.1,.5,.9,1]).tolist(),targets=len(chosen),target_area=[v['target'].area for v in chosen]);rows.append(row)
if ci!=0:continue
frame=Image.new('RGB',(1000,390),'white');d=ImageDraw.Draw(frame);d.text((5,5),p['id']+' mask '+str(j)+' score %.2f'%score+' targets '+str(len(chosen)),font=font,fill='black')
for k,a in enumerate([im,np.where(m[:,:,None]>0,im,im//4),np.where(white[:,:,None],255,0).astype('uint8').repeat(3,axis=2)]):
tile=Image.fromarray(a);tile.thumbnail((330,330));frame.paste(tile,(k*333,50))
d.text((5,367),'white %.3f m2; gray '%row['white_area']+str(row['gray_quantiles']),font=font,fill='black');panels.append(frame)
for i in range(0,len(panels),4):
group=panels[i:i+4];sheet=Image.new('RGB',(1000,len(group)*390),'white')
for j,panel in enumerate(group):sheet.paste(panel,(0,j*390))
sheet.save(O/('recall-diagnostic-%02d.jpg'%(i//4)),quality=95)
(O/'recall-diagnostics.json').write_text(json.dumps(rows,indent=2));print('RECORDS',len(rows),'BIKES',sum(x['ci']==0 for x in rows));print(json.dumps([x for x in rows if x['ci']==0],indent=2))
@@ -0,0 +1,8 @@
"""Reject a preset fitted only to a child mask of a longer semantic object."""
import shapely
EXTENT_POLICY=dict(parent_seed_fraction=.70,preset_tolerance_m=.12,min_semantic_recall=.85)
def semantic_extent(seed,regions):
parents=[(i,p)for i,p in regions if not p.is_empty and p.intersection(seed).area/max(seed.area,1e-9)>=EXTENT_POLICY['parent_seed_fraction']]
return shapely.union_all([seed]+[p for _,p in parents]),[i for i,_ in parents]
def semantic_recall(preset,extent):
return float(preset.buffer(EXTENT_POLICY['preset_tolerance_m']).intersection(extent).area/max(extent.area,1e-9))
@@ -0,0 +1,10 @@
from component_rules import POLICY as COMPONENT_POLICY,accept_symbol
VERSION='semantic-local-recall-v4'
POLICY={**COMPONENT_POLICY,'candidate_sources':['global-components','semantic-local-paint'],'candidate_mask_margins_m':[.03,.10],'calibration':'observed-valid-ground','arrow_connectivity_open_m':.08}
from recall_extent import EXTENT_POLICY
POLICY['semantic_extent']=EXTENT_POLICY
from recall_templates import KINDS,SOURCE_SHA256
POLICY['arrow_kinds']=KINDS
POLICY['curved_artwork_sha256']=SOURCE_SHA256
@@ -0,0 +1,28 @@
"""Semantic-local paint candidates survive a noisy global connected component.
Mask clipping proposes a transform only. Complete unmasked Gaussian image
mosaics must still validate every final preset and all its negative space.
"""
import numpy as np,cv2
from component_targets import targets as component_targets,vector
def targets(image,p,masks,scores,classes):
result=component_targets(image,p,masks,scores,classes)
gray=cv2.cvtColor(image,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(image,cv2.COLOR_RGB2HSV)
yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>65)
for scale in [.72,3.0]:
radius=int(scale/p['mpp'])//2*2+1
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(radius,radius)))
white=(ridge>12)&(gray>100)&(hsv[:,:,1]<100)&~yellow
for i,(mask,score,ci) in enumerate(zip(masks,scores,classes)):
if ci not in [0,1] or score<(.30 if ci==0 else .50):continue
region=vector(mask,p)
# Metric dilation, independent of source-image resolution.
for margin in [.03,.10]:
k=max(3,int(2*margin/p['mpp'])//2*2+1)
local=cv2.dilate(mask.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))>0
target=vector(white&local,p)
if target.is_empty or target.area<.08:continue
if any(ci==x['ci'] and target.symmetric_difference(x['target']).area<.02 for x in result):continue
result.append(dict(target=target,ci=int(ci),region=region,score=float(score),masks=[i],paint_scale_m=scale,candidate_source='semantic-local-paint',margin_m=margin))
return result
@@ -0,0 +1,17 @@
"""Curved arrow artwork adapted from Major Alexey's marking 1.19.
Source: https://commons.wikimedia.org/wiki/File:1.19_Russian_road_marking.svg
License: https://creativecommons.org/licenses/by-sa/4.0/
Changes: sampled SVG curves, normalized coordinates, metric registration.
The adapted arrow artwork remains CC BY-SA 4.0; no standard compliance claim.
"""
from shapely.affinity import scale
from road_glyph_presets import parse_path
from fragment_templates import template as legacy_template
SOURCE_SHA256='c32984daee1bb4519751afce5be6e73452bd040c73fbceb4e2073ab30fbc6d34'
PATHS={'merge_left_arrow': 'M334.2,305.1c-0.3-6.9-0.6-13.8-0.8-20.6c-0.7-15.9-1.3-31.7-2-47.6c-0.8-17.7-1.5-35.4-2.4-53.1\n\t\t\tc-0.4-8.5-0.4-17.1-2.2-25.4c-1.7-7.9-5.1-15.3-10-21.7c-7-9-17-15.5-27.8-19.2c-1.2-0.4-2.4-0.8-3.7-1.1l-0.1-27.5\n\t\t\tc0-1.1-21.7,36.9-21.7,36.9l22,36.9l-0.1-22.9c14.6,4.1,22.1,19.7,21.7,34.1c-0.3,9.5-1,19-1.6,28.4c-0.9,15-1.8,30-2.8,45\n\t\t\tc-0.9,14.1-1.7,28.1-2.5,42.2c-0.3,5-0.6,10.1-0.8,15.1L334.2,305.1z', 'merge_right_arrow': 'M136.6,125.8c0,0-21.7-38-21.7-36.9l-0.1,27.5c-9.6,2.5-18.7,7.4-26,14.2c-5.4,5-9.6,11.2-12.5,17.9\n\t\t\tc-1.7,4-2.9,8.3-3.7,12.6c-0.8,4.4-1,8.8-1.2,13.3c-0.8,17.2-1.6,34.3-2.3,51.5c-0.7,16.8-1.4,33.6-2.2,50.4\n\t\t\tc-0.4,9.3-0.8,18.6-1.2,27.9c0,0.3,0,0.7,0,1l34.8-0.6c-0.4-10.8-1.1-21.7-1.7-32.5c-0.9-15.4-1.8-30.8-2.8-46.3\n\t\t\tc-0.8-13.4-1.6-26.8-2.4-40.2c-0.2-3.9-0.5-7.8-0.7-11.7c-0.3-6.3,0.7-12.5,3.5-18.2c3.6-7.6,10-13.6,18.2-15.9l-0.1,22.9\n\t\t\tL136.6,125.8z'}
UNIT={k:parse_path(v)for k,v in PATHS.items()}
KINDS=['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow',*UNIT]
def template(kind,length,width,stroke):
if kind not in UNIT:return legacy_template(kind,length,width,stroke)
g=scale(UNIT[kind],length,width,origin=(0,0));delta=(stroke-.16)*.3
return g.buffer(delta,join_style=2)if abs(delta)>.001 else g
@@ -0,0 +1,63 @@
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 recall_targets import targets
from recall_templates import template,KINDS
from component_targets import vector
from recall_extent import semantic_extent,semantic_recall,EXTENT_POLICY
from recall_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']);regions={ci:[(i,vector(m,p))for i,(m,score,cls)in enumerate(zip(z['masks'],z['scores'],z['classes']))if cls==ci and score>=(.30 if ci==0 else .50)]for ci in [0,1]}
for proposal in proposals:
target=proposal['target'];region=proposal['region'];ci=proposal['ci'];score=proposal['score'];extent,extent_masks=semantic_extent(region,regions[ci])
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,kinds=KINDS,template_fn=template)
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'];complete=semantic_recall(q,extent)
if complete<EXTENT_POLICY['min_semantic_recall']:continue
containment=q.intersection(region.buffer(.20)).area/max(q.area,1e-9)
if f['score']<POLICY['bicycle_fit_score'if ci==0 else'arrow_fit_score']or containment<POLICY['min_semantic_fraction']:continue
context=bicycle_context(q,f['parameters'],lines)
if not context['passed']:continue
ev,names=mosaic_views(q,views,kind=kind if ci!=0 else None,parameters=f['parameters']if ci!=0 else None,allow_pedestrian=ci==0,calibrate_ground=True,connectivity_open_m=0. if ci==0 else .08);passed=accept_symbol(ev,score,containment,f['score'],kind)
diag['evaluated'].append(dict(kind=kind,parameters=f['parameters'],evidence=ev,semantic_containment=containment,semantic_recall=complete,semantic_extent_masks=extent_masks,passed=passed,covered=not uncovered(q,existing)))
if not passed:continue
replacements=symbol_replacements(q,kind,current.values())
if replacements is None:continue
out=feature(lift(q),'road_marking',subtype=kind,method=VERSION,source_tile=p['source_tile'],source_tiles=names,standard_compliance='not_assessed',template_parameters=f['parameters'],template_fit_score=f['score'],semantic_score=score,semantic_patch=p['id'],semantic_masks=proposal['masks'],semantic_extent_masks=extent_masks,semantic_recall=complete,lane_context=context)
if out['id']in current:continue
for replaced in replacements:del current[replaced['id']]
current[out['id']]=out;existing=shapely.union_all([poly(v)for v in current.values()if v['properties']['class']=='road_marking']);transactions.append(dict(kind='assembled-symbol',source_ids=[v['id']for v in replacements],output_ids=[out['id']],before=replacements,after=[out],bounds_xy=q.bounds,source_tiles=names,evidence=ev,semantic_containment=containment,semantic_score=score,fit_score=f['score'],patch=p['id'],masks=proposal['masks'],semantic_extent_masks=extent_masks,semantic_recall=complete));print('ADMIT',len(transactions),kind,p['id'],flush=True);break
print('PATCH',p['id'],'CANDIDATES',len(diagnostics),'ADMITTED',len(transactions),flush=True)
result={**old,'features':list(current.values()),'recall_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'recall-rows.json').write_text(json.dumps(transactions,indent=2));(O/'recall-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'crosswalk-standard-check.json').write_bytes(Path('/symbolplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=sha(baseline),semantic_sha256=sha(semantic_file),patch_manifest_sha256=sha(patch_file),changed_segments=len(transactions),added_objects=len(transactions),added_subtypes=dict(collections.Counter(t['after'][0]['properties']['subtype']for t in transactions)),removed_fragments=sum(len(t['before'])for t in transactions),fragment_policy=FRAGMENT_POLICY,policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'recall-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -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/'recall-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('recall-*.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='recall-%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/('recall-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'recall-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,60 @@
import json,runpy
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from catalog_templates import bicycle
from component_targets import targets as old_targets
from recall_targets import targets
from recall_rules import accept_symbol
prior=runpy.run_path('/candidate/test_coverage.py')['result'];checks={}
# A real failure class: a correct semantic object belongs to a much larger
# connected white component. Candidate extraction must not discard its mask.
def fixture(size,angle=0):
cell=8/size;x,y=np.meshgrid(np.arange(size)*cell,np.arange(size)*cell);points=np.c_[x.ravel(),y.ravel()];p=bicycle([2,3,angle,2.,1.1,0.])
m=shapely.contains_xy(p,points[:,0],points[:,1]).reshape(size,size)
# Flooding paint noise connects the symbol to a long stripe outside its mask.
paint=m|((x>1.5)&(x<4.5)&(y>2.7)&(y<3.3))|((x>1.5)&(x<1.8))
rgb=np.repeat(np.where(paint,210,65)[:,:,None],3,axis=2).astype('uint8')
spec=dict(mpp=cell,width_px=size,height_px=size,world_corners=[[0,0],[8,0],[8,8],[0,8]])
return rgb,spec,np.array([m],dtype='uint8'),p
for size in [400,800]:
rgb,spec,m,p=fixture(size)
props=targets(rgb,spec,m,np.array([.8]),np.array([0]))
checks['semantic_candidate_survives_connected_noise_'+str(size)]=any(x.get('candidate_source')=='semantic-local-paint'and x['target'].intersection(p).area/p.area>.75 for x in props)
checks['missing_class_never_creates_bicycle_'+str(size)]=not targets(rgb,spec,m,np.array([.8]),np.array([3]))
checks['below_model_threshold_not_promoted_'+str(size)]=not targets(rgb,spec,m,np.array([.15]),np.array([0]))
checks['uniform_paving_not_a_symbol_'+str(size)]=not targets(np.full_like(rgb,150),spec,m,np.array([.99]),np.array([0]))
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['mask_crop_does_not_authorize_whole_object']=not accept_symbol([{**e,'connected_recall':.4},e],.99,.99,.99,'bicycle')
checks['mask_crop_does_not_hide_second_view_contradiction']=not accept_symbol([e,{**e,'observed_support':.1}],.99,.99,.99,'bicycle')
from component_evidence import directional_score
from paint_channels import paint_mask
from road_glyph_presets import arrow
cell=.04;x,y=np.meshgrid(np.arange(-1,7,cell),np.arange(-2,2,cell));points=np.c_[x.ravel(),y.ravel()];p=arrow('straight_arrow',4,1.2,.16);target=shapely.contains_xy(p,points[:,0],points[:,1]).reshape(x.shape)
rgb=np.repeat(np.where(target,140,65)[:,:,None],3,axis=2).astype('uint8');rgb[x>4.6]=255;ground=x<4.5
pm=paint_mask(rgb,observed=np.ones(x.shape,bool),calibration=ground)
checks['ground_calibration_keeps_gray_arrow_near_white_void']=float(pm[target].mean())>.80
checks['calibration_mask_does_not_imply_paint']=not paint_mask(np.full_like(rgb,150),calibration=ground).any()
# A one-pixel lateral noise bridge is not the width of a painted shaft.
base=np.repeat(np.where(target,220,65)[:,:,None],3,axis=2).astype('uint8')
base[(abs(x-1.5)<.02)&(y>0)]=220
for opening,label in [(0.,'raw'),(.08,'opened')]:
g=directional_score(base,np.ones(x.shape,bool),points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16],connectivity_open_m=opening);g.update(paint_coverage=1.,paint_valid=1.,observed_support=g['support'])
checks['thin_noise_bridge_'+label]=(not accept_symbol([g,g],.99,.99,.99,'straight_arrow'))if opening==0 else accept_symbol([g,g],.99,.99,.99,'straight_arrow')
base[(abs(x-1.5)<.12)&(y>0)]=220
g=directional_score(base,np.ones(x.shape,bool),points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16],connectivity_open_m=.08);g.update(paint_coverage=1.,paint_valid=1.,observed_support=g['support'])
checks['real_wide_continuation_still_rejected']=not accept_symbol([g,g],.99,.99,.99,'straight_arrow')
from recall_extent import semantic_extent,semantic_recall,EXTENT_POLICY
head=Polygon([(4,-.5),(4,.5),(5,0)]);whole=head.union(LineString([(0,0),(4,0)]).buffer(.08));extent,ids=semantic_extent(head,[(0,head),(1,whole)])
checks['head_child_mask_cannot_hide_parent_tail']=ids==[0,1]and semantic_recall(head,extent)<EXTENT_POLICY['min_semantic_recall']
checks['whole_semantic_object_explained']=semantic_recall(whole,extent)>.99
neighbor=shapely.affinity.translate(whole,0,3);extent,ids=semantic_extent(whole,[(0,whole),(1,neighbor)])
checks['neighboring_symbol_not_joined_by_extent']=ids==[0]and extent.equals(whole)
from recall_templates import template,KINDS
from component_arrows import fit_arrows
from shapely.affinity import rotate,translate
for kind in ['merge_left_arrow','merge_right_arrow']:
p=translate(rotate(template(kind,5.,1.3,.16),.37,origin=(0,0),use_radians=True),3,2)
fit=fit_arrows(p,kinds=KINDS,template_fn=template)
checks['curved_arrow_registration_'+kind]=bool(fit)and fit[0]['kind']==kind and fit[0]['score']>.90
checks['curved_preset_valid_'+kind]=p.is_valid and p.geom_type=='Polygon'
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/recall-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']