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,69 @@
Image-supported interval continuity and adjacent paint tracks
============================================================
Scope
-----
This offline Gaussian-only increment refines the immutable lines-pass-20261012
maps. It uses the existing Gaussian ground RGB, calibrated top-view transforms,
road domain and vehicle masks. Roads, pedestrian zones, facade and existing
nonlinear paint objects are preserved. No point clouds, colliders, manually
selected processing areas or per-scene parameters are used.
Method
------
interval_profiles.py rectifies a narrow strip around every eligible long paint
primitive. OpenCV transverse morphological opening estimates road background;
SciPy find_peaks and peak_widths distinguish two actual transverse paint ridges.
Longitudinal support then produces separate continuous intervals and observed
short dashes. Short rows reuse the prior robust periodic-fitting primitive. Prominent,
regular longitudinal peaks can separate strong dashes from a faint continuous
underlay of worn or superseded paint; that background is not filled as a stroke.
Only sub-stroke cracks up to 12.5 cm may close in this profile. An adjacent row
must have its own image evidence; no companion line is invented from spacing.
For these image-measured paired rows the minimum period/length ratio is 1.10;
the prior proposal-only fitter keeps its default 1.25. This allows narrow real
gaps between wide/blurred dashes while retaining a positive measured separation.
refine_intervals.py replaces affected geometry inside exact measured corridor
bounds. It does not use the former 16 cm exclusion buffer at replacement seams.
The separate interval-union pass considers nearby, straight compatible paint
pieces. A join of up to 55 cm requires actual bright paint across at least 80%
of the sampled gap. Real unpainted dash gaps and vehicle/unknown pixels cannot
supply that evidence. Each accepted join records input IDs, source tile, gap
and measured paint support. Old row reconstruction remains otherwise unchanged.
Ready components: OpenCV minAreaRect, remap, morphology and robust fitLine;
SciPy Gaussian filtering and peak measurement; Shapely geometry operations.
Application code associates evidence and replaces geometry, not a new learned
model or a per-location drawing system.
Limits
------
The pass is seeded by existing long linear paint. It does not guarantee all
line detection or all marking classes. Locally straight pairs are handled;
curved paint, wide/irregular separation and severely degraded Gaussian images
can remain unresolved. Existing long-dash intervals incorrectly represented as
solid can remain so: this increment does not yet perform whole-row long-dash
classification. The seven resolved pairs are local intervals, not seven fully
reconstructed marking systems. A successful structural audit does not measure absolute
geodetic accuracy or whole-map precision/recall. See visual-review.json for the
actual accepted scope, known failures and images reviewed for the frozen run.
Execution
---------
All fitting, image processing, tests and rendering run on Worker006. The Mac
orchestrates jobs, verifies hashes, copies artifacts and displays images.
Qualification: .runtime/simulation-qualifications/intervals-pass-20261012.
Canonical module: simulation/urban-plan-research/intervals_pass/bundle.json.
Stages: refine_intervals, test_intervals, audit_intervals, render_intervals,
render_plan. Existing scene cache, queue, SSH alias mission-gpu and configuration
are required; this is not a standalone public command-line package.
The source ZIP is flat; bundle.json resolves reused canonical modules.
review-font.ttf is separately hashed and retained for rendering in qualification.
Pinned image:
sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0
4 CPU, 20 GiB RAM, 1 GiB tmpfs, network none, read-only root, 1800 seconds/stage.
Reservations precede execution; temporary owned containers are removed before
release. Baseline and source hashes accompany receipts. No product-map deploy,
commit, system installation or Ops publication is part of this qualification.
@@ -0,0 +1,18 @@
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/interval-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']}
pairs=json.loads(Path('/out/interval-pairs.json').read_text());joins=json.loads(Path('/out/interval-joins.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'])
descendants=set(features)
for f in new['features']:descendants.update(f['properties'].get('source_ids',[]))
checks['output_lineage']=all(fid in descendants for p in pairs for fid in p['output_ids'])and all(r['output_id']in descendants for r in joins)
checks['joins_have_paint_evidence']=all(r['paint_support']>=.8 and r['gap_m']<=.55 for r in joins)
checks['paired_ridges_are_separate']=all(len(r['tracks'])==2 and abs(r['tracks'][0]['offset']-r['tracks'][1]['offset'])>=.14 for r in pairs)
checks['same_policy']=new['interval_refinement']=='image-supported-intervals-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/interval-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,38 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_intervals.py": "intervals_pass/audit_intervals.py",
"fit_scene.py": "full_plan/fit_scene.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",
"refine_intervals.py": "intervals_pass/refine_intervals.py",
"render_intervals.py": "intervals_pass/render_intervals.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"
},
"reference_qualification": "intervals-pass-20261012",
"source_snapshot": "7a40dc4bcc79862506ac",
"source_sha256": {
"audit_intervals.py": "6a7b82bdf1ae675faf2bc240de6cff7b9086ea2abf18de6d11d61dbb62a3664a",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"interval_profiles.py": "6e7dc0e0eb2cc7ed641bd786b283688ecbc831a2b3442f3f6e6c18add0bad345",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "f89883a1140aca2b78e1567e3361aa69403725d9b384daca6f782951b8920738",
"refine_intervals.py": "69b85c6de481ad124d3a73556df4e66a57fbdd9a00c7d97a35485877c6fec4b1",
"render_intervals.py": "aa28db4f05699523c968e882c0cb19f88202d76fce34308a6a2c336c16de7200",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"test_intervals.py": "0fd926c0739f066bf79d549e190b8641399eea39486726e5946d67388ab73a12",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a"
},
"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,151 @@
"""Resolve adjacent paint ridges and join only image-supported line seams."""
import numpy as np
import cv2
from scipy.signal import find_peaks, peak_widths
from scipy.ndimage import gaussian_filter1d
from shapely.geometry import Polygon
from line_reconstruction import observation, reconstruct
def rectangle(o, u, lo, hi, width, offset=0):
n = np.array([-u[1], u[0]])
return Polygon(o + np.array([[lo, offset-width/2], [hi, offset-width/2],
[hi, offset+width/2], [lo, offset+width/2]]) @ np.stack([u, n]))
def runs(mask):
edges = np.flatnonzero(np.diff(np.r_[False, mask, False].astype('int8')))
return list(zip(edges[::2], edges[1::2]))
def strip(o, u, ts, ns, sampler):
n = np.array([-u[1], u[0]])
xy = o + ts[:, None, None]*u + ns[None, :, None]*n
rgb, allowed = sampler(xy.reshape(-1, 2))
gray = cv2.cvtColor(rgb.reshape(len(ts), len(ns), 3).astype('uint8'), cv2.COLOR_RGB2GRAY).astype('float32')
allowed = allowed.reshape(len(ts), len(ns))
# Opening only across the strip estimates the local road background.
background = cv2.morphologyEx(gray, cv2.MORPH_OPEN, np.ones((1, 35), np.uint8))
contrast = gaussian_filter1d(np.maximum(gray-background, 0), .8, axis=1)
return contrast, allowed
def resolve_pair(poly, sampler, debug=None):
"""Two distinct transverse peaks are required; no invented companion row."""
obs = observation(np.asarray(poly.exterior.coords), 'seed')
if obs['L'] < 3 or obs['L'] > 65:
return None
o, u = obs['center'], obs['axis'].astype(float)
u /= np.linalg.norm(u)
step = .025
ts = np.arange(-obs['L']/2-.45, obs['L']/2+.45, step)
ns = np.arange(-.75, .751, .025)
contrast, allowed = strip(o, u, ts, ns, sampler)
central = abs(ts) < obs['L']/2
profile = np.quantile(np.where(allowed[central], contrast[central], 0), .80, axis=0)
peaks, props = find_peaks(profile, height=18, prominence=12, distance=6)
widths = peak_widths(profile, peaks, rel_height=.5)
if debug is not None:debug.update(offsets=ns.tolist(),profile=profile.tolist(),peaks=peaks.tolist(),length=obs['L'],tracks=[])
tracks = []
for pi, k in enumerate(peaks):
if abs(ns[k]) > .53 or not .06 < widths[0][pi]*step < .32:
continue
band = abs(ns-ns[k]) <= .05
signal = gaussian_filter1d(np.quantile(contrast[:, band], .65, axis=1), 1)
valid = allowed[:, band].mean(axis=1) > .8
cut = max(15., min(25., float(np.quantile(signal[central], .85))*.35))
paint = (signal > cut) & valid
# Only sub-stroke cracks; ordinary dash gaps are wider and stay open.
for a, b in runs(~paint):
if a > 0 and b < len(paint) and (b-a)*step <= .125 and valid[a:b].all():
paint[a:b] = True
intervals = [(ts[a]-step/2, ts[b-1]+step/2) for a, b in runs(paint) if (b-a)*step >= .26]
# Worn or superseded paint may leave a faint continuous underlay beneath
# clear short dashes. A regular sequence of prominent peaks identifies
# the current dash pattern without lowering the threshold into that floor.
regular_short = None
peak_signal=np.where(valid, signal, 0)
pk, pr = find_peaks(peak_signal, prominence=15, distance=int(.45/step))
pw = peak_widths(peak_signal, pk, rel_height=.5)
peak_intervals=[(ts[0]+pw[2][j]*step, ts[0]+pw[3][j]*step) for j in range(len(pk)) if .26<pw[0][j]*step<1.4]
n = np.array([-u[1],u[0]])
if len(peak_intervals)>=4:
peak_obs=[dict(center=o+(a+b)/2*u+ns[k]*n,axis=u,L=b-a,W=.12,source_tile='profile') for a,b in peak_intervals]
period_fit=reconstruct(dict(records=peak_obs,axis=u,origin=o+ns[k]*n,points=np.array([x['center']for x in peak_obs]),parallel=False),minimum_period_to_length=1.10)
if period_fit is not None and period_fit['kind']=='dashed':
regular_short=peak_intervals
lo,hi=peak_intervals[0][0],peak_intervals[-1][1]
outer=[(a,min(b,lo))for a,b in intervals if a<lo-.26]+[(max(a,hi),b)for a,b in intervals if b>hi+.26]
intervals=sorted(outer+peak_intervals)
if debug is not None:debug['tracks'].append(dict(offset=float(ns[k]),ts=ts[::2].tolist(),signal=signal[::2].tolist(),intervals=intervals,cut=cut))
if not intervals:
continue
lengths = np.array([b-a for a, b in intervals])
if max(lengths) < 2.7 and not (len(lengths) >= 4 and np.median(lengths) < 1.5):
continue
bright = paint & (abs(ts) < obs['L']/2)
if bright.sum() < 12 or np.median(signal[bright]) < 22:
continue
near = abs(ns-ns[k]) <= .11
w = np.where(near[None, :], np.maximum(contrast[bright] - profile[k]*.5, 0), 0).sum(0)
offset = float(w@ns / w.sum()) if w.sum() else float(ns[k])
width = float(np.clip(widths[0][pi]*step, .075, .27))
polys = []
# Regularize short runs as a family; keep long intervals separately.
short = regular_short if regular_short is not None else [(a,b) for a,b in intervals if .26 < b-a < 1.4]
n = np.array([-u[1], u[0]])
if len(short) >= 4:
observations = [dict(center=o+(a+b)/2*u+offset*n, axis=u, L=b-a,
W=width, source_tile='profile') for a,b in short]
fit = reconstruct(dict(records=observations, axis=u, origin=o+offset*n,
points=np.array([x['center'] for x in observations]), parallel=False),minimum_period_to_length=1.10)
if fit is not None and fit['kind'] == 'dashed':
# This pass does not introduce unobserved short slots.
for p in fit['polygons']:
t = (np.array(p.centroid.coords[0])-o)@u
if any(a-.1 <= t <= b+.1 for a,b in short):
polys.append((p, 'dashed'))
polys += [(rectangle(o,u,a,b,width,offset), 'solid') for a,b in intervals if b-a >= 1.4]
if not polys:
continue
tracks.append(dict(offset=offset, width=width, polygons=polys,
observed_runs=len(intervals), contrast=float(np.median(signal[bright]))))
if len(tracks) != 2 or abs(tracks[0]['offset']-tracks[1]['offset']) < .14:
return None
if not any(any(kind == 'solid' for _,kind in t['polygons']) for t in tracks):
return None
# The old seed must actually touch one of the measured tracks.
if min(abs(t['offset']) for t in tracks) > .25:
return None
domain = rectangle(o,u,ts[0],ts[-1],max(t['offset'] for t in tracks)-min(t['offset'] for t in tracks)+.45,
(max(t['offset'] for t in tracks)+min(t['offset'] for t in tracks))/2)
return dict(axis=u,origin=o,tracks=tracks,domain=domain,observed=True)
def seam_proposal(a, b, sampler):
"""A proposed union must have actual bright paint across its whole gap."""
oa, ob = [observation(np.asarray(p.exterior.coords),'seam') for p in [a,b]]
if min(oa['L'],ob['L']) < 1.4 or abs(oa['axis']@ob['axis']) < np.cos(np.deg2rad(2)):
return None
u = oa['axis'].astype(float);u /= np.linalg.norm(u);n = np.array([-u[1],u[0]])
vertices = np.concatenate([np.asarray(p.exterior.coords) for p in [a,b]])
o = oa['center'];ranges = sorted([(float(((np.asarray(p.exterior.coords)-o)@u).min()),
float(((np.asarray(p.exterior.coords)-o)@u).max())) for p in [a,b]])
left,right=ranges;gap=right[0]-left[1]
if gap < -.2 or gap > .55 or abs((ob['center']-o)@n) > .075:
return None
width = float((oa['W']*oa['L']+ob['W']*ob['L'])/(oa['L']+ob['L']))
if max(oa['W'],ob['W'])/max(min(oa['W'],ob['W']),1e-5)>1.8 or width>.35:
return None
# Include adjoining paint so a faint seam is judged against the same image.
ts=np.arange(left[1]-.2,right[0]+.21,.025);ns=np.arange(-.75,.751,.025)
contrast,allowed=strip(o,u,ts,ns,sampler);band=abs(ns)<max(.035,min(.07,width*.3))
good=allowed[:,band].mean(1)>.8;signal=np.median(contrast[:,band],axis=1)
gaprange=(ts>=left[1]-.025)&(ts<=right[0]+.025)
if not gaprange.any():gaprange=np.ones(len(ts),bool)
supported=good & (signal>15)
if supported[gaprange].mean()<.8:
return None
center_offset=float(((ob['center']-o)@n)*ob['L']/(oa['L']+ob['L']))
p=rectangle(o,u,left[0],max(left[1],right[1]),width,center_offset)
return p,dict(gap_m=max(0.,float(gap)),paint_support=float(supported[gaprange].mean()),axis=u.tolist())
@@ -0,0 +1,160 @@
"""Image-driven thin paint observations and whole-row robust metric fitting."""
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from scipy.optimize import least_squares
def observation(p,source,kind='component'):
p=np.asarray(p,np.float32);rect=cv2.minAreaRect(p);box=cv2.boxPoints(rect);edges=np.roll(box,-1,axis=0)-box;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/max(L,1e-9)
if u[0]<0:u=-u
return dict(center=np.array(rect[0]),axis=u,L=L,W=W,source_tile=source,kind=kind,polygon=Polygon(box))
def extract(rgb,allowed,xy,source,mpp):
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.6/mpp)//2*2+1,)*2)
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel)
white=(hsv[:,:,1]<100)&(gray>100);yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>50)&(gray>100)
binary=((ridge>12)&(white|yellow)&allowed).astype('uint8')
binary=cv2.morphologyEx(binary,cv2.MORPH_CLOSE,np.ones((3,3),np.uint8))
cc,_=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);records=[]
for c in cc:
if cv2.contourArea(c)*mpp*mpp<.02:continue
o=observation(xy(c[:,0]),source);L,W=o['L'],o['W'];area=cv2.contourArea(c)*mpp*mpp
if .26<L<65 and .045<W<.45 and L/W>2.0 and area/(L*W)>.48:records.append(o)
# Connected stop lines/crossing remnants must not erase long thin strips.
lines=cv2.HoughLinesP(binary,1,np.pi/720,threshold=max(25,int(1.5/mpp)),minLineLength=2.8/mpp,maxLineGap=.10/mpp)
if lines is not None:
for x1,y1,x2,y2 in lines[:,0]:
a=np.array([x1,y1],float);b=np.array([x2,y2],float);u=b-a;L=np.linalg.norm(u);u/=L;n=np.array([-u[1],u[0]])
ts=np.arange(0,L, max(1,.1/mpp));ns=np.arange(-.22/mpp,.22/mpp+1);uv=a+ts[:,None,None]*u+ns[None,:,None]*n
val=cv2.remap(binary,uv[:,:,0].astype('float32'),uv[:,:,1].astype('float32'),cv2.INTER_NEAREST);cnt=val.sum(1)
good=(cnt>=.04/mpp)&(cnt<=.30/mpp)
if np.mean(good)<.80:continue
gaps=np.flatnonzero(np.diff(np.r_[False,~good,False].astype('int8')))
if len(gaps) and max(gaps[1::2]-gaps[::2])*.1>.25:continue
offsets=np.divide(val@ns,cnt,out=np.zeros(len(cnt)),where=cnt>0);points=a+ts[good,None]*u+offsets[good,None]*n
fit=cv2.fitLine(points.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();u=fit[:2];origin=fit[2:];n=np.array([-u[1],u[0]])
if np.quantile(abs((points-origin)@n),.90)*mpp>.045:continue
width=float(np.median(cnt[good])*mpp);t=(points-origin)@u;box=origin+np.array([[t.min(),-width/(2*mpp)],[t.max(),-width/(2*mpp)],[t.max(),width/(2*mpp)],[t.min(),width/(2*mpp)]])@np.stack([u,n]);o=observation(xy(box),source,'hough-ridge')
if o['L']>2.7:records.append(o)
return records,dict(raw_components=len(cc),linear_observations=len(records))
def dedup(records):
result=[]
for o in sorted(records,key=lambda o:-(o['L']*o['W'])):
if any(o['polygon'].intersection(r['polygon']).area/min(o['polygon'].area,r['polygon'].area)>.48 for r in result):continue
result.append(o)
return result
def rows(records):
parent=list(range(len(records)))
def root(i):
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
return i
for i,a in enumerate(records):
for j,b in enumerate(records[:i]):
d=b['center']-a['center'];u=a['axis'];n=np.array([-u[1],u[0]]);v=b['axis'];m=np.array([-v[1],v[0]])
if abs(u@v)<np.cos(np.deg2rad(15 if max(a['L'],b['L'])<1.5 else 8)):continue
# Short dash orientation is noisy. Both center-to-axis tests constrain rows.
if min(abs(d@n),abs(d@m))>.14 or max(abs(d@n),abs(d@m))>.65:continue
gap=abs(d@u)-(a['L']+b['L'])/2
if gap>9 or abs(d@u)>60:continue
parent[root(i)]=root(j)
groups={}
for i in range(len(records)):groups.setdefault(root(i),[]).append(records[i])
result=[]
for group in groups.values():
pts=np.concatenate([r['center']+np.linspace(-r['L']/2,r['L']/2,max(2,int(r['L']/.4)))[:,None]*r['axis']for r in group]);f=cv2.fitLine(pts.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=f[:2];o=f[2:];n=np.array([-u[1],u[0]])
if u[0]<0:u=-u;n=-n
residual=abs((pts-o)@n)
if np.quantile(residual,.95)>.14 or residual.max()>.30:
# Reject incompatible chain: retain longer independent supported observations.
for r in group:
if r['L']>3:result.append(dict(records=[r],axis=r['axis'],origin=r['center'],points=np.array([r['center']-r['L']/2*r['axis'],r['center']+r['L']/2*r['axis']]),parallel=False))
continue
result.append(dict(records=group,axis=u,origin=o,points=pts,parallel=False))
# RANSAC-style consensus on component centers supplies entire short-dash
# rows even when each small blurred rectangle has an unreliable orientation.
# The fitting primitive is OpenCV Huber; period/length consistency remains
# mandatory, so random bright components cannot form an admitted row.
from scipy.spatial import cKDTree
short=[r for r in records if .26<r['L']<1.5]
if len(short)>=3:
centers=np.array([r['center']for r in short]);axes=np.array([r['axis']for r in short]);hypotheses=[];seen=set()
for i,j in sorted(cKDTree(centers).query_pairs(3.5)):
u=centers[j]-centers[i];distance=np.linalg.norm(u)
if distance<.5:continue
u/=distance
if min(abs(axes[i]@u),abs(axes[j]@u))<np.cos(np.deg2rad(25)):continue
n=np.array([-u[1],u[0]]);delta=centers-centers[i];ids=np.flatnonzero((abs(delta@n)<.12)&(abs(delta@u)<25)&(abs(axes@u)>np.cos(np.deg2rad(25))))
ids=ids[np.argsort((centers[ids]-centers[i])@u)]
chunks=np.split(ids,np.flatnonzero(np.diff((centers[ids]-centers[i])@u)>3.5)+1)
for ids in chunks:
identity=tuple(sorted(ids.tolist()))
if len(ids)<3 or identity in seen:continue
seen.add(identity);pts=centers[ids];f=cv2.fitLine(pts.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();uu=f[:2];oo=f[2:]
if uu[0]<0:uu=-uu
rr=dict(records=[short[k]for k in ids],axis=uu,origin=oo,points=pts,parallel=False)
fit=reconstruct(rr)
if fit is None or fit['kind']!='dashed':continue
hypotheses.append((len(ids),identity,rr))
taken=set();consensus=[]
for _,ids,rr in sorted(hypotheses,key=lambda item:-item[0]):
if len(taken.intersection(ids))>1:continue
taken.update(ids);consensus.append(rr)
if consensus:
claimed={id(short[k])for k in taken}
result=[rr for rr in result if not all(id(r)in claimed for r in rr['records'])]+consensus
# Shared direction for supported neighboring straight rows. Never require equal
# phase or equal spacing across distinct rows; curved evidence can veto it.
for i,a in enumerate(result):
if len(a['records'])<3:continue
neighbors=[a]
for b in result[i+1:]:
if len(b['records'])<3 or abs(a['axis']@b['axis'])<np.cos(np.deg2rad(3)):continue
n=np.array([-a['axis'][1],a['axis'][0]]);delta=b['origin']-a['origin']
if not .6<abs(delta@n)<15:continue
ta=(a['points']-a['origin'])@a['axis'];tb=(b['points']-a['origin'])@a['axis'];overlap=min(ta.max(),tb.max())-max(ta.min(),tb.min())
if overlap<.6*min(np.ptp(ta),np.ptp(tb)):continue
neighbors.append(b)
if len(neighbors)<2:continue
pts=np.concatenate([r['points']-np.mean(r['points'],axis=0)for r in neighbors]);_,_,vt=np.linalg.svd(pts,full_matrices=False);u=vt[0];u*=1 if u[0]>=0 else -1;n=np.array([-u[1],u[0]])
if any(np.max(abs((r['points']-np.mean(r['points'],axis=0))@n))>.14 for r in neighbors):continue
for r in neighbors:r.update(axis=u,origin=np.mean(r['points'],axis=0),parallel=True)
# Partition a shared axis at changes between continuous and dashed paint.
# Collinear solid approaches and short junction dashes must not invalidate
# one another's length/period estimate.
partitioned=[]
for row in result:
u=row['axis'];o=row['origin'];ordered=sorted(row['records'],key=lambda r:(r['center']-o)@u);lens=np.array([r['L']for r in ordered]);values=np.sort(lens)
ratio=values[1:]/np.maximum(values[:-1],1e-6)
cut=np.sqrt(values[np.argmax(ratio)]*values[np.argmax(ratio)+1])if len(ratio)and ratio.max()>2.2 else None
chunks=[]
for r in ordered:
cls=r['L']>cut if cut else False
if not chunks or chunks[-1][0]!=cls:chunks.append((cls,[r]))
else:chunks[-1][1].append(r)
for _,chunk in chunks:
q={**row,'records':chunk};partitioned.append(q)
return partitioned
def reconstruct(row,minimum_period_to_length=1.25):
u=row['axis'];o=row['origin'];n=np.array([-u[1],u[0]]);rs=row['records'];ranges=sorted([[(r['center']-o)@u-r['L']/2,(r['center']-o)@u+r['L']/2]for r in rs]);merged=[]
for a,b in ranges:
if merged and a<=merged[-1][1]+.11:merged[-1][1]=max(b,merged[-1][1])
else:merged.append([a,b])
lens=np.diff(merged,axis=1).ravel();centers=np.mean(merged,axis=1);width=float(np.clip(np.median([r['W']for r in rs]),.07,.24));filled=0;period=None
if len(merged)==1 and lens[0]>2.7:intervals=merged;kind='solid'
elif len(merged)>=3 and np.median(abs(lens-np.median(lens)))/np.median(lens)<.22:
steps=np.diff(centers);P=float(np.median(steps[steps<np.quantile(steps,.60)+.01]));L=float(np.median(lens));slots=np.rint((centers-centers[0])/P).astype(int)
if P<L*minimum_period_to_length or P>15 or np.max(np.diff(slots))>3 or len(np.unique(slots))!=len(slots):return None
fit=least_squares(lambda x:(x[0]+slots*x[1])-centers,[centers[0],P],loss='soft_l1',f_scale=.06,bounds=([-np.inf,.85*P],[np.inf,1.15*P]))
phase,P=fit.x;err=abs(phase+slots*P-centers)
if err.max()>min(.20,.17*P):return None
# Only observed range; image discovery supplies previously missing exterior
# dashes, not blind extrapolation from this periodic model.
allslots=np.arange(slots.min(),slots.max()+1);intervals=[[phase+t*P-L/2,phase+t*P+L/2]for t in allslots];filled=len(allslots)-len(slots);kind='dashed';period=float(P)
elif len(merged)>=2 and max(b[0]-a[1]for a,b in zip(merged,merged[1:]))<.55 and sum(lens)>4:
intervals=[[merged[0][0],merged[-1][1]]];kind='solid-interpolated'
else:return None
polys=[Polygon(o+np.array([[a,-width/2],[b,-width/2],[b,width/2],[a,width/2],[a,-width/2]])@np.stack([u,n]))for a,b in intervals]
return dict(polygons=polys,kind=kind,axis=u.tolist(),origin=o.tolist(),width_m=width,period_m=period,filled_internal_slots=int(filled),input_observations=len(rs),output_objects=len(polys),shared_parallel_direction=row['parallel'],source_tiles=sorted(set(r['source_tile']for r in rs)))
@@ -0,0 +1,110 @@
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 interval_profiles import resolve_pair,seam_proposal
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}
seeds=[]
for f in linear:
p=shapes[f['id']]
if p.geom_type!='Polygon':continue
obs=observation(np.asarray(p.exterior.coords),'seed')
if obs['L']>3 and obs['W']<.5:seeds.append((obs['L'],f,p))
domains=[];generated=[];removed=set();pairs=[];diagnostics=[]
for _,f,p in sorted(seeds,key=lambda x:-x[0]):
if any(p.intersection(d).area/max(p.area,1e-8)>.5 for d in domains):continue
sampler,name=sampler_for(np.array(p.centroid.coords[0]));debug=dict(id=f['id'],bounds=p.bounds,tile=name);rec=resolve_pair(p,sampler,debug);diagnostics.append(debug)
if rec is None:continue
domain=rec['domain'];polygons=[(q,k,t)for t in rec['tracks']for q,k in t['polygons']]
if any(q.intersection(protected).area>.005 for q,_,_ in polygons):continue
sources=[];residuals=[]
for prior in linear:
if prior['id']in removed:continue
q=shapes[prior['id']];hit=q.intersection(domain).area
if hit/max(q.area,1e-8)<.10:continue
sources.append(prior['id'])
# Exact domain cut, without the 16 cm exclusion buffer that caused seams.
for part in parts(q.difference(domain)):
if part.area>.025:residuals.append(feature(lift(part),'road_marking',subtype='linear_marking',method='interval-domain-residual',source_ids=[prior['id']]))
if not sources:continue
ids=[]
for q,kind,t in polygons:
item=feature(lift(q),'road_marking',subtype='linear_marking',method='transverse-paint-pair-v1',line_kind=kind,source_ids=sources,source_tiles=[name],profile_observed=True,template_width_m=t['width']);generated.append(item);ids.append(item['id'])
generated.extend(residuals);removed.update(sources);domains.append(domain)
pairs.append(dict(bounds_xy=domain.bounds,axis=rec['axis'].tolist(),source_tile=name,source_ids=sources,output_ids=ids,tracks=[{k:v for k,v in t.items()if k!='polygons'}for t in rec['tracks']]))
print('PAIR',len(pairs),name,len(sources),len(ids),flush=True)
(O/'pair-diagnostics.json').write_text(json.dumps(diagnostics))
current=[f for f in linear if f['id']not in removed]+generated
# Greedy union is bounded by measured geometric and photometric support. Every
# accepted bridge is retained in the report; no map-specific seed or ROI exists.
joins=[];changed=True;considered=set();shape_cache={}
def planar(f):
if f['id'] not in shape_cache:shape_cache[f['id']]=shapely.force_2d(shape(f['geometry']))
return shape_cache[f['id']]
while changed:
changed=False
for i,a in enumerate(current):
if a['properties'].get('line_kind')=='dashed':continue
pa=planar(a)
if pa.geom_type!='Polygon':continue
for j in range(i):
b=current[j]
key=tuple(sorted([a['id'],b['id']]))
if key in considered:continue
considered.add(key)
if b['properties'].get('line_kind')=='dashed':continue
pb=planar(b)
if pb.geom_type!='Polygon' or pa.distance(pb)>.56:continue
center=(np.array(pa.centroid.coords[0])+np.array(pb.centroid.coords[0]))/2
sampler,name=sampler_for(center);proposal=seam_proposal(pa,pb,sampler)
if proposal is None:continue
q,evidence=proposal
if q.intersection(protected).area>.005:continue
source_ids=sorted(set(a['properties'].get('source_ids',[])+b['properties'].get('source_ids',[])+[a['id'],b['id']]))
item=feature(lift(q),'road_marking',subtype='linear_marking',method='image-supported-interval-union-v1',line_kind='solid',source_ids=source_ids,source_tiles=[name],paint_support=evidence['paint_support'])
joins.append(dict(bounds_xy=q.bounds,source_ids=[a['id'],b['id']],output_id=item['id'],source_tile=name,**evidence))
current=[f for k,f in enumerate(current)if k not in [i,j]]+[item]
changed=True;break
if changed:break
if len(joins)>1000:raise RuntimeError('Unexpected interval union growth')
ids={f['id']for f in current};replaced=[f['id']for f in linear if f['id']not in ids]
result={**old,'features':[f for f in old['features']if f['properties'].get('subtype')!='linear_marking']+current,'interval_refinement':'image-supported-intervals-v1'}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'interval-pairs.json').write_text(json.dumps(pairs,indent=2));(O/'interval-joins.json').write_text(json.dumps(joins,indent=2))
(O/'interval-replacements.json').write_text(json.dumps(dict(removed_ids=replaced),indent=2))
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-started,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),paired_corridors=len(pairs),image_supported_joins=len(joins),before_linear_objects=len(linear),after_linear_objects=len(current),replaced_objects=len(replaced),manual_geometry=False,manual_rois=[],policy_version='image-supported-intervals-v1')
(O/'interval-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='paired',baseline_objects=len(r['source_ids']),output_objects=len(r['output_ids']))for r in json.loads((O/'interval-pairs.json').read_text())]+[dict(**r,kind='joined',baseline_objects=2,output_objects=1)for r in json.loads((O/'interval-joins.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,51 @@
import json,numpy as np,cv2
from shapely.geometry import Polygon
from interval_profiles import rectangle,resolve_pair,seam_proposal
import runpy
prior=runpy.run_path('/candidate/test_lines.py')['result']
checks={'prior_'+k:v for k,v in prior['checks'].items()};u=np.array([1.,0.]);o=np.array([0.,0.]);mpp=.01
rgb=np.full((300,1600,3),65,np.uint8)
cv2.rectangle(rgb,(30,130),(1500,144),(215,215,215),-1)
for x in range(40,1470,100):cv2.rectangle(rgb,(x,158),(x+45,171),(215,215,215),-1)
def sampler(points):
uv=(points/mpp+np.array([0,150])).astype('float32');colors=np.concatenate([cv2.remap(rgb,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).reshape(-1,3)for q in np.array_split(uv,max(1,int(np.ceil(len(uv)/20000))))])
allowed=(uv[:,0]>=0)&(uv[:,0]<rgb.shape[1])&(uv[:,1]>=0)&(uv[:,1]<rgb.shape[0]);return colors,allowed
seed=rectangle(o,u,.4,14.5,.23,-.03)
pair=resolve_pair(seed,sampler)
checks['adjacent_solid_and_dash_resolved']=pair is not None and len(pair['tracks'])==2 and sum(k=='dashed'for t in pair['tracks']for _,k in t['polygons'])>=12
if pair:
solid=[p for t in pair['tracks']for p,k in t['polygons']if k=='solid'];dash=[p for t in pair['tracks']for p,k in t['polygons']if k=='dashed']
checks['adjacent_tracks_do_not_overlap']=all(a.intersection(b).area<1e-8 for a in solid for b in dash)
checks['dash_gaps_remain_open']=len(dash)>1 and min(a.distance(b)for i,a in enumerate(dash)for b in dash[:i])>.2
a=rectangle(o,u,.4,6.,.14,-.13);b=rectangle(o,u,6.32,14.5,.14,-.13)
joined=seam_proposal(a,b,sampler)
checks['painted_seam_is_joined']=joined is not None and joined[1]['paint_support']>.8
blank=lambda p:(np.full((len(p),3),65,np.uint8),np.ones(len(p),bool))
checks['unpainted_seam_not_joined']=seam_proposal(a,b,blank)is None
checks['no_parallel_track_hallucination']=resolve_pair(seed,blank)is None
def occluded(points):
colors,valid=sampler(points);valid&=~((points[:,0]>6)&(points[:,0]<6.32));return colors,valid
checks['occluded_gap_not_claimed_as_observed']=seam_proposal(a,b,occluded)is None
checks['different_parallel_lanes_not_joined']=seam_proposal(a,rectangle(o,u,6.32,14.5,.14,.17),sampler)is None
checks['long_unobserved_gap_not_joined']=seam_proposal(a,rectangle(o,u,7.,14.5,.14,-.13),sampler)is None
rot=np.array([[np.cos(.62),-np.sin(.62)],[np.sin(.62),np.cos(.62)]]);shift=np.array([100.,-70.]);transform=lambda p:Polygon(np.asarray(p.exterior.coords)@rot.T+shift)
trans_sampler=lambda p:sampler((p-shift)@rot)
rotpair=resolve_pair(transform(seed),trans_sampler);rotjoin=seam_proposal(transform(a),transform(b),trans_sampler)
checks['rigid_transform_invariance']=rotpair is not None and rotjoin is not None and abs(rotjoin[0].area-joined[0].area)<.01
# Faint old paint must not turn the stronger regular short dashes into solid.
saved=rgb.copy();rgb[158:172,30:1500]=120
for x in range(40,1470,100):cv2.rectangle(rgb,(x,158),(x+45,171),(215,215,215),-1)
ghost_pair=resolve_pair(seed,sampler)
checks['regular_dashes_survive_faint_continuous_underlay']=ghost_pair is not None and sum(k=='dashed'for t in ghost_pair['tracks']for _,k in t['polygons'])>=12
rgb[:]=saved
rgb[158:172,:]=65
for x in range(40,1440,120):cv2.rectangle(rgb,(x,158),(x+100,171),(215,215,215),-1)
dense=resolve_pair(seed,sampler)
checks['observed_short_gaps_between_wide_dashes_preserved']=dense is not None and sum(k=='dashed'for t in dense['tracks']for _,k in t['polygons'])>=10
rgb[:]=saved
# Ordinary long dashes with an actual dark separation must never become solid.
rgb[:,620:653]=65
checks['real_gap_preserved']=seam_proposal(a,b,sampler)is None
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()})
open('/out/interval-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']