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,80 @@
Two-view verification of redundant road-marking vectors
======================================================
Scope
-----
Offline Gaussian-only increment over transitions-pass-20261012. One immutable
source and one policy across Maroseyka, Pokrovka and Smolensk. The code never
branches on scene names, world coordinates, manually chosen regions or IDs.
Worker006 performs all computation, tests and rendering. Mac operations are
limited to orchestration, source/document editing, hashes, copies and viewing.
Reusable components and policy
------------------------------
OpenCV minAreaRect/remap/morphology measure metric image strips; SciPy filtering
and find_peaks/peak_widths resolve paint ridges; Shapely handles overlap. The new
wrapper expresses acceptance and preservation rules, not a map-specific model.
POLICY is saved in each scene report. Parameters have metric or photometric
meaning and are identical for all maps; none are selected from street identity.
Candidate pairs are thin linear-marking polygons with compatible directions
(<=4 degrees), lateral distance <=0.65 m and >=75% longitudinal overlap of the
source. Each candidate is evaluated in two nearest render tiles that fully
cover both polygons with an image margin. Render views share the same Gaussian
reconstruction: agreement is not independent ground-truth evidence.
Valid samples require actual image coverage, top-view alpha >=0.65, road surface,
vehicle score <0.20 and exclusion of protected symbols/crosswalks. Both objects
need >=95% valid samples in both views. The retained stroke needs >=85% bright
support and median local contrast >=22. Unknown or masked pixels cannot justify
removal. Neighboring rows are not duplicates merely because they are close.
Deletion can be justified by:
* >=90% geometric containment in an image-supported keeper;
* <=15% bright support and source contrast q75 <8, beside a supported keeper;
* one common physical paint ridge represented by two vectors. The keeper must
be <=8 cm from the ridge, the rejected vector >=10 cm away and at least 6 cm
farther from it. Both views must agree on the ridge within 5 cm.
For every reason, an observed second ridge vetoes deletion. Transverse profiles
are inspected both as a median and along individual stations. A second ridge
present at >10% of stations or continuously for >=0.25 m protects intermittent
parallel paint, even if it disappears from the median profile. The transverse
corridor also needs >=95% valid evidence. All these are reconstruction rules,
not GOST application tolerances. Earlier normative dimensional checks remain.
The deterministic selection keeps each named keeper and prevents deletion cycles.
No vector coordinates are moved or newly drawn by this pass; all surviving
features are byte-for-byte identical JSON objects. Each removal records source,
keeper, views, profiles and acceptance metrics. Old anchor/source IDs remain
historical provenance; consumers needing current IDs can resolve the explicit
source_id -> target_id records in consensus-rows.json.
Verification and limits
-----------------------
The controlled suite reuses all preceding 57 checks and adds tests for visible
parallel lines, faint paint, occlusion, missing/disagreeing views, overlap,
perpendicular/distant neighbors, rotation/translation, one blurred ridge,
real double ridges, intermittent short paint and invalid transverse coverage.
Each accepted edit has an exhaustive source/before/after frame. Existing short
punctuation reference frames and whole-map overviews support visual regression
review; unchanged-feature audits cover all unmodified objects.
This pass removes only evidence-confirmed whole-object duplicates. It does not
repair false solid continuations lacking a suitable neighboring keeper, perform
partial duplicate trimming, resolve single-view cases, redraw curved rows or
find missing symbols. Some pairs that look duplicated at overview scale are
actual double paint ridges and intentionally remain. Whole-map recall/precision,
geodetic accuracy and legal marking compliance are not established. Unchanged
scenes are regression controls, not proof of universal performance on all scans.
Replay
------
Pinned image sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0.
4 CPU, 20 GiB RAM, 1 GiB tmpfs, read-only root, no network, 1800s per stage.
Stages: test_consensus, refine_consensus, audit_consensus, render_consensus,
render_plan. Private scene caches, canonical queue and SSH configuration are
required external inputs. Qualified hashes and execution receipts accompany
outputs. bundle.json resolves unchanged canonical modules; review-font.ttf is
separately pinned and omitted from source ZIP. No live deployment, Ops post or
commit. Technical artifacts and intermediate attempts stay in qualification.
@@ -0,0 +1,30 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());rows=json.loads(Path('/out/consensus-rows.json').read_text())
removed=set(json.loads(Path('/out/consensus-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']};checks={}
checks['unique_ids']=len(features)==len(new['features'])
checks['all_surviving_features_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed)
checks['only_linear_removed']=all(f['properties'].get('subtype')=='linear_marking'for f in old['features']if f['id']in removed)
checks['no_new_or_moved_geometry']=len(features)+len(removed)==len(old['features'])and all(f['id']in {x['id']for x in old['features']}for f in new['features'])
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['keeper_survives']=all(r['target_id']in features and r['source_id']not in features for r in rows)
checks['each_removal_traced']=removed==set(r['source_id']for r in rows)
checks['two_distinct_views']=all(len(set(r['source_tiles']))>=2 and len(r['views'])>=2 for r in rows)
checks['image_supported_keepers']=all(all(v['source_valid']>=.95 and v['target_valid']>=.95 and v['target_support']>=.85 and v['target_median']>=22 for v in r['views'])for r in rows)
def reason_supported(r):
if r['kind']=='overlapping_duplicate':return r['geometry']['contained_fraction']>=.9
if r['kind']=='unsupported_offset_duplicate':return all(v['source_support']<=.15 and v['source_q75']<8 for v in r['views'])
if r['kind']!='one_ridge_two_vectors':return False
offsets=[]
for x in r['ridges']:
if len(x['peaks'])!=1 or x['valid_fraction']<.95 or x['two_ridge_fraction']>.1 or x['longest_two_ridge_m']>=.25:return False
d=x['peaks'][0]['offset'];offsets.append(d)
if abs(d)<.10 or abs(d-x['target_offset'])>.08 or abs(d)-abs(d-x['target_offset'])<.06:return False
return len(offsets)>=2 and max(offsets)-min(offsets)<=.05
checks['no_observed_second_ridge_removed']=all(all(x['valid_fraction']>=.95 and x['two_ridge_fraction']<=.1 and x['longest_two_ridge_m']<.25 for x in r['ridges'])for r in rows)
checks['each_reason_has_evidence']=all(reason_supported(r)for r in rows)
checks['crosswalk_audit_preserved']=Path('/out/crosswalk-standard-check.json').read_bytes()==Path('/fullplan/crosswalk-standard-check.json').read_bytes()
checks['same_policy']=new['consensus_refinement']=='two-view-redundant-paint-v1'
result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/consensus-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,64 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_consensus.py": "consensus_pass/audit_consensus.py",
"audit_norms.py": "norms_pass/audit_norms.py",
"audit_transitions.py": "transitions_pass/audit_transitions.py",
"consensus_profiles.py": "consensus_pass/consensus_profiles.py",
"fit_scene.py": "full_plan/fit_scene.py",
"gost_catalog.py": "norms_pass/gost_catalog.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"interval_profiles.py": "intervals_pass/interval_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "intervals_pass/line_reconstruction.py",
"norm_profiles.py": "norms_pass/norm_profiles.py",
"refine_consensus.py": "consensus_pass/refine_consensus.py",
"refine_norms.py": "norms_pass/refine_norms.py",
"refine_transitions.py": "transitions_pass/refine_transitions.py",
"render_consensus.py": "consensus_pass/render_consensus.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "continuation_pass/render_plan.py",
"render_transitions.py": "transitions_pass/render_transitions.py",
"test_consensus.py": "consensus_pass/test_consensus.py",
"test_intervals.py": "intervals_pass/test_intervals.py",
"test_lines.py": "lines_pass/test_lines.py",
"test_norms.py": "norms_pass/test_norms.py",
"test_transitions.py": "transitions_pass/test_transitions.py",
"transition_profiles.py": "transitions_pass/transition_profiles.py"
},
"reference_qualification": "consensus-pass-20261012",
"source_snapshot": "430fd320ec10ad4ea212",
"source_sha256": {
"audit_consensus.py": "7056d6195b320ae165aeef44e802c29697ae8163abb99d4593e0c8df6e186bc2",
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"audit_transitions.py": "35a3ecb08d96ee21badf438a18bdddf800263032078e2daee888673ab4209c4a",
"consensus_profiles.py": "4069e7e56eff1cfe3c10884a63a8c329891bbdffa68f477281c2eebff9128091",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"gost_catalog.py": "a55a837cc1473055ff24d340c6a669a45d8295f9efb08fd81f1bf2651c0ac537",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"norm_profiles.py": "fe5169f850919abdbc762fcf12960ef7dc0185f1ae56330246ca322db6caa0e7",
"refine_consensus.py": "e0e6bf6ad7023515103be330df93b5d925cc1c62642d1a38e67f07cbe027eb36",
"refine_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"refine_transitions.py": "777d0a0f4d9c762768311db154f66a77880790f523ec639bbd02225ac470138b",
"render_consensus.py": "ea677bac3a4950209133268801f238c67236b0e7866f22df3e738e7592fde682",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"render_transitions.py": "eea6be5a6f90145f00d7e930f4123c87aa135a64a2c59723908cf7056520128d",
"test_consensus.py": "90cdd1be7bd2a0d1471141eb40bfa806cc149789c3d6794bbfdaba5999a369f7",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f",
"test_transitions.py": "95837d6e04c890f514901d9b587092f79fa1552dde6df99e301849d66c004438",
"transition_profiles.py": "7f713e5fed3a1aa88d00a4c3299b45a8970ff225ab827f82950901185b33ea2e"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,97 @@
"""Image-supported suppression of redundant thin vector paint objects.
Nearby vectors nominate pairs only. Two render views must independently pass
the same evidence gates; they are views of the same reconstruction, not two
independent measurements of the real road.
"""
import numpy as np
from scipy.signal import find_peaks,peak_widths
from interval_profiles import strip,runs
from line_reconstruction import observation
POLICY=dict(max_angle_deg=4.,max_lateral_m=.65,min_overlap=.75,
min_valid=.95,min_keeper_support=.85,min_keeper_median=22.,
max_ghost_support=.15,max_ghost_q75=8.,min_views=2,
max_keeper_ridge_offset_m=.08,min_source_ridge_offset_m=.10,
min_ridge_offset_advantage_m=.06,max_two_ridge_fraction=.10,
max_two_ridge_run_m=.25,max_view_ridge_disagreement_m=.05)
def pair_geometry(source,target):
a,b=[observation(np.asarray(p.exterior.coords),'vector')for p in [source,target]]
if not (1.45<a['L']<70 and 1.45<b['L']<70 and a['W']<=.6 and b['W']<=.4):return None
if abs(a['axis']@b['axis'])<np.cos(np.deg2rad(POLICY['max_angle_deg'])):return None
u=a['axis'];n=np.array([-u[1],u[0]]);d=b['center']-a['center'];lateral=float(abs(d@n))
if lateral>POLICY['max_lateral_m']:return None
tt=(np.asarray(target.exterior.coords)-a['center'])@u
overlap=max(0.,min(a['L']/2,tt.max())-max(-a['L']/2,tt.min()))/a['L']
if overlap<POLICY['min_overlap']:return None
contained=source.intersection(target).area/max(source.area,1e-9)
return dict(lateral_m=lateral,overlap_fraction=float(overlap),contained_fraction=float(contained))
def shared_ridge(source,target,sampler):
"""Inspect one common transverse profile to distinguish one/two paint ridges."""
a,b=[observation(np.asarray(p.exterior.coords),'vector')for p in [source,target]]
u=a['axis'].astype(float);u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
tt=(np.asarray(target.exterior.coords)-a['center'])@u
lo=max(-a['L']/2,tt.min())+.15;hi=min(a['L']/2,tt.max())-.15
ts=np.arange(lo,hi,.05);ns=np.arange(-.9,.901,.025)
contrast,allowed=strip(a['center'],u,ts,ns,sampler)
profile=np.median(contrast,axis=0);offset=float((b['center']-a['center'])@n)
corridor=(ns>=min(0,offset)-.12)&(ns<=max(0,offset)+.12)
pk,_=find_peaks(profile,height=18,prominence=max(8.,float(profile.max())*.20),distance=4)
pw=peak_widths(profile,pk,rel_height=.5)[0]*.025
peaks=[dict(offset=float(ns[k]),width=float(w),height=float(profile[k]))for k,w in zip(pk,pw)if corridor[k]and .05<w<.50]
two=[]
for row in contrast:
rr,_=find_peaks(row,height=12,prominence=max(8.,float(row.max())*.18),distance=4)
left=[j for j in rr if abs(ns[j])<=.08]
right=[j for j in rr if abs(ns[j]-offset)<=.08]
two.append(any(i!=j and abs(ns[i]-ns[j])>=.10 for i in left for j in right))
longest=max([(b-a)*.05 for a,b in runs(np.array(two))]or[0.])
return dict(peaks=peaks,target_offset=offset,valid_fraction=float(allowed[:,corridor].mean()),
two_ridge_fraction=float(np.mean(two)),longest_two_ridge_m=longest,
offsets=ns.tolist(),profile=profile.tolist())
def observe_track(poly,sampler):
o=observation(np.asarray(poly.exterior.coords),'vector');u=o['axis'].astype(float);u/=np.linalg.norm(u)
trim=min(.15,o['L']*.08);ts=np.arange(-o['L']/2+trim,o['L']/2-trim,.05);ns=np.arange(-.80,.801,.025)
contrast,allowed=strip(o['center'],u,ts,ns,sampler)
band=abs(ns)<=max(.025,min(.05,o['W']*.25))
signal=np.median(contrast[:,band],axis=1);valid=allowed[:,band].mean(1)>.85
return dict(signal=signal,valid=valid)
def decision(geometry,views,ridges=None):
records=[]
for source,target in views:
s,v=source['signal'],source['valid'];t,w=target['signal'],target['valid']
if not len(s)or not len(t):return None,records
level=float(np.median(t[w]))if w.any()else 0.;cut=max(15.,.35*level)
rec=dict(source_valid=float(v.mean()),target_valid=float(w.mean()),
source_support=float(((s>cut)&v).mean()),target_support=float(((t>cut)&w).mean()),
source_q75=float(np.quantile(s[v],.75))if v.any()else 0.,target_median=level,cut=cut)
records.append(rec)
if len(records)<POLICY['min_views']:return None,records
if any(r['source_valid']<POLICY['min_valid'] or r['target_valid']<POLICY['min_valid']or
r['target_support']<POLICY['min_keeper_support'] or r['target_median']<POLICY['min_keeper_median']for r in records):return None,records
# A real intermittent second row vetoes every suppression reason, including
# containment. A wide old vector must not erase a valid nested narrow row.
if ridges and any(r['valid_fraction']<POLICY['min_valid'] or
r['two_ridge_fraction']>POLICY['max_two_ridge_fraction'] or
r['longest_two_ridge_m']>=POLICY['max_two_ridge_run_m']for r in ridges):return None,records
# Strong containment is a geometric duplicate even if both sample paint.
# The retained full stroke must itself be image-supported in every view.
if geometry['contained_fraction']>=.90:return 'overlapping_duplicate',records
if ridges and len(ridges)>=POLICY['min_views']:
single=all(len(r['peaks'])==1 and r['valid_fraction']>=POLICY['min_valid']and
r['two_ridge_fraction']<=POLICY['max_two_ridge_fraction']and
r['longest_two_ridge_m']<POLICY['max_two_ridge_run_m']for r in ridges)
if single:
offsets=[r['peaks'][0]['offset']for r in ridges]
aligned=all(abs(r['peaks'][0]['offset']-r['target_offset'])<=POLICY['max_keeper_ridge_offset_m']and
abs(r['peaks'][0]['offset'])>=POLICY['min_source_ridge_offset_m']and
abs(r['peaks'][0]['offset'])-abs(r['peaks'][0]['offset']-r['target_offset'])>=POLICY['min_ridge_offset_advantage_m']for r in ridges)
if aligned and max(offsets)-min(offsets)<=POLICY['max_view_ridge_disagreement_m']:
return 'one_ridge_two_vectors',records
if all(r['source_support']<=POLICY['max_ghost_support']and r['source_q75']<POLICY['max_ghost_q75']for r in records):
return 'unsupported_offset_duplicate',records
return None,records
@@ -0,0 +1,70 @@
from pathlib import Path
from functools import lru_cache
import os,json,time,hashlib
import numpy as np,cv2,shapely
from PIL import Image
from shapely.geometry import shape
from layer_common import O,S,sample
from fit_scene import project
from consensus_profiles import POLICY,pair_geometry,observe_track,decision,shared_ridge
cv2.setNumThreads(3);started=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.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']
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'])
@lru_cache(maxsize=4)
def inputs(name):
geom=geometry(name);rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB'))
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle'].astype('float32')
return geom,rgb,vehicle
@lru_cache(maxsize=90)
def geometry(name):return dict(np.load(S/name/'top.geometry.npz'))
def sampler(name):
def read(points):
geom,rgb,vehicle=inputs(name);uv=project(points,geom).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5;chunks=max(1,int(np.ceil(len(uv)/20000)))
colors=np.concatenate([cv2.remap(rgb,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).reshape(-1,3)for q in np.array_split(native,chunks)])
veh=np.concatenate([cv2.remap(vehicle,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,chunks)])
alpha=np.concatenate([cv2.remap(geom['alpha'].astype('float32'),q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).ravel()for q in np.array_split(uv,chunks)])
valid=(uv[:,0]>=0)&(uv[:,1]>=0)&(uv[:,0]<1199)&(uv[:,1]<1199)
allowed=valid&(alpha>=.65)&(sample(labels,points,low,high)==1)&(veh<.20)&~shapely.contains_xy(protected,points[:,0],points[:,1])
return colors,allowed
return read
linear={f['id']:shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties'].get('subtype')=='linear_marking'and f['geometry']['type']=='Polygon'}
@lru_cache(maxsize=1500)
def observed(fid,name):return observe_track(linear[fid],sampler(name))
pairs=[]
for sid,p in linear.items():
for tid,q in linear.items():
if sid==tid:continue
geom=pair_geometry(p,q)
if geom is not None:pairs.append((sid,tid,geom))
# Nearby pairs share decoded tile images. Stable tie-breaking does not depend
# on street names, route distance or hard-coded coordinates.
pairs.sort(key=lambda x:(tuple(linear[x[0]].centroid.coords[0]),x[0],x[1]))
proposals=[];diagnostics=[]
for k,(sid,tid,geom)in enumerate(pairs):
center=np.array(linear[sid].centroid.coords[0]);ranked=sorted(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center))
names=[];vertices=np.concatenate([np.asarray(linear[fid].exterior.coords)for fid in [sid,tid]])
for tile in ranked:
uv=project(vertices,geometry(tile['id']))
if uv.min()>=20 and uv.max()<1180:names.append(tile['id'])
if len(names)==2:break
views=[(observed(sid,name),observed(tid,name))for name in names]
ridges=[shared_ridge(linear[sid],linear[tid],sampler(name))for name in names]
kind,evidence=decision(geom,views,ridges);rec=dict(source_id=sid,target_id=tid,source_tiles=names,geometry=geom,views=evidence,ridges=ridges,kind=kind)
diagnostics.append(rec)
if kind:proposals.append(rec)
if k%50==0:print('PAIR',k,len(pairs),'CANDIDATES',len(proposals),flush=True)
# Greedy selection keeps every nominated keeper. A keeper can never later be
# removed, which avoids deletion cycles for coincident copies.
removed=set();keepers=set();accepted=[]
for rec in sorted(proposals,key=lambda r:(r['kind']!='unsupported_offset_duplicate',max(v['source_support']for v in r['views']),-min(v['target_support']for v in r['views']),r['source_id'])):
sid,tid=rec['source_id'],rec['target_id']
if sid in removed or sid in keepers or tid in removed:continue
removed.add(sid);keepers.add(tid);p=linear[sid].union(linear[tid]);accepted.append({**rec,'bounds_xy':p.bounds,'source_ids':[sid],'output_ids':[tid],'source_tile':rec['source_tiles'][0]})
result={**old,'features':[f for f in old['features']if f['id']not in removed],'consensus_refinement':'two-view-redundant-paint-v1'}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'consensus-rows.json').write_text(json.dumps(accepted,indent=2));(O/'consensus-diagnostics.json').write_text(json.dumps(diagnostics,indent=2));(O/'consensus-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed))))
(O/'crosswalk-standard-check.json').write_bytes(Path('/fullplan/crosswalk-standard-check.json').read_bytes())
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),changed_segments=len(accepted),removed_duplicates=len(removed),offset_duplicates=sum(r['kind']=='unsupported_offset_duplicate'for r in accepted),overlapping_duplicates=sum(r['kind']=='overlapping_duplicate'for r in accepted),single_ridge_duplicates=sum(r['kind']=='one_ridge_two_vectors'for r in accepted),candidate_pairs=len(pairs),before_linear_objects=len(linear),after_linear_objects=len(linear)-len(removed),policy=POLICY,policy_version='two-view-redundant-paint-v1',manual_geometry=False,manual_rois=[],legal_compliance_assessed=False)
(O/'consensus-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,41 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=[dict(**r,baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'consensus-rows.json').read_text())];tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('rows-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='rows-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('rows-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'rows-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
# Revisit every short-dash family shown in the prior delivery, using its stored
# bounds only for review framing; these bounds never enter the detector.
references=json.loads(Path('/families/line-families.json').read_text());ref_manifest=[]
for gi,rec in enumerate(references):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]):
frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640')
fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only'))
(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2))
@@ -0,0 +1,54 @@
import json,runpy,numpy as np
from consensus_profiles import pair_geometry,observe_track,decision,shared_ridge
from interval_profiles import rectangle
from shapely.geometry import Polygon
prior=runpy.run_path('/candidate/test_transitions.py')['result'];checks={'prior_'+k:v for k,v in prior['checks'].items()}
def obs(signal=80.,valid=True):return dict(signal=np.full(80,signal),valid=np.full(80,valid))
g=dict(contained_fraction=0.,overlap_fraction=1.,lateral_m=.3)
checks['ghost_requires_supported_keeper']=decision(g,[(obs(0),obs())]*2)[0]=='unsupported_offset_duplicate'
checks['true_parallel_pair_retained']=decision(g,[(obs(),obs())]*2)[0]is None
checks['worn_parallel_paint_retained']=decision(g,[(obs(12),obs())]*2)[0]is None
checks['occluded_source_retained']=decision(g,[(obs(0,False),obs())]*2)[0]is None
checks['occluded_keeper_no_deletion']=decision(g,[(obs(0),obs(80,False))]*2)[0]is None
checks['disagreeing_views_no_deletion']=decision(g,[(obs(0),obs()),(obs(),obs())])[0]is None
checks['missing_second_view_no_deletion']=decision(g,[(obs(0),obs())])[0]is None
checks['blank_pair_retained']=decision(g,[(obs(0),obs(0))]*2)[0]is None
checks['overlapping_copies_resolved']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2)[0]=='overlapping_duplicate'
checks['overlap_alone_not_evidence']=decision({**g,'contained_fraction':.97},[(obs(0),obs(0))]*2)[0]is None
o=np.array([0.,0.]);u=np.array([1.,0.]);a=rectangle(o,u,0,6,.15,.35);b=rectangle(o,u,0,6,.15)
checks['parallel_geometry_candidate']=pair_geometry(a,b)is not None
checks['perpendicular_not_duplicate']=pair_geometry(a,rectangle(o,np.array([0.,1.]),0,6,.15))is None
checks['neighbor_lane_not_duplicate']=pair_geometry(a,rectangle(o,u,0,6,.15,3.5))is None
checks['short_overlap_not_duplicate']=pair_geometry(a,rectangle(o,u,5,11,.15))is None
def sampler(xy):
paint=(abs(xy[:,1])<.075)&(xy[:,0]>-.1)&(xy[:,0]<6.1)
return np.repeat(np.where(paint,210,65)[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
s,t=observe_track(a,sampler),observe_track(b,sampler);reason,_=decision(pair_geometry(a,b),[(s,t)]*2)
checks['image_profile_rejects_offset_ghost']=reason=='unsupported_offset_duplicate'
theta=.87;rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([125.,-71.]);ar=Polygon(np.asarray(a.exterior.coords)@rot.T+shift);br=Polygon(np.asarray(b.exterior.coords)@rot.T+shift)
read=lambda xy:sampler((xy-shift)@rot);sr,tr=observe_track(ar,read),observe_track(br,read)
checks['rigid_transform_invariance']=decision(pair_geometry(ar,br),[(sr,tr)]*2)[0]==reason
def blurred_sampler(xy):
value=65+140*np.exp(-.5*(xy[:,1]/.085)**2)
return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
a=rectangle(o,u,0,6,.15,.15);b=rectangle(o,u,0,6,.15)
s,t=observe_track(a,blurred_sampler),observe_track(b,blurred_sampler);ridge=shared_ridge(a,b,blurred_sampler)
checks['one_blurred_ridge_not_two_lines']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]=='one_ridge_two_vectors'
def dual_sampler(xy):
value=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.20)/.028)**2)
return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
a=rectangle(o,u,0,6,.10,.20);b=rectangle(o,u,0,6,.10)
s,t=observe_track(a,dual_sampler),observe_track(b,dual_sampler);ridge=shared_ridge(a,b,dual_sampler)
checks['two_physical_ridges_preserved']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]is None
checks['transverse_profile_resolves_two_ridges']=len(ridge['peaks'])==2
# Intermittent neighbor paint must survive even if it vanishes in the median.
def intermittent(xy):
value=65+130*np.exp(-.5*(xy[:,1]/.028)**2)+110*np.exp(-.5*((xy[:,1]-.20)/.028)**2)*((xy[:,0]%1.5)<.4)
return np.repeat(value[:,None],3,1).astype('uint8'),np.ones(len(xy),bool)
s,t=observe_track(a,intermittent),observe_track(b,intermittent);ridge=shared_ridge(a,b,intermittent)
checks['intermittent_second_ridge_preserved']=decision(pair_geometry(a,b),[(s,t)]*2,[ridge]*2)[0]is None
checks['short_parallel_runs_detected']=ridge['longest_two_ridge_m']>=.25
checks['real_second_ridge_vetoes_containment']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2,[ridge]*2)[0]is None
invalid={**ridge,'valid_fraction':.4,'two_ridge_fraction':0.,'longest_two_ridge_m':0.}
checks['unknown_transverse_corridor_preserved']=decision({**g,'contained_fraction':.97},[(obs(),obs())]*2,[invalid]*2)[0]is None
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/consensus-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']