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,64 @@
Independent Gaussian paint discovery — offline research
======================================================
This bundle follows beta-pass-20261012. It consumes its accepted full-map,
calibrated Gaussian RGB ground renders, Gaussian-derived labels/height,
vehicle masks, cached marking semantics, and survey tile index. It does not
consume point clouds. All computation, tests and rendering run on Worker006.
Stages
------
extract_discovery: run the existing OpenCV top-hat/connected component/Hough
extractor over every surveyed tile at a common metric resolution. Components
and bounded morphological closing supply fragmented glyph hypotheses; original
paint geometry, including holes, is retained for fitting. Cached semantic scores
are proposal filters. No existing vector axis seeds this search.
refine_discovery: use the existing robust row fitting and beta two-render
profiles to validate periodic rows. Whole glyphs use attributed templates and
two whole-object image footprints selected by geometry before RGB inspection.
Positive paint, negative space, observed recall and valid coverage are required.
The proposal fit tolerates incomplete/noisy contours (score >= .74, recall >= .75);
this alone never authorizes output. Both image footprints must separately pass
valid coverage >= .98, paint support >= .73, observed recall >= .78 and negative
paint fraction <= .23. Template branch/head/counter identity checks stay active. The tail requires
50% positive support to tolerate wear; head and side branch require 73%.
A pure turn needs a lateral head displacement relative to the independently
Huber-fitted paint tail, not relative to the optimized template angle.
A glyph also needs compatible nearby image strips and observed dark space beyond
its ends. End probes start .35 m outside the preset to allow bounded fit error;
a continuing lane stripe cannot be reclassified as an arrow.
An isolated stripe is explicitly unclassified without a measured periodic row.
Only non-overlapping missing objects are added. Every baseline object is retained.
Render tiles are different views of one Gaussian reconstruction, not independent
physical scans. Outputs remain observation-only, unreviewed for routing, and
standard_compliance=not_assessed. GOST catalog associations are suggestions, not
legal tolerances or compliance certification. No new physical accuracy claim.
Reproduction
------------
Use bundle.json to resolve byte-identical canonical modules; qualification
operator/replay retains the bounded runner, registry and frozen source manifest.
Execution requires the pinned Docker image, private Gaussian inputs, and the
pinned external review font. No downloads or installs occur in the container.
Run test_discovery, extract_discovery, refine_discovery, audit_discovery,
render_discovery and render_plan, then verify inputs, receipts, maps and images.
The same source snapshot and POLICY are required on all three scenes.
Attribution
-----------
Arrow artwork: MajorAlexey, 1.18 Russian road marking.svg, CC BY-SA 4.0.
Source: https://commons.wikimedia.org/wiki/File:1.18_Russian_road_marking.svg
License: https://creativecommons.org/licenses/by-sa/4.0/
Source SHA-256: b76f40ee8d1603ddfeb3cd430f397dcc509684f0a0aa38c61bbd8a2cba554ea8
Adaptation: normalized polygon presets with parameterized length/width/stroke.
The letter A is an existing original parametric preset. Artwork derivatives
retain their CC BY-SA attribution and licensing obligations.
Limits
------
This stage does not change roads, facades, pedestrian areas or existing paint.
It does not infer a completely unobserved symbol or certify complete recall.
Curved rows, thin low-contrast paint, occlusions, template variants outside the
library and inadequate second-render coverage can still be missed.
@@ -0,0 +1,32 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
from discovery_rules import POLICY,VERSION,uncovered,glyph_pass
from beta_profiles import supported
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/discovery-rows.json').read_text());current={f['id']:f for f in old['features']}
def poly(f):return shapely.force_2d(shape(f['geometry']))
existing=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'])
checks=dict(transaction_replay=True,only_paint_added=True,no_new_neighbor_overlap=True,evidence_passes=True,independent_image_proposals=True)
for r in rows:
checks['transaction_replay']&=not r['before']and not r['source_ids']and r['output_ids']==[f['id']for f in r['after']]and all(f['id']not in current for f in r['after'])
checks['independent_image_proposals']&=r['discovery_without_vector_seed']
checks['only_paint_added']&=all(f['properties']['class']=='road_marking'and f['properties']['method']==VERSION for f in r['after'])
okay=len(set(r['source_tiles']))>=2;ev=r['evidence']
if r['kind']=='glyph':okay&=len(ev)==2 and all(glyph_pass(e)and len(e.get('parts',[]))>=2 and len(e.get('ends',[]))==2 for e in ev)and r['template_fit_score']>=POLICY['symbol_proposal_score'] and r['fit_recall']>=POLICY['symbol_proposal_recall']and r['lane_context']['passed']and r['lane_context']['supporting_strips']>=2
elif r['kind']=='observed-strip':okay&=len(ev['paint'])==2 and len(ev['ends'])==4 and all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']and e['contrast']>=22 for e in ev['paint'])and all(e.get('full_corridor')and supported(e,False)for e in ev['ends'])
elif r['kind']=='periodic-row':
okay&=len(ev['paint'])==2*len(ev['observations'])and all(supported(e)for e in ev['paint'])and len(ev['gaps'])==2*(len(ev['observations'])-1)
okay&=all(supported(e,False)if ev['mode']=='intervals'else e['valid']>=.95 and e['contrast_drop']>=18 and e['contrast']<(e['contrast']+e['contrast_drop'])*.65 for e in ev['gaps'])
okay&=all(len(e['edges'])==2 and max(abs(e['edges'][0][k]-e['edges'][1][k])for k in [0,1])<=.20 for e in ev['observations'])
else:okay=False
checks['evidence_passes']&=okay
for f in r['after']:
checks['no_new_neighbor_overlap']&=uncovered(poly(f),existing);existing=shapely.union_all([existing,poly(f)]);current[f['id']]=f
features={f['id']:f for f in new['features']};checks['final_map_matches_replay']=features==current;checks['unique_ids']=len(features)==len(new['features'])
checks['all_baseline_objects_unchanged']=all(features.get(f['id'])==f for f in old['features'])
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
report=json.loads(Path('/out/discovery-report.json').read_text());checks['same_policy']=new['discovery_refinement']==VERSION and report['policy']==POLICY
checks['every_operation_counted']=report['changed_segments']==len(rows)and report['added_objects']==sum(len(r['after'])for r in rows)
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()},full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/discovery-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,116 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_beta.py": "beta_pass/audit_beta.py",
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_discovery.py": "discovery_pass/audit_discovery.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_rows.py": "rows_pass/audit_rows.py",
"audit_sections.py": "sections_pass/audit_sections.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"beta_profiles.py": "beta_pass/beta_profiles.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"discovery_evidence.py": "discovery_pass/discovery_evidence.py",
"discovery_rules.py": "discovery_pass/discovery_rules.py",
"extract_discovery.py": "discovery_pass/extract_discovery.py",
"fit_scene.py": "full_plan/fit_scene.py",
"fragment_templates.py": "discovery_pass/fragment_templates.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"paint_templates.py": "continuation_pass/paint_templates.py",
"refine_beta.py": "beta_pass/refine_beta.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_discovery.py": "discovery_pass/refine_discovery.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_rows.py": "rows_pass/refine_rows.py",
"refine_sections.py": "sections_pass/refine_sections.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_beta.py": "beta_pass/render_beta.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_discovery.py": "discovery_pass/render_discovery.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "continuation_pass/render_plan.py",
"render_rows.py": "rows_pass/render_rows.py",
"render_sections.py": "sections_pass/render_sections.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"road_glyph_presets.py": "continuation_pass/road_glyph_presets.py",
"row_evidence.py": "rows_pass/row_evidence.py",
"row_profiles.py": "rows_pass/row_profiles.py",
"section_profiles.py": "sections_pass/section_profiles.py",
"test_beta.py": "beta_pass/test_beta.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_discovery.py": "discovery_pass/test_discovery.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_rows.py": "rows_pass/test_rows.py",
"test_sections.py": "sections_pass/test_sections.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py"
},
"reference_qualification": "discovery-pass-20261012",
"source_snapshot": "91768632d85929db9c92",
"source_sha256": {
"audit_beta.py": "f6dfe314f5f0f9875035f08ae279e64309fafcd9c04e0feb468dcf106cc2990f",
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_discovery.py": "9e5f1bdd0d752d82a52121fe86d4e6fb00068a6af9330a072fe7311a909bc974",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_rows.py": "7298fddd8baf9798e6dd5251d4f261e97a5b92f0beeb60f3198c6aa7498d7f01",
"audit_sections.py": "755d129ef5e1c6503c784393f67cc0dae1c9ebaaecb9c08b8ad440cde7dceea7",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"beta_profiles.py": "172ab1f02b8767e9e96c21d99925c8fd7568403434f951feadc2857036d07c6e",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"discovery_evidence.py": "dc7e0594b77f6d3723a965216164427835aa5ae2ff736b5599774c4efbc626eb",
"discovery_rules.py": "1ac148d3fd75d443d2bde69e46da775de838c9cb2013570d87c13900f0a1a491",
"extract_discovery.py": "5d2835cde2b9d4d895609ea39be2a94a22e894d0996d525dcc3df7046c33e681",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"fragment_templates.py": "11f2eb0bdf89a76f2f3be1e8368662f45fea1dec13f7fb43bac9c3e41acf1ae7",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"paint_templates.py": "9cf9c4e871ea03f38e1641c1c89864a628e0fe87462cccdc0149fdf6242545b6",
"refine_beta.py": "36f39ab464c967b1df136f992a3156deef1dfe2af858bc7cbbef43e9bf7f9831",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_discovery.py": "6272ca1f5052259fb3c6cfd1f1079e4e5864e1e067d12de7ff36d95857219d7b",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_rows.py": "3983e8de9b6dadb349b8731335798640e4ce11c87356925f9ea79c5d0bf819b8",
"refine_sections.py": "7fd48aa308df07b980e40153651c9c6985949245d4f3f0d1a46bbfd13f735ff3",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_beta.py": "4a5fdeaa746ce8b4f449df44c210e13fcc2cabf2e2931beab00928eda3777e1c",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_discovery.py": "868ad8eb712f5880e944b0899205a2c0fd6dd0713eb727b1c49dda92b897fa20",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_rows.py": "65f57b15f2b288048a75d1f4603625637f1e2af505925628ec80a2169fe9944e",
"render_sections.py": "43de78c4b1c643162f4ac9ada77411a2a4e222fa5506ec8f1061311a96bb234c",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"road_glyph_presets.py": "619f4e9c9eeaf63537afc0e8676ab5915d78af1aee8bfb9fe4656bf81b07f322",
"row_evidence.py": "fc6a390faa97fb4cf6213dd6b841a94de9c6e78e0b68e6715aa06f2de565f28c",
"row_profiles.py": "0b23a93b6de9b2e01efb5ce57085fac0afebcd3df6184e573d6b84793e0128df",
"section_profiles.py": "f3f57b2f5e01962f0aca44164d95dfd2d1e03c73c1b0ecb94c6d550f509609de",
"test_beta.py": "e5729c05063afb65c3e35b4e380219dee9893dfa26bb41e1c5cd24641e08358b",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_discovery.py": "a75ffc22d065201f7023d8e6cfb6dc09204a80f9be607599b85479628a301538",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_rows.py": "a89932294a62a373b8c4c80556c4d23d7182c64126788d63988312bc3b9f3449",
"test_sections.py": "0b9f5da94e3f7ca8f05ab1f15b48685a6c97ac4a559147f98adb6634ad74031f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,29 @@
"""Whole-object footprints choose two render tiles before seeing their paint."""
import numpy as np,cv2,shapely
from functools import lru_cache
from row_evidence import GaussianViews
from fit_scene import project
from layer_common import sample
from discovery_rules import glyph_score
class DiscoveryViews(GaussianViews):
# Bounded decode cache for a whole-map search with overlapping render tiles.
@lru_cache(maxsize=12)
def inputs(self,name):return super().inputs(name)
def glyph_views(p,views,kind,parameters):
lo=np.array(p.bounds[:2])-1.;hi=np.array(p.bounds[2:])+1.;cell=.04
xx=np.arange(lo[0],hi[0],cell);yy=np.arange(lo[1],hi[1],cell)
x,y=np.meshgrid(xx,yy);points=np.c_[x.ravel(),y.ravel()];corners=np.array([[lo[0],lo[1]],[lo[0],hi[1]],[hi[0],lo[1]],[hi[0],hi[1]]]);center=(lo+hi)/2
eligible=[]
for i,t in enumerate(views.tiles):
uv=project(corners,views.geometry(t['id']))
if uv.min()>=20 and uv.max()<1180:eligible.append((float(np.linalg.norm(center-views.centers[i])),i))
if len(eligible)<2:return [],[]
ev=[];names=[]
for _,i in sorted(eligible)[:2]:
name=views.tiles[i]['id'];g=views.geometry(name);rgb,vehicle=views.inputs(name);uv=project(points,g).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
def read(a,q):return np.concatenate([cv2.remap(a,b[:,0,None],b[:,1,None],cv2.INTER_LINEAR).reshape(len(b),-1)for b in np.array_split(q,max(1,int(np.ceil(len(q)/20000))))])
colors=read(rgb,native).reshape(len(yy),len(xx),3);valid=(read(g['alpha'].astype('float32'),uv).ravel()>=.65)&(read(vehicle,uv).ravel()<.2)&(sample(views.labels,points,views.low,views.high)==1)
ev.append(glyph_score(colors,valid.reshape(len(yy),len(xx)),points,p,kind=kind,parameters=parameters));names.append(name)
return ev,names
@@ -0,0 +1,69 @@
"""Image proposals do not require an existing vector; admission remains measured."""
import numpy as np, cv2, shapely
from shapely.geometry import Polygon, shape, mapping
from line_reconstruction import observation
VERSION='image-discovery-v1'
POLICY=dict(proposal_image_size=2048,fragment_join_radii_m=[.12,.25],min_symbol_area_m2=.25,symbol_proposal_score=.74,symbol_proposal_recall=.75,
min_semantic_mean=.06,min_semantic_peak=.35,max_new_overlap_m2=.005,
duplicate_clearance_m=.10,min_symbol_valid=.98,min_symbol_paint_support=.73,min_tail_support=.50,
min_symbol_observed_recall=.78,max_symbol_negative_paint=.23,
min_solid_length_m=3.,min_solid_valid=.98,min_solid_bright=.93,
max_glyph_end_paint=.25,glyph_end_probe_start_m=.35,glyph_end_probe_stop_m=.85,glyph_context_angle_deg=15.,glyph_context_radius_m=10.,glyph_context_length_m=6.)
def glyph_context(p,parameters,records):
u=np.array([np.cos(parameters[2]),np.sin(parameters[2])]);support=[]
for r in records:
if r['L']<3 or r['W']>.35:continue
distance=r['polygon'].distance(p)
if .3<distance<POLICY['glyph_context_radius_m']and abs(r['axis']@u)>=np.cos(np.deg2rad(POLICY['glyph_context_angle_deg'])):support.append(r)
length=sum(r['L']for r in support)
return dict(passed=len(support)>=2 and length>=POLICY['glyph_context_length_m'],supporting_strips=len(support),supporting_length_m=float(length),source_tiles=sorted(set(r['source_tile']for r in support)))
def eligible_symbol(p):
if p.is_empty or p.area<POLICY['min_symbol_area_m2']:return False
r=observation(np.array(p.convex_hull.exterior.coords),'symbol');L,W=r['L'],r['W']
return 1.2<L<9 and .55<W<3 and L/W>1.2 and .09<p.area/(L*W)<.75
def uncovered(p,existing):
return p.intersection(existing).area<=POLICY['max_new_overlap_m2'] and p.intersection(existing.buffer(POLICY['duplicate_clearance_m'])).area/p.area<.25
def pack(r):
return {k:(mapping(v)if hasattr(v,'geom_type')else v.tolist()if isinstance(v,np.ndarray)else v)for k,v in r.items()}
def unpack(r):
return {k:(shape(v)if isinstance(v,dict)and 'coordinates'in v else np.asarray(v)if k in ['center','axis','origin','points']else v)for k,v in r.items()}
def glyph_score(rgb,allowed,points,polygon,cell=.04,kind=None,parameters=None):
"""Check positive paint, unpainted negative space, and unexplained pixels."""
h,w=allowed.shape;gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY)
bg=cv2.morphologyEx(gray,cv2.MORPH_OPEN,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(31,31)))
hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
paint=(gray.astype(float)-bg>15)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))
target=shapely.contains_xy(polygon,points[:,0],points[:,1]).reshape(h,w)
near=cv2.dilate(paint.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
wide=cv2.dilate(target.astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))>0
region=shapely.contains_xy(polygon.convex_hull.buffer(.15),points[:,0],points[:,1]).reshape(h,w)
negative=region&~wide
result=dict(valid=float(allowed[region].mean())if region.any()else 0.,
support=float(near[target].mean())if target.any()else 0.,
recall=float(wide[paint&region&allowed].mean())if (paint&region&allowed).any()else 0.,
negative_paint=float(paint[negative&allowed].mean())if (negative&allowed).any()else 1.)
if kind is not None and parameters is not None:
px,py,a,L,W,stroke=parameters;u=np.array([np.cos(a),np.sin(a)]);n=np.array([-u[1],u[0]]);local=points-[px,py];t=(local@u).reshape(h,w);side=(local@n).reshape(h,w)
regions=[('head',t>L*.80),('tail',t<L*.25)]
if kind.startswith('straight_')and kind!='straight_arrow':regions.append(('branch',side*(1 if 'left'in kind else -1)>W*.24))
result['parts']=[]
for name,where in regions:
select=target&where
result['parts'].append(dict(part=name,valid=float(allowed[select].mean())if select.any()else 0.,support=float(near[select].mean())if select.any()else 0.))
result['ends']=[]
for name,interior,exterior in [('tail',t<L*.20,(t<-POLICY['glyph_end_probe_start_m'])&(t>-POLICY['glyph_end_probe_stop_m'])),('head',t>L*.90,(t>L+POLICY['glyph_end_probe_start_m'])&(t<L+POLICY['glyph_end_probe_stop_m']))]:
observed_side=side[target&interior]
offset=float(np.median(observed_side))if len(observed_side)else 0.
select=exterior&(abs(side-offset)<max(.12,stroke*.6))
result['ends'].append(dict(end=name,valid=float(allowed[select].mean())if select.any()else 0.,paint_fraction=float(paint[select].mean())if select.any()else 1.))
return result
def glyph_pass(e):
return e['valid']>=POLICY['min_symbol_valid']and e['support']>=POLICY['min_symbol_paint_support']and e['recall']>=POLICY['min_symbol_observed_recall']and e['negative_paint']<=POLICY['max_symbol_negative_paint']and all(p['valid']>=POLICY['min_symbol_valid']and p['support']>=(POLICY['min_tail_support']if p['part']=='tail'else POLICY['min_symbol_paint_support'])for p in e.get('parts',[]))and all(p['valid']>=POLICY['min_symbol_valid']and p['paint_fraction']<=POLICY['max_glyph_end_paint']for p in e.get('ends',[]))
@@ -0,0 +1,64 @@
from pathlib import Path
import json,time,hashlib
import numpy as np,cv2,shapely
from PIL import Image
from shapely.geometry import Polygon,shape,mapping
from scipy.ndimage import distance_transform_edt
from layer_common import O,S,sample,parts
from fit_scene import world,project
from line_reconstruction import extract,dedup
from discovery_rules import POLICY,eligible_symbol,pack
cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text())
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];low,high=z['bounds']
inside=distance_transform_edt(labels==1)*.1
protected=[shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking']
protected_union=shapely.union_all(protected);symbols=shapely.union_all([shapely.force_2d(shape(f['geometry'])).convex_hull for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')not in ['linear_marking','crosswalk']])
lines=[];glyphs=[];reports=[]
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));size=POLICY['proposal_image_size'];mpp=60/size
rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB').resize((size,size),Image.Resampling.LANCZOS))
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=cv2.resize(z['vehicle'].astype('float32'),(size,size))
with np.load(Path('/evidence_plan/evidence')/(name+'.npz'))as z:semantic=cv2.resize(z['road marking'].astype('float32'),(size,size))
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
yy,xx=np.mgrid[:size,:size];points=xy(np.c_[xx.ravel(),yy.ravel()]);allowed=(sample(inside,points,low,high)>.25).reshape(size,size)&(vehicle<.2)&(cv2.resize(g['alpha'].astype('float32'),(size,size))>.65)
mask=np.zeros((size,size),np.uint8);domain=shapely.box(*tile['bounds_xy'][0],*tile['bounds_xy'][1])
for p in protected:
if p.intersects(domain):
for q in parts(p.buffer(.10)):cv2.fillPoly(mask,[np.rint((project(q.exterior.coords,g)+.5)*size/1200-.5).astype('int32')],1)
observations,rec=extract(rgb,allowed&(mask==0),xy,name,mpp);lines.extend(observations)
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/mpp)//2*2+1,)*2)
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel)
binary=((ridge>12)&(gray>100)&((hsv[:,:,1]<100)|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)))&allowed).astype('uint8')
cc,hier=cv2.findContours(binary,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE);components=[]
if hier is not None:
for i,c in enumerate(cc):
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.018:continue
holes=[];j=hier[0,i,2]
while j>=0:
if cv2.contourArea(cc[j])*mpp*mpp>.018:holes.append(xy(cc[j][:,0]))
j=hier[0,j,0]
p=shapely.make_valid(Polygon(xy(c[:,0]),holes));components.extend(parts(p))
union=shapely.union_all(components);proposals=list(components)
for radius in POLICY['fragment_join_radii_m']:
for region in parts(union.buffer(radius).buffer(-radius)):
if not eligible_symbol(region):continue
p=union.intersection(region.buffer(.02))
if not p.is_empty:proposals.append(p)
count=0
for p in proposals:
if not eligible_symbol(p)or p.intersection(symbols).area/p.area>.35:continue
coords=project(np.asarray(p.convex_hull.exterior.coords),g);uv=np.rint((coords+.5)*size/1200-.5).astype('int32');x,y,w,h=cv2.boundingRect(uv)
if x<0 or y<0 or x+w>size or y+h>size:continue
sel=np.zeros((h,w),np.uint8);cv2.fillPoly(sel,[uv-[x,y]],1);vals=semantic[y:y+h,x:x+w][sel>0]
mean=float(vals.mean());peak=float(np.quantile(vals,.9))
if mean<POLICY['min_semantic_mean']or peak<POLICY['min_semantic_peak']:continue
glyphs.append(dict(geometry=mapping(p),source_tile=name,semantic_mean=mean,semantic_peak=peak));count+=1
reports.append(dict(tile=name,**rec,glyph_proposals=count));print('TILE',name,'LINES',len(observations),'GLYPHS',count,flush=True)
records=dedup(lines);candidates=[]
for r in sorted(glyphs,key=lambda r:-shape(r['geometry']).area):
p=shape(r['geometry'])
if any(p.intersection(shape(q['geometry'])).area/min(p.area,shape(q['geometry']).area)>.75 for q in candidates):continue
candidates.append(r)
(O/'discovery-proposals.json').write_text(json.dumps(dict(lines=[pack(r)for r in records],glyphs=candidates,tile_reports=reports,seconds=time.monotonic()-start,policy=POLICY,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest()),allow_nan=False))
print('PROPOSALS',len(records),len(candidates),flush=True)
@@ -0,0 +1,97 @@
"""Template hypotheses in metric object coordinates; never site coordinates."""
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from shapely.ops import unary_union
from shapely.affinity import rotate,translate
from scipy.optimize import minimize
from road_glyph_presets import arrow
def turn_signature(xy,u,L,W,sign):
# Measure the tail's actual paint axis; rotating a turn template over a
# straight arrow must not manufacture the required lateral head displacement.
t=xy@u;tail=xy[t<L*.32];front=xy[t>L*.72]
if len(tail)<8 or len(front)<8:return False
fit=cv2.fitLine(tail.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();axis=fit[:2]
if axis@u<0:axis=-axis
if axis@u<np.cos(np.deg2rad(20)):return False
normal=np.array([-axis[1],axis[0]]);shift=float(np.median((front-fit[2:])@normal))
return sign*shift>max(.18,.25*W)
def template(kind,L,W,stroke):
if kind!='letter_A':return arrow(kind,L,W,stroke)
# A is an original parametric preset. Arrows use the attributed SVG library.
outer=LineString([(0,-W/2),(L,0),(0,W/2)]).buffer(stroke/2,cap_style=2,join_style=3)
bar=LineString([(L*.3,-W*.35),(L*.3,W*.35)]).buffer(stroke/2,cap_style=2)
return unary_union([outer,bar])
def fit_symbol(p,heading=None,diagnostics=None):
from discovery_rules import POLICY
if p.geom_type not in ['Polygon','MultiPolygon'] or p.area<.25:return None
points=np.array(p.convex_hull.exterior.coords)[:,:2];rect=cv2.minAreaRect(points.astype('float32'));corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));u=edges[k]/np.linalg.norm(edges[k]);L=np.linalg.norm(edges[k]);W=min(rect[1]);origin=np.array(rect[0]);ang=np.arctan2(u[1],u[0]);fill=p.area/(L*W)
if not (1.2<L<9 and .35<W<3 and L/W>1.2 and .09<fill<.75):return None
# A fixed-resolution local evidence patch avoids manipulating full scene pixels.
cell=.04;lo=np.array(p.bounds[:2])-.6;hi=np.array(p.bounds[2:])+.6;shape=np.ceil((hi-lo)/cell).astype(int)[::-1]
if max(shape)>350:return None
target=np.zeros(shape,np.uint8)
def draw(poly):
out=np.zeros(shape,np.uint8)
for part in ([poly] if poly.geom_type=='Polygon' else getattr(poly,'geoms',[])):
if part.geom_type!='Polygon' or part.is_empty:continue
cv2.fillPoly(out,[np.rint((np.array(part.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
for hole in part.interiors:cv2.fillPoly(out,[np.rint((np.array(hole.coords)[:,:2]-lo)/cell).astype('int32')],0)
return out
target=draw(p);expanded=cv2.dilate(target,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
# The counter supplies a strong object identity cue, independent of a noisy
# semantic mask. A bounded 8 cm closing tolerates small wear breaks.
closed=p.buffer(.08).buffer(-.08)
counters=[Polygon(h)for part in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if part.geom_type=='Polygon'for h in part.interiors]
has_counter=any(h.area>.05*L*W for h in counters)
variants=['letter_A']if has_counter else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow'];best=None
if heading is not None:ang=float(np.arctan2(heading[1],heading[0]))
for kind in variants:
for flip in [0,np.pi]:
a=ang+flip;uu=np.array([np.cos(a),np.sin(a)]);base=origin-uu*L/2
x0=np.array([base[0],base[1],a,L,W,.16]);bounds=[(base[0]-.4,base[0]+.4),(base[1]-.4,base[1]+.4),(a-.16,a+.16),(L*.85,L*1.15),(W*.75,W*1.25),(.08,.32)]
def polygon(x):
m=template(kind,x[3],x[4],x[5]);m=rotate(m,x[2],origin=(0,0),use_radians=True);return translate(m,x[0],x[1])
def loss(x):
m=draw(polygon(x));wide=cv2.dilate(m,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
coverage=(m&expanded).sum()/max(m.sum(),1);recall=(wide&target).sum()/max(target.sum(),1)
overlap=(m&target).sum()/max((m|target).sum(),1)
return 1-(.6*2*coverage*recall/max(coverage+recall,1e-6)+.4*overlap)+.03*abs(x[3]/L-1)
score=loss(x0)
if kind!='letter_A' and (W<.60 or W/x0[5]<3.5):continue
# A worn letter may have an open counter; missing topology is not a veto.
if score>.8:continue
fit=minimize(loss,x0,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.004,ftol=.004));m=polygon(fit.x);r=draw(m)
coverage=float((r&expanded).sum()/max(r.sum(),1));recall=float((cv2.dilate(r,np.ones((5,5),np.uint8))&target).sum()/max(target.sum(),1));f1=2*coverage*recall/max(coverage+recall,1e-6);overlap=float((r&target).sum()/max((r|target).sum(),1));score=.6*f1+.4*overlap
if diagnostics is not None:diagnostics.append(dict(kind=kind,coverage=coverage,recall=recall,score=score,overlap=overlap,counter=has_counter,parameters=fit.x.tolist()))
if kind=='letter_A':
x=fit.x;bar=LineString([(x[3]*.3,-x[4]*.30),(x[3]*.3,x[4]*.30)]).buffer(x[5]/2,cap_style=2)
bar=translate(rotate(bar,x[2],origin=(0,0),use_radians=True),x[0],x[1]);support=draw(bar)
if (support&expanded).sum()/max(support.sum(),1)<.6:continue
# Positive shape overlap alone confuses arrow heads and triangular signs
# with A. Its counter is negative evidence and must stay largely unpainted.
holes=unary_union([Polygon(h)for part in ([m]if m.geom_type=='Polygon'else m.geoms)if part.geom_type=='Polygon'for h in part.interiors])
core=holes.buffer(-.08)
mask=draw(core)
if mask.sum()<8 or (mask&expanded).sum()/mask.sum()>.15:continue
elif kind.startswith('straight_') and kind!='straight_arrow':
# A compound arrow needs its lateral branch, even if a straight arrow
# alone matches most of the template area.
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
yy,xx=np.mgrid[:r.shape[0],:r.shape[1]];xy=np.stack([lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]],axis=-1);side=xy@n
# Artwork is bbox-centered; use the outer quarter on the branch side.
sign=1 if 'left'in kind else -1
branch=(r>0)&(side*sign>x[4]*.24)
if branch.sum()<5 or (branch&expanded).sum()/branch.sum()<.8:continue
longitudinal=xy@u;head=(r>0)&(longitudinal>x[3]*.8)
if head.sum()<5 or (head&expanded).sum()/head.sum()<.85:continue
elif kind in ['left_arrow','right_arrow']:
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
yy,xx=np.nonzero(target);xy=np.c_[lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]];longitudinal=xy@u;side=xy@n
sign=1 if kind=='left_arrow'else -1
if not turn_signature(xy,u,x[3],x[4],sign):continue
if coverage>=.72 and recall>=POLICY['symbol_proposal_recall'] and (best is None or score>best[1]):best=(m,score,kind,recall,fit.x.tolist())
if best and best[1]>=POLICY['symbol_proposal_score']:return best
return None
@@ -0,0 +1,97 @@
from pathlib import Path
import os,json,time,hashlib,collections
import numpy as np,cv2,shapely
from shapely.geometry import shape,mapping
from shapely.ops import transform
from layer_common import O,S,sample,feature
from line_reconstruction import rows
from beta_profiles import describe,profiles,discover,section_evidence,supported
from interval_profiles import rectangle
from row_evidence import GaussianViews
from discovery_rules import VERSION,POLICY,unpack,uncovered,glyph_pass,glyph_context
from discovery_evidence import glyph_views,DiscoveryViews
from fragment_templates import fit_symbol
from gost_catalog import assess_dash
cv2.setNumThreads(3);start=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());current={f['id']:f for f in old['features']}
proposals=json.loads((O/'discovery-proposals.json').read_text());assert proposals['baseline_sha256']==hashlib.sha256(baseline.read_bytes()).hexdigest()
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
def poly(f):return shapely.force_2d(shape(f['geometry']))
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
paint=[poly(f)for f in old['features']if f['properties']['class']=='road_marking'];existing=shapely.union_all(paint)
protected=shapely.union_all([poly(f)for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'])
views=DiscoveryViews(tiles,labels,low,high,protected);transactions=[];diagnostics=[]
def admit(polys,subtype,kind,evidence,source_tiles,**extra):
global existing
kept=[p for p in polys if uncovered(p,existing)]
if not kept:return False
new=[feature(lift(p),'road_marking',subtype=subtype,method=VERSION,source_ids=[],source_tile=source_tiles[0],source_tiles=source_tiles,line_kind='dashed'if kind=='periodic-row'else'unclassified-strip'if kind=='observed-strip'else None,standard_compliance='not_assessed',**extra)for p in kept]
if len(set(f['id']for f in new))!=len(new)or any(f['id']in current for f in new):return False
for f in new:current[f['id']]=f
existing=shapely.union_all([existing]+kept)
transactions.append(dict(kind=kind,source_ids=[],output_ids=[f['id']for f in new],before=[],after=new,bounds_xy=shapely.union_all(polys).bounds,evidence=evidence,source_tiles=source_tiles,discovery_without_vector_seed=True,**extra))
print('ADMIT',len(transactions),kind,subtype,len(new),flush=True);return True
# Fragment sets and complete components share the same attributed presets.
# The two full-object render footprints are selected by geometry only.
records=[unpack(r)for r in proposals['lines']]
for gi,r in enumerate(proposals['glyphs']):
p=shape(r['geometry']);diag=[];f=fit_symbol(p,diagnostics=diag)
if f is None:diagnostics.append(dict(kind='glyph',reason='template-rejected',proposal=gi,best_score=max((q['score']for q in diag),default=0),model_trials=diag));continue
polygon,score,kind,recall,params=f
if not uncovered(polygon,existing):continue
context=glyph_context(polygon,params,records)
if not context['passed']:diagnostics.append(dict(kind='glyph',proposal=gi,reason='no-compatible-lane-context',context=context,geometry=mapping(polygon)));continue
ev,names=glyph_views(polygon,views,kind,params);okay=len(ev)==2 and len(set(names))==2 and all(glyph_pass(e)for e in ev)
diagnostics.append(dict(kind='glyph',proposal=gi,subtype=kind,score=score,evidence=ev,passed=okay,geometry=mapping(polygon)))
if okay:admit([polygon],kind,'glyph',ev,names,template_fit_score=score,fit_recall=recall,template_parameters=params,fragment_count=len(getattr(p,'geoms',[p])),lane_context=context)
if gi%10==0:print('GLYPH',gi+1,'/',len(proposals['glyphs']),flush=True)
views.protected=shapely.union_all([protected]+[poly(f).convex_hull for f in current.values()if f['properties'].get('method')==VERSION and f['properties'].get('subtype')!='linear_marking'])
# Use both individual image strips and robust component-center row hypotheses.
# No old vector supplies a proposal axis or selects a processing neighborhood.
records=[unpack(r)for r in proposals['lines']];seeds=[]
for r in records:
if r['W']<=.35 and r['L']>=.3 and r['polygon'].intersection(existing.buffer(.1)).area/r['polygon'].area<.70:
seed=describe(r['polygon'])
if seed is not None:seeds.append(seed)
for row in rows(records):
if len(row['records'])<3:continue
o,u=row['origin'].astype(float),row['axis'].astype(float);u/=np.linalg.norm(u);ts=(row['points']-o)@u;L=float(ts.max()-ts.min())
if 1<L<70:
p=rectangle(o,u,float(ts.min()),float(ts.max()),.12)
if p.intersection(existing.buffer(.1)).area/p.area<.7:seeds.append(dict(origin=o+(ts.max()+ts.min())/2*u,axis=u,length=L,width=.12))
seen=[];periodic=[];solids=[];profiled=0;profile_stats=collections.Counter()
for si,seed in enumerate(sorted(seeds,key=lambda r:(int(np.argmin(np.linalg.norm(views.centers-r['origin'],axis=1))),-r['length']))):
domain=rectangle(seed['origin'],seed['axis'],-seed['length']/2,seed['length']/2,.14)
if any(domain.intersection(p).area/domain.area>.8 for p in seen):continue
seen.append(domain);profiled+=1;readers,used=views.readers(seed['origin'],seed['axis']);pv=profiles(seed,readers)
profile_stats['two_view_profile'if pv is not None else 'no_two_view_profile']+=1
found=discover(seed,pv)
for r in found:r['source_tiles']=sorted(set(used[0])|set(used[1]));periodic.append(r)
if pv is not None and seed['length']>=POLICY['min_solid_length_m']:
# Keep measured uninterrupted intervals only. Endpoints of new solids
# come from agreeing paint runs, never a semantic/visibility mask edge.
for a,b in pv[0]['intervals']:
if b-a<3 or b<-seed['length']/2 or a>seed['length']/2:continue
matches=[(c,d)for c,d in pv[1]['intervals']if max(abs(a-c),abs(b-d))<=.2]
if not matches:continue
c,d=min(matches,key=lambda z:abs(z[0]-a)+abs(z[1]-b));lo0,hi0=(a+c)/2,(b+d)/2
ev=[section_evidence(v,lo0+.1,hi0-.1)for v in pv]
if not all(e['valid']>=POLICY['min_solid_valid']and e['support']>=POLICY['min_solid_bright']and e['contrast']>=22 for e in ev):continue
from beta_profiles import corridor_dark
ends=[corridor_dark(v,*span)for v in pv for span in [(lo0-.3,lo0-.07),(hi0+.07,hi0+.3)]]
if not all(supported(e,False)for e in ends):continue
p=rectangle(seed['origin'],seed['axis'],lo0,hi0,float(np.clip(np.median([v['width']for v in pv]),.075,.27)),float(np.mean([v['offset']for v in pv])))
solids.append(dict(polygon=p,evidence=dict(paint=ev,ends=ends),source_tiles=sorted(set(used[0])|set(used[1]))))
if profiled%25==0:print('PROFILE',profiled,'/',len(seeds),'ROWS',len(periodic),'SOLIDS',len(solids),flush=True)
for r in sorted(periodic,key=lambda r:-len(r['polygons'])):
ev=dict(paint=r['paint_evidence'],gaps=r['gap_evidence'],edges=r['edge_evidence'],observations=r['observations'],mode=r['mode'])
admit(r['polygons'],'linear_marking','periodic-row',ev,r['source_tiles'],period_m=r['period'],dash_length_m=r['length'],width_m=r['width'],standard_assessment=assess_dash(r['length'],r['period'],r['width']))
for r in sorted(solids,key=lambda r:-r['polygon'].area):admit([r['polygon']],'linear_marking','observed-strip',r['evidence'],r['source_tiles'])
result={**old,'features':list(current.values()),'discovery_refinement':VERSION};(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'discovery-rows.json').write_text(json.dumps(transactions,indent=2,allow_nan=False));(O/'discovery-diagnostics.json').write_text(json.dumps(diagnostics,indent=2,allow_nan=False));(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(transactions),stages=dict(collections.Counter(r['kind']for r in transactions)),profiled_axes=profiled,profile_stats=dict(profile_stats),raw_line_proposals=len(records),raw_glyph_proposals=len(proposals['glyphs']),added_objects=sum(len(r['after'])for r in transactions),added_subtypes=dict(collections.Counter(f['properties']['subtype']for r in transactions for f in r['after'])),policy=POLICY,policy_version=VERSION,manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'discovery-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,31 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'discovery-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('discovery-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('class')!='road_marking':continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='discovery-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('discovery-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'discovery-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
@@ -0,0 +1,54 @@
import json,runpy,numpy as np,shapely
from shapely.affinity import rotate,translate
from shapely.geometry import box
from discovery_rules import uncovered,eligible_symbol,glyph_score,glyph_pass,glyph_context
from fragment_templates import fit_symbol,turn_signature
from road_glyph_presets import arrow
from line_reconstruction import observation,rows
from beta_profiles import profiles,discover
from interval_profiles import rectangle
prior=runpy.run_path('/candidate/test_beta.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
p=arrow('straight_arrow',4.,1.2,.16)
checks['preset_is_glyph_proposal']=eligible_symbol(p)
checks['narrow_lane_strip_not_glyph']=not eligible_symbol(box(0,0,5,.12))
checks['solid_box_not_glyph']=not eligible_symbol(box(0,0,4,1.2))
checks['zero_area_not_glyph']=not eligible_symbol(box(0,0,0,0))
fragmented=p.difference(box(1.5,-2,1.56,2));fit=fit_symbol(fragmented)
checks['fragmented_arrow_uses_reusable_preset']=fit is not None and fit[2]=='straight_arrow'
checks['near_duplicate_not_added']=not uncovered(translate(box(0,0,5,.12),yoff=.10),box(0,0,5,.12))
checks['real_separate_parallel_strip_allowed']=uncovered(translate(box(0,0,5,.12),yoff=.32),box(0,0,5,.12))
checks['overlapping_paint_not_added']=not uncovered(box(0,0,5,.12),box(2,0,8,.12))
checks['empty_map_accepts_first_object']=uncovered(p,shapely.GeometryCollection())
cell=.04;x,y=np.meshgrid(np.arange(-1,5,cell),np.arange(-2,2,cell));points=np.c_[x.ravel(),y.ravel()];on=shapely.contains_xy(p,points[:,0],points[:,1]).reshape(x.shape)
rgb=np.repeat(np.where(on,220,65)[:,:,None],3,axis=2).astype('uint8');valid=np.ones(x.shape,bool)
ev=glyph_score(rgb,valid,points,p);checks['visible_preset_has_paint_and_negative_support']=glyph_pass(ev)
checks['unobserved_preset_rejected']=not glyph_pass(glyph_score(rgb,np.zeros_like(valid),points,p))
checks['paint_free_patch_rejected']=not glyph_pass(glyph_score(np.full_like(rgb,65),valid,points,p))
filled=shapely.contains_xy(p.convex_hull,points[:,0],points[:,1]).reshape(x.shape);rr=np.repeat(np.where(filled,220,65)[:,:,None],3,axis=2).astype('uint8')
checks['painted_negative_space_rejected']=not glyph_pass(glyph_score(rr,valid,points,p))
checks['head_and_tail_verified_separately']=glyph_pass(glyph_score(rgb,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]))
missing=rgb.copy();missing[x>3.1]=65
checks['missing_head_cannot_authorize_arrow']=not glyph_pass(glyph_score(missing,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]))
cp=arrow('straight_left_arrow',4,1.5,.16);on2=shapely.contains_xy(cp,points[:,0],points[:,1]).reshape(x.shape);crgb=np.repeat(np.where(on2,220,65)[:,:,None],3,axis=2).astype('uint8')
checks['compound_parts_all_observed']=glyph_pass(glyph_score(crgb,valid,points,cp,kind='straight_left_arrow',parameters=[0,0,0,4,1.5,.16]))
crgb[y>.2]=65
checks['missing_side_branch_cannot_authorize_compound']=not glyph_pass(glyph_score(crgb,valid,points,cp,kind='straight_left_arrow',parameters=[0,0,0,4,1.5,.16]))
xy=points[on.ravel()]
for degrees in [-9,0,9]:
a=np.deg2rad(degrees);axis=np.array([np.cos(a),np.sin(a)])
checks['straight_arrow_not_turn_with_hypothesis_angle_'+str(degrees)]=not turn_signature(xy,axis,4,1.2,1)and not turn_signature(xy,axis,4,1.2,-1)
for kind,sign in [('left_arrow',1),('right_arrow',-1)]:
tp=arrow(kind,4,1.5,.16);txy=points[shapely.contains_xy(tp,points[:,0],points[:,1])]
checks[kind+'_has_independently_measured_turn']=turn_signature(txy,np.array([1.,0]),4,1.5,sign)
missingtail=rgb.copy();missingtail[x<1.0]=65
checks['entire_missing_tail_rejected']=not glyph_pass(glyph_score(missingtail,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]))
through=rgb.copy();through[abs(y)<.08]=220
checks['stripe_through_symbol_cannot_be_arrow']=not glyph_pass(glyph_score(through,valid,points,p,kind='straight_arrow',parameters=[0,0,0,4,1.2,.16]))
context=[observation(np.array(box(-1,offset,6,offset+.12).exterior.coords),'image')for offset in [-1.5,1.5]]
checks['arrow_agrees_with_independent_lane_strips']=glyph_context(p,[0,0,0,4,1.2,.16],context)['passed']
checks['perpendicular_noise_not_lane_arrow']=not glyph_context(p,[0,0,np.pi/2,4,1.2,.16],context)['passed']
checks['one_strip_not_sufficient_context']=not glyph_context(p,[0,0,0,4,1.2,.16],context[:1])['passed']
# Empty vector map: image component centers alone supply the row hypothesis.
obs=[observation(np.array(rectangle(np.zeros(2),np.array([1.,0]),i,i+.5,.12).exterior.coords),'image')for i in range(6)]
rs=rows(obs);checks['image_components_form_row_without_vectors']=any(len(r['records'])>=4 for r in rs)
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/discovery-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(dict(passed=result['passed'],tests=len(checks),failed=[k for k,v in checks.items()if not v])));assert result['passed']