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,73 @@
Observed long-dash families with dimensional checks
==================================================
Scope
-----
Offline, Gaussian-only refinement of intervals-pass-20261012 on Worker006.
Every eligible existing long paint element seeds a rectified image strip. No
per-location thresholds, coordinates or manually chosen processing regions.
Roads, sidewalks, facades, short-dash families, symbols and crosswalk geometry
are preserved unless a linear object lies inside a confirmed long-dash row.
The implementation uses OpenCV remap/morphology/Huber fitLine, SciPy filtering,
peak finding and robust least_squares, and Shapely geometry operations.
Method
------
The existing transverse background subtraction separates paint from road. A
nearby supported ridge must belong to the seed's row. Longitudinal evidence
must contain at least three similar observed strokes and two valid dark gaps.
Each gap needs >=90% valid support, >=75% dark samples and sufficient contrast.
Unknown pixels, cars and crosswalk masks cannot stand in for visible asphalt.
Only sub-stroke cracks <=15 cm are closed. A constant measured stroke length,
width, phase and period regularize each accepted series; no exterior slots are
extrapolated. Existing unsupported geometry outside its domain is retained.
Overlapping windows merge only if position, direction, period and phase agree;
a lateral straightness veto prevents merging curves or neighboring rows.
Standards
---------
gost_catalog.py contains a versioned geometric catalogue from GOST R 51256-2018
with amendment 1, Appendix A table A.1, and application tolerances from 5.1.4.1.
Current status and amendment were checked on 2026-10-12 in Rosstandart's registry:
https://protect.gost.ru/gost/details/e84660db-4e3b-4c82-9627-c142a36355d2
The published standard text used for dimensions:
https://www.mos.ru/upload/documents/files/1106/GOSTR51256-2018TehnicheskiesredstvaorganizaciidorojnogodvijeniyaR_.pdf
A standard rhythm is a small tie-breaker between equally image-supported
hypotheses, and a dimensional cross-check. It never cuts an observed solid
line without dark-gap evidence, changes map scale, or silently stretches a
nonstandard measured pattern. Nominal sizes, measured sizes and residuals are
separate. The broad 18% period / 25% stroke-length model-association thresholds
are algorithmic uncertainty bounds, NOT GOST manufacturing/application limits.
'rhythm_compatible' does not assert width, colour, use or legal compliance.
Several marking types share a rhythm; candidate classes remain ambiguous until
road context, companion lines and colour are qualified. Speed is not inferred.
GOST R 52289 application rules are not implemented in this pass.
Existing crosswalk vector families are checked for stripe width, centre spacing
and stripe length against the 1.14.1 geometric reference. This is an audit of
previously reconstructed vectors, not a new independent photogrammetric survey.
Crosswalks are not resized, and mismatch is not declared a road-code violation.
The road application context and Gaussian reconstruction uncertainty remain.
Limits
------
Seeded straight-row refinement is not complete paint detection. Long lines
outside accepted evidence intervals, poorly visible paint, curves, endpoints
and some prior false positives remain. Nearby strokes can be slightly wider
or shorter in a Gaussian render. Metric ground-truth accuracy and whole-map
precision/recall are not measured. See visual-review.json for actual scope.
Reproduction
------------
Pinned image sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0.
4 CPU, 20 GiB RAM, 1 GiB tmpfs, read-only root, network none, 1800s per stage.
All computation, tests and rendering run on Worker006. The Mac orchestrates,
checks hashes, copies and displays files. Required private scene caches and
queue/SSH configuration are external dependencies, not included in the ZIP.
Canonical bundle: simulation/urban-plan-research/norms_pass/bundle.json.
Qualification: .runtime/simulation-qualifications/norms-pass-20261012/operator.
Stages: test_norms, refine_norms, audit_norms, render_norms, render_plan.
Source ZIP is flat; bundle.json resolves reused canonical modules. Separately
hashed review-font.ttf is rendering-only and excluded from the ZIP.
No live map deploy, Ops publication, commit, point cloud or collider input.
@@ -0,0 +1,15 @@
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())
removed=set(json.loads(Path('/out/norm-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']};rows=json.loads(Path('/out/norm-rows.json').read_text());checks={}
checks['unique_ids']=len(features)==len(new['features'])
checks['untouched_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed)
checks['only_linear_paint_replaced']=all(f['properties'].get('subtype')=='linear_marking'for f in old['features']if f['id']in removed)
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['output_lineage']=all(fid in features for r in rows for fid in r['output_ids'])
checks['real_gaps_required']=all(len(r['gaps'])>=2 and all(g['valid_fraction']>=.9 and g['dark_fraction']>=.75 for g in r['gaps'])for r in rows)
checks['gost_not_compliance']=all(r['norm']['compliance']=='not_assessed'for r in rows)
checks['same_policy']=new['norm_refinement']=='observed-long-dash-family-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/norm-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,44 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_norms.py": "norms_pass/audit_norms.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_norms.py": "norms_pass/refine_norms.py",
"render_norms.py": "norms_pass/render_norms.py",
"render_plan.py": "continuation_pass/render_plan.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"
},
"reference_qualification": "norms-pass-20261012",
"source_snapshot": "0ce36da982893694f306",
"source_sha256": {
"audit_norms.py": "234e431040e38d9c999f10a62d05454f217673cda5e2ab3e3119a2fabf9e703d",
"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_norms.py": "081f6f2347a19b996d5f1b69d63194112d808071eb8c8313e173b5cd09e2dfd5",
"render_norms.py": "3a8bcf81723d7bda4b49c8ff12e21efded4450839e11a4f23e719dfc8fa4441d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a",
"test_norms.py": "02b0757f7c1c4498c9165dde2bd650ca9f0a1dec840d59e7828343264079905f"
},
"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,66 @@
"""Versioned geometric priors, never a finding of regulatory compliance.
ГОСТ Р 51256-2018, amendment 1, Appendix A, table A.1; 5.1.4.1.
Status checked 2026-10-12 in Rosstandart's official catalogue.
Geometry alone cannot determine legal use, road speed or marking authority.
"""
import math
STANDARD = 'GOST-R-51256-2018-amendment-1'
SOURCES = [
'https://protect.gost.ru/gost/details/e84660db-4e3b-4c82-9627-c142a36355d2',
'https://www.mos.ru/upload/documents/files/1106/GOSTR51256-2018TehnicheskiesredstvaorganizaciidorojnogodvijeniyaR_.pdf',
]
# Equal geometry has multiple legal meanings. Keep candidate classes together.
DASH_TEMPLATES = [
dict(classes=['1.5', '1.8'], length=1., gap=3.),
dict(classes=['1.5'], length=2., gap=6.),
dict(classes=['1.5'], length=3., gap=9.),
dict(classes=['1.5'], length=4., gap=12.),
dict(classes=['1.6', '1.9', '1.11'], length=3., gap=1.),
dict(classes=['1.6', '1.9', '1.11'], length=6., gap=2.),
dict(classes=['1.6', '1.9', '1.11'], length=9., gap=3.),
dict(classes=['1.7'], length=.5, gap=.5),
dict(classes=['1.11'], length=.9, gap=.3),
dict(classes=['1.10'], length=1., gap=1.),
]
def dimensional_tolerance(size):
"""Application tolerance from table 1; NOT Gaussian measurement error."""
return .01 if size <= .2 else .02 if size <= .4 else .05 if size <= 7 else .10
def assess_dash(length, period, width):
gap = period-length
if min(length, gap, width) <= 0:
return dict(status='unresolved', compliance='not_assessed')
# Broad model-association tolerance explicitly separate from legal tolerance.
ranked = sorted(DASH_TEMPLATES, key=lambda t:
abs(math.log(period/(t['length']+t['gap']))) +
.5*abs(math.log(length/t['length'])))
t = ranked[0]; pe = abs(period/(t['length']+t['gap'])-1)
le = abs(length/t['length']-1)
compatible = pe <= .18 and le <= .25
candidates=[]
for cls in t['classes']:
permitted = [.2,.4] if cls=='1.8' else [.1,.15,.2] if cls in ['1.9','1.10','1.11'] else [.1,.15]
nominal=min(permitted,key=lambda x:abs(x-width))
candidates.append(dict(marking=cls,widths_m=permitted,nearest_width_m=nominal,
width_residual_m=width-nominal,
width_application_tolerance_m=dimensional_tolerance(nominal)))
return dict(standard=STANDARD,status='rhythm_compatible' if compatible else 'measured_nonstandard_or_uncertain',
compliance='not_assessed',candidate_classes=candidates,
nominal_length_m=t['length'],nominal_gap_m=t['gap'],
observed_length_m=float(length),observed_gap_m=float(gap),observed_period_m=float(period),observed_width_m=float(width),
period_relative_error=pe,length_relative_error=le,
geometry_policy='measured_period_and_phase; nominal_dimensions_are_soft_prior; no_scale_change',
application_tolerances_m={k:dimensional_tolerance(t[k]) for k in ['length','gap']},
model_association_tolerances=dict(period_relative=.18,length_relative=.25))
def assess_crosswalk(width, spacing, stripe_length):
return dict(standard=STANDARD,candidate_marking='1.14.1',compliance='not_assessed',
observed_width_m=float(width),observed_spacing_m=float(spacing),
observed_gap_m=float(spacing-width),observed_stripe_length_m=float(stripe_length),
nominal_width_m=.4,nominal_gap_m=.6,nominal_spacing_m=1.,
nominal_stripe_length_range_m=[4.,6.],
width_residual_m=float(width-.4),spacing_residual_m=float(spacing-1.),
geometry_changed=False,reason='Existing vector measurement; Gaussian uncertainty and application context are not a legal compliance test')
@@ -0,0 +1,125 @@
"""Whole-row paint/gap fitting with standard geometry as a soft prior."""
import numpy as np,cv2
from scipy.ndimage import gaussian_filter1d
from scipy.optimize import least_squares
from scipy.signal import find_peaks
from interval_profiles import strip,runs,rectangle
from line_reconstruction import observation
from gost_catalog import assess_dash
def fit_runs(ts,signal,valid,step=.025):
"""Require at least three actual strokes and two observed asphalt gaps.
Unknown/occluded pixels cannot become gap evidence. Only a regular bounded
subseries is replaced, preserving solid-to-dash transitions outside it.
"""
if valid.sum()<80:return None
level=float(np.quantile(signal[valid],.80))
if level<22:return None
cut=max(15.,level*.40)
paint=(signal>cut)&valid
for a,b in runs(~paint):
if a>0 and b<len(paint) and (b-a)*step<=.15 and valid[a:b].all():paint[a:b]=True
strokes=[(a,b)for a,b in runs(paint)if (b-a)*step>=.65]
candidates=[]
for start in range(len(strokes)-2):
for end in range(start+3,min(len(strokes),start+12)+1):
seq=strokes[start:end]
lengths=np.array([(b-a)*step for a,b in seq]);L=float(np.median(lengths))
if not 1.45<L<10.5 or np.max(abs(lengths-L))>max(.35,.20*L):continue
centers=np.array([(ts[a]+ts[b-1])/2 for a,b in seq]);delta=np.diff(centers)
P=float(np.median(delta))
if P-L<.30 or np.max(abs(delta-P))>max(.22,.08*P):continue
gaps=[]
for (_,a),(b,_) in zip(seq,seq[1:]):
# Avoid ambiguous blurred stroke edges in the gap validation.
aa=a+max(1,int(.06/step));bb=b-max(1,int(.06/step))
if bb<=aa:break
good=float(valid[aa:bb].mean());dark=float((signal[aa:bb]<cut).mean())
contrast=float(level-np.median(signal[aa:bb]))
if good<.90 or dark<.75 or contrast<15:break
gaps.append(dict(lo=float(ts[aa]),hi=float(ts[bb-1]),valid_fraction=good,dark_fraction=dark,contrast=contrast))
if len(gaps)!=len(seq)-1:continue
k=np.arange(len(seq));fit=least_squares(lambda v:(v[0]+k*v[1]-centers),[centers[0],P],loss='soft_l1',f_scale=.10)
phase,period=fit.x
if np.max(abs(phase+k*period-centers))>.25:continue
# A standard candidate may help rank equally supported hypotheses;
# measured phase/period remain authoritative and no global rescale.
norm=assess_dash(L,float(period),.15)
prior=.05 if norm['status']=='rhythm_compatible'else 0
candidates.append((len(seq)+prior+float(period)*.001,dict(phase=float(phase),period=float(period),length=L,
centers=(phase+k*period).tolist(),runs=seq,gaps=gaps,cut=cut,level=level,norm=norm,
phase_residual_m=float(np.max(abs(phase+k*period-centers))))))
return max(candidates,key=lambda x:x[0])[1]if candidates else None
def reconstruct_long(poly,sampler,debug=None):
obs=observation(np.asarray(poly.exterior.coords),'seed');o=obs['center'];u=obs['axis'].astype(float);u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
if not 1.45<obs['L']<70 or obs['W']>.4:return None
step=.025;ts=np.arange(-obs['L']/2-14,obs['L']/2+14,step);ns=np.arange(-.60,.601,step)
contrast,allowed=strip(o,u,ts,ns,sampler)
profile=np.quantile(np.where(allowed,contrast,0),.80,axis=0)
peaks,_=find_peaks(profile,height=18,prominence=12,distance=4)
peaks=[k for k in peaks if abs(ns[k])<=.22]
if not peaks:return None
# Seed identity controls the row; never jump to a neighboring paint track.
k=min(peaks,key=lambda k:abs(ns[k]));offset=float(ns[k]);band=abs(ns-offset)<=.04
signal=gaussian_filter1d(np.median(contrast[:,band],axis=1),1)
valid=allowed[:,band].mean(1)>.85
fit=fit_runs(ts,signal,valid,step)
if debug is not None:debug.update(length=obs['L'],offset=offset,ts=ts[::4].tolist(),signal=signal[::4].tolist(),valid=valid[::4].tolist(),accepted=fit is not None)
if fit is None:return None
centers=np.array(fit['centers']);L=fit['length'];lo=centers[0]-L/2;hi=centers[-1]+L/2
if hi < -obs['L']/2 or lo > obs['L']/2:return None
# Measure width only at supported stroke interiors; keep a constant row width.
bright=np.zeros(len(ts),bool)
for a,b in fit['runs']:bright[a+2:b-2]=True
normal=np.median(contrast[bright],axis=0);near=abs(ns-offset)<.17
indices=np.flatnonzero((normal>max(15,normal[k]*.5))&near)
W=float(np.clip((indices.max()-indices.min()+1)*step if len(indices)else obs['W'],.075,.30))
polys=[rectangle(o,u,c-L/2,c+L/2,W,offset)for c in centers]
domain=rectangle(o,u,lo-.10,hi+.10,max(W,obs['W'])+.10,offset)
for gap in fit['gaps']:
gap['world_start_xy']=(o+gap['lo']*u+offset*n).tolist()
gap['world_end_xy']=(o+gap['hi']*u+offset*n).tolist()
fit.update(polygons=polys,domain=domain,axis=u,origin=o,width=W,offset=offset,
norm=assess_dash(L,fit['period'],W),bounds_xy=domain.bounds)
return fit
def merge_overlapping(records):
"""Join overlapping measured windows only when phase and direction agree.
No new slots are extrapolated. This removes arbitrary tile/seed boundaries
while retaining a straightness veto for curves and neighboring lines.
"""
result=[]
for rec in sorted(records,key=lambda r:-len(r['polygons'])):
merged=False
for j,prior in enumerate(result):
u=prior['axis'];n=np.array([-u[1],u[0]])
if abs(u@rec['axis'])<np.cos(np.deg2rad(1.5)):continue
if abs(rec['period']/prior['period']-1)>.05 or abs(rec['length']/prior['length']-1)>.18:continue
pa=np.array([p.centroid.coords[0]for p in prior['polygons']]);pb=np.array([p.centroid.coords[0]for p in rec['polygons']])
if abs((pb.mean(0)-pa.mean(0))@n)>.14:continue
ta=pa@u;tb=pb@u
overlap=min(ta.max(),tb.max())-max(ta.min(),tb.min())
if overlap<prior['period']*.7:continue
points=np.concatenate([pa,pb]);line=cv2.fitLine(points.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();uu=line[:2].astype(float);oo=line[2:].astype(float)
if uu@u<0:uu=-uu
nn=np.array([-uu[1],uu[0]])
if max(abs((points-oo)@nn))>.13:continue
t=(points-oo)@uu;P=np.mean([prior['period'],rec['period']]);slots=np.rint((t-t.min())/P).astype(int)
fit=least_squares(lambda v:v[0]+slots*v[1]-t,[t.min(),P],loss='soft_l1',f_scale=.1)
phase,P=fit.x
if max(abs(phase+slots*P-t))>.25:continue
ids=sorted(set(slots.tolist()))
if max(np.diff(ids))>1:continue
centers=phase+np.array(ids)*P;L=float(np.mean([prior['length'],rec['length']]));W=float(np.mean([prior['width'],rec['width']]))
polygons=[rectangle(oo,uu,c-L/2,c+L/2,W)for c in centers]
domain=rectangle(oo,uu,centers[0]-L/2-.1,centers[-1]+L/2+.1,W+.14)
result[j]={**prior,'axis':uu,'origin':oo,'offset':0.,'centers':centers.tolist(),'period':float(P),'length':L,'width':W,
'polygons':polygons,'domain':domain,'bounds_xy':domain.bounds,'gaps':prior['gaps']+rec['gaps'],
'phase_residual_m':float(max(abs(phase+slots*P-t))),'norm':assess_dash(L,float(P),W),
'source_tiles':sorted(set(prior.get('source_tiles',[prior['source_tile']])+rec.get('source_tiles',[rec['source_tile']])))}
merged=True;break
if not merged:result.append(rec)
return result
@@ -0,0 +1,94 @@
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 shapely.ops import transform
from layer_common import O,S,feature,sample,parts
from fit_scene import project
from line_reconstruction import observation
from norm_profiles import reconstruct_long,merge_overlapping
from gost_catalog import assess_crosswalk,STANDARD,SOURCES
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'];height=z['z'];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'])
def lift(p):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),p)
@lru_cache(maxsize=3)
def inputs(name):
geom=dict(np.load(S/name/'top.geometry.npz'))
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
def sampler_for(center):
tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
def sampler(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)])
valid=(uv[:,0]>=0)&(uv[:,1]>=0)&(uv[:,0]<1199)&(uv[:,1]<1199)
allowed=valid&(sample(labels,points,low,high)==1)&(veh<.20)&~shapely.contains_xy(protected,points[:,0],points[:,1])
return colors,allowed
return sampler,name
linear=[f for f in old['features']if f['properties'].get('subtype')=='linear_marking']
shapes={f['id']:shapely.force_2d(shape(f['geometry']))for f in linear}
proposals=[];diagnostics=[]
for f in linear:
p=shapes[f['id']]
if p.geom_type!='Polygon':continue
obs=observation(np.asarray(p.exterior.coords),'seed')
if not 1.45<obs['L']<70 or obs['W']>.4:continue
sampler,name=sampler_for(np.array(p.centroid.coords[0]));debug=dict(id=f['id'],tile=name)
fit=reconstruct_long(p,sampler,debug);diagnostics.append(debug)
if fit is not None:fit.update(source_tile=name,seed_id=f['id']);proposals.append(fit)
print('PROFILE',len(diagnostics),len(proposals),flush=True)if len(diagnostics)%50==0 else None
proposals=merge_overlapping(proposals)
removed=set();generated=[];accepted=[];domains=[]
for rec in sorted(proposals,key=lambda x:-len(x['polygons'])):
domain=rec['domain']
if any(domain.intersection(d).area/min(domain.area,d.area)>.15 for d in domains):continue
if any(p.intersection(protected).area>.005 for p in rec['polygons']):continue
source_ids=[];residual=[]
u=rec['axis'];n=np.array([-u[1],u[0]]);origin=rec['origin']+rec['offset']*n
for f in linear:
if f['id']in removed:continue
p=shapes[f['id']]
if p.geom_type!='Polygon' or p.intersection(domain).area/max(p.area,1e-9)<.04:continue
obs=observation(np.asarray(p.exterior.coords),'source')
if abs(obs['axis']@u)<np.cos(np.deg2rad(5)) or abs((obs['center']-origin)@n)>max(.14,rec['width']*.6):continue
source_ids.append(f['id'])
for part in parts(p.difference(domain)):
if part.area>.025:residual.append(feature(lift(part),'road_marking',subtype='linear_marking',method='norm-domain-residual',source_ids=[f['id']]))
if not source_ids:continue
output_ids=[]
for p in rec['polygons']:
item=feature(lift(p),'road_marking',subtype='linear_marking',line_kind='dashed',method='observed-long-dash-family-v1',source_ids=source_ids,source_tiles=rec.get('source_tiles',[rec['source_tile']]),period_m=rec['period'],dash_length_m=rec['length'],width_m=rec['width'],standard_assessment=rec['norm'],observed_stroke=True)
output_ids.append(item['id']);generated.append(item)
generated.extend(residual);removed.update(source_ids);domains.append(domain)
accepted.append({**{k:rec[k]for k in ['bounds_xy','source_tile','seed_id','period','length','width','gaps','phase_residual_m','norm']},'source_tiles':rec.get('source_tiles',[rec['source_tile']]),'source_ids':source_ids,'output_ids':output_ids,'axis':rec['axis'].tolist(),'centers':rec['centers']})
print('ACCEPT',len(accepted),rec['source_tile'],len(output_ids),rec['length'],rec['period'],flush=True)
# Crosswalks are measured and compared, never resized without rechecking evidence.
crosswalks={}
for f in old['features']:
if f['properties'].get('subtype')!='crosswalk':continue
prop=f['properties'];key=(prop.get('source_tile','unknown'),prop.get('crosswalk_family','ungrouped'))
if key[1]=='ungrouped':continue
p=shapely.force_2d(shape(f['geometry']))
if p.geom_type=='Polygon':crosswalks.setdefault(key,[]).append((f,observation(np.asarray(p.exterior.coords),'crosswalk')))
checks=[]
for key,group in crosswalks.items():
if len(group)<3:continue
obs=[o for _,o in group];u=obs[0]['axis'];n=np.array([-u[1],u[0]]);centers=np.sort([o['center']@n for o in obs]);spacing=float(np.median(np.diff(centers)));width=float(np.median([o['W']for o in obs]));length=float(np.median([o['L']for o in obs]))
checks.append(dict(source_tile=key[0],family=key[1],stripes=len(group),source_ids=[f['id']for f,_ in group],**assess_crosswalk(width,spacing,length)))
result={**old,'features':[f for f in old['features']if f['id']not in removed]+generated,'norm_refinement':'observed-long-dash-family-v1'}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'norm-rows.json').write_text(json.dumps(accepted,indent=2));(O/'norm-diagnostics.json').write_text(json.dumps(diagnostics));(O/'norm-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(removed))))
(O/'crosswalk-standard-check.json').write_text(json.dumps(dict(standard=STANDARD,sources=SOURCES,families=checks,compliance='not_assessed',geometry_changed=False),indent=2))
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),long_dash_rows=len(accepted),observed_dashes=sum(len(r['output_ids'])for r in accepted),replaced_objects=len(removed),norm_rhythm_compatible_rows=sum(r['norm']['status']=='rhythm_compatible'for r in accepted),crosswalk_families_checked=len(checks),profiled_seeds=len(diagnostics),before_linear_objects=len(linear),after_linear_objects=len(linear)-len(removed)+len(generated),manual_geometry=False,manual_rois=[],policy_version='observed-long-dash-family-v1',legal_compliance_assessed=False)
(O/'norm-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,kind='long-dashed',baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'norm-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,42 @@
import json,runpy,numpy as np
from norm_profiles import fit_runs,reconstruct_long,merge_overlapping
from interval_profiles import rectangle
from gost_catalog import assess_dash,assess_crosswalk,dimensional_tolerance
prior=runpy.run_path('/candidate/test_intervals.py')['result']
checks={'prior_'+k:v for k,v in prior['checks'].items()}
ts=np.arange(-2,45,.025);valid=np.ones(len(ts),bool)
def signal(L,P,phase=0):return np.where((ts-phase)%P<L,80.,0.)
f=fit_runs(ts,signal(3,4),valid)
checks['long_dense_dash_recovered']=f is not None and abs(f['length']-3)<.06 and abs(f['period']-4)<.05
f=fit_runs(ts,signal(3,12),valid)
checks['long_sparse_dash_recovered']=f is not None and abs(f['period']-12)<.05
checks['solid_never_cut_by_standard']=fit_runs(ts,np.full(len(ts),80.),valid)is None
v=valid.copy();s=signal(3,4);v[s<10]=False
checks['occlusion_not_asphalt_gap']=fit_runs(ts,s,v)is None
checks['blank_no_norm_hallucination']=fit_runs(ts,np.zeros(len(ts)),valid)is None
s=signal(3,4);s[(ts>14)&(ts<14.1)]=0
f=fit_runs(ts,s,valid);checks['hairline_paint_crack_not_new_dash']=f is not None and abs(f['period']-4)<.05
a=assess_dash(3.05,4.05,.16);checks['gost_dense_candidate']=a['status']=='rhythm_compatible' and a['nominal_length_m']==3 and a['compliance']=='not_assessed'
a=assess_dash(2.1,5.8,.19);checks['nonstandard_measurement_not_forced']=a['status']=='measured_nonstandard_or_uncertain' and a['observed_period_m']==5.8
c=assess_crosswalk(.43,1.07,3.8);checks['zebra_audit_no_geometry_claim']=not c['geometry_changed']and c['compliance']=='not_assessed'and abs(c['spacing_residual_m']-.07)<1e-8
checks['application_tolerance_separate']=dimensional_tolerance(.15)==.01 and dimensional_tolerance(3)==.05
def sampler(points):
t=points[:,0];n=points[:,1];paint=((t%4)<3)&(abs(n)<.075)
return np.repeat(np.where(paint,210,65)[:,None],3,axis=1).astype('uint8'),np.ones(len(points),bool)
p=rectangle(np.array([0.,0.]),np.array([1.,0.]),0,18,.15)
rec=reconstruct_long(p,sampler)
checks['metric_profile_rebuilds_long_dashes']=rec is not None and len(rec['polygons'])>=6
theta=.62;rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]]);shift=np.array([110.,-80.])
from shapely.geometry import Polygon
r=reconstruct_long(Polygon(np.asarray(p.exterior.coords)@rot.T+shift),lambda xy:sampler((xy-shift)@rot))
checks['rotation_translation_invariant']=r is not None and rec is not None and abs(r['period']-rec['period'])<.05
f=fit_runs(ts,signal(2.1,5.8),valid)
checks['nonstandard_period_stays_measured']=f is not None and abs(f['period']-5.8)<.05 and f['norm']['status']=='measured_nonstandard_or_uncertain'
left=reconstruct_long(rectangle(np.array([0.,0.]),np.array([1.,0.]),0,18,.15),sampler)
right=reconstruct_long(rectangle(np.array([0.,0.]),np.array([1.,0.]),20,38,.15),sampler)
for a in [left,right]:a.update(source_tile='synthetic')
joined=merge_overlapping([left,right])
checks['overlapping_windows_extend_same_measured_row']=len(joined)==1 and len(joined[0]['polygons'])>max(len(left['polygons']),len(right['polygons']))
checks['merged_row_preserves_period']=len(joined)==1 and abs(joined[0]['period']-4)<.05
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()})
open('/out/norm-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']