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,107 @@
Gaussian-only crosswalk and short-dash families
=============================================
Status
------
Research increment families-pass-20261012, source 482ae9e8118b3145a6c2.
Same code and metric policy on Maroseyka, Pokrovka and Smolensk. No manual
geometry, processing ROIs, scene-specific thresholds or point-cloud inputs.
This is downstream paint reconstruction over the accepted continuation-pass
candidate. It is not a complete new end-to-end run or production deployment.
Inputs and outputs
------------------
/fullplan/full-map.json is the immutable continuation-pass baseline, not the
older full-plan map. /evidence_plan contains cached semantic fields and depth;
/ortho, /survey and /input supply native detailed Gaussian ground RGB, vehicle
masks and calibrated transforms. Upstream semantic models are not rerun.
/out/full-map.json preserves all untouched features, including roads,
pedestrian polygons, facades and symbol templates. Reports distinguish image
observations, retained seed observations and inferred internal dash slots.
Crosswalk replacement removes the previous stripe objects as a group, so old
and new rectangles are not stacked on top of one another.
Method
------
1. Group seeded crossing stripes by direction, relative size and proximity.
Fit shared orientation and robust linear end envelopes using SciPy
least_squares. Adapt the existing recover_stripes brightness-profile idea
from parametric-fit-20261010/fit_scene.py to the current whole-map output.
2. Sample Gaussian RGB at 0.025 m transverse spacing over the middle 60 percent
of stripe length with OpenCV remap. Mask vehicles. Within confirmed crossing
extent, a semantic road-mask hole does not erase image paint evidence.
Unknown samples may interpolate the analysis signal but never count as a
new observation.
3. SciPy find_peaks and peak_widths recover observed stripes. Locate centers
between both half-prominence edges rather than at the brightest pixel.
Use white/yellow color profiles where both colors have repeated support.
Limit exterior search to 2 m and require observed, compatible evidence.
Weak peaks are suppressed; unseen periodic slots do not generate crosswalks.
4. Fit shared rectangular stripe geometry, retaining parent IDs and marking
seed centers without fresh image matches. Width is a shared median bounded
to avoid overlaps. Shared ends and width are still approximate, not measured
independently for each stripe.
5. For short dashed lines, reuse robust OpenCV Huber fitting. Require at least
three observed intervals, consistent lengths, period and phase. Only fill
internal slots within the observed range; veto crosswalk overlap and
incompatible road domain. Repeated dashes never become a solid line.
Results
-------
Maroseyka: 16 crossing families, 111 -> 120 stripes, 1 internal dash added.
Pokrovka: 19 crossing families, 136 -> 144 stripes, 2 internal dashes added.
Smolensk: 2 crossing families, 18 -> 19 stripes, no dash added.
Total: 37 crossing families, 18 additional stripe objects, 3 inferred dash slots.
Numbers describe output objects, not measured recall or accuracy.
All 11 controlled checks passed, including rotation/translation invariance,
vehicle exclusion, missing observations, color alternation, center stability,
nonoverlap and dash/crosswalk exclusion. Real-scene audit checks untouched
features, valid XYZ, provenance, observed recovery centers and nonoverlap.
All 37 crossing comparisons and 8 dash-family comparisons were visually read.
Known limitations and next work
------------------------------
Seeded families are required: completely undetected crossings are not found.
Some inferred shared ends remain too long or short; some widths are visibly
narrower than paint. Maroseyka crossing 15 still misses exterior stripes.
Smolensk's white/yellow family remains incomplete and retains uncertain seed
centers. New observed centers are not equivalent to verified entire polygons.
No independent metric ground truth or blind new-scene qualification is claimed.
Curbs, pedestrian silhouettes, facades and symbols are unchanged by this pass;
their previously recorded gaps and offsets remain. Next tests should improve
shared-end/width estimation and crossing discovery, then the planned joint
road/pedestrian boundary reconstruction. Review IDs are diagnostics only and
must not enter geometry settings or scene-specific exception tables.
Reproduction and ownership
--------------------------
Canonical source: simulation/urban-plan-research/families_pass/bundle.json.
Resolve each files entry relative to simulation/urban-plan-research and stage
as a flat directory, checking the SHA-256 entries. The output source ZIP is
already flat. It has ten Python files, README and bundle manifest.
review-font.ttf is a rendering-only external font, not bundled in the source
ZIP. The exact qualified copy and SHA are retained in qualification source and
source-sha256.json; computation and audit do not depend on this font.
Qualification: .runtime/simulation-qualifications/families-pass-20261012/operator.
Worker: C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/families-pass-20261012.
The replay folder preserves runner, collector, verifier, scene registry and
source identity. This operator replay requires the existing Mission Core
checkout, queue API, SSH alias mission-gpu, pinned baseline maps, private survey
caches, config-v8.json and workspace layout. It is not a standalone public CLI.
Runner stages: refine_paint, test_families, audit_families, render_families,
render_plan. Set URBAN_SOURCE_BUNDLE to the immutable qualified flat directory.
Run refine before audit/render and collect after completion. Accepted baseline
SHA comes from urban-plan-refinement-20261012/verification.json.
All numerical work, tests and rendering run on Worker006. Local operations
only orchestrate, verify hashes, copy artifacts and review images.
Pinned worker image:
sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0
Bounded stage: 4 CPU, 20 GiB RAM, read-only root, network none, 1 GiB tmpfs,
1800 s timeout. Queue reservation precedes execution; cleanup removes only the
owned ndc-families container and releases ownership after confirmation.
No runtime installation, live-map publication, source commit or Ops write.
@@ -0,0 +1,18 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
O=Path('/out');old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());report=json.loads((O/'crosswalk-families.json').read_text());accepted=[r for r in report if r['accepted']]
changed={i for r in accepted for i in r['source_ids']};newstripes=[f for f in new['features']if f['properties'].get('method')=='observed-profile-crosswalk-family'];newids={f['id']for f in newstripes}
lines=json.loads((O/'line-families.json').read_text());lineparents={i for r in lines for i in r['source_ids']};changed|=lineparents
newids|={f['id']for f in new['features']if f['properties'].get('method')=='periodic-dash-family'and set(f['properties'].get('source_ids',[]))<=lineparents}
checks=dict(untouched_features_preserved={f['id']:f for f in old['features']if f['id']not in changed}=={f['id']:f for f in new['features']if f['id']not in newids},unique_feature_ids=len(new['features'])==len({f['id']for f in new['features']}),finite_valid_3d=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features']))
geometries=[shapely.force_2d(shape(f['geometry']))for f in new['features']if f['properties'].get('subtype')=='crosswalk'];bad=[]
for i,a in enumerate(geometries):
for j,b in enumerate(geometries[:i]):
if a.intersection(b).area>.02:bad.append([i,j,float(a.intersection(b).area)])
checks['crosswalks_do_not_overlap']=not bad
checks['recovered_centers_have_image_evidence']=all(f['properties']['observed_center']for f in newstripes if f['properties']['recovered_stripe'])
checks['parent_provenance_complete']=set(x for f in newstripes for x in f['properties']['source_ids'])|lineparents==changed
checks['all_accepted_groups_materialized']=set(f['properties']['crosswalk_family']for f in newstripes)==set(r['group']for r in accepted)
result=dict(passed=all(checks.values()),checks=checks,crossing_count=len(accepted),overlaps=bad,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),full_map_sha256=hashlib.sha256((O/'full-map.json').read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_detection_measured=False)
(O/'family-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,36 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_families.py": "families_pass/audit_families.py",
"crossing_completion.py": "families_pass/crossing_completion.py",
"crosswalk_family.py": "full_plan/crosswalk_family.py",
"fit_scene.py": "full_plan/fit_scene.py",
"layer_common.py": "full_plan/layer_common.py",
"line_family_completion.py": "families_pass/line_family_completion.py",
"refine_paint.py": "families_pass/refine_paint.py",
"render_families.py": "families_pass/render_families.py",
"render_plan.py": "continuation_pass/render_plan.py",
"test_families.py": "families_pass/test_families.py"
},
"reference_qualification": "families-pass-20261012",
"source_snapshot": "482ae9e8118b3145a6c2",
"source_sha256": {
"audit_families.py": "8159b6c208c5a5d7dbb5aef720b5d0ef847032f96cc418e7c0969241999b29b4",
"crossing_completion.py": "6e75ae4b65e8d6447acae57ae17ca088a427fda39f438271bc0f1b0ca84641fb",
"crosswalk_family.py": "68ee6327a7a24ab74e77bdbbc9c504562f6997cfb7f0e6082095b3e2eb32fc2d",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_family_completion.py": "4267dc01d7442bc1c8782dd104ff3c5d8ac67f9551711b29ffe7f748424dd37c",
"refine_paint.py": "99a262cececbf23b46a0ceb17f99af13a7a1148bbbb2e0b17e656b157a359019",
"render_families.py": "772631ff02f65022e0ca800ae8cc4ebea8b57e5b953411ea86701c8f41757a2d",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"test_families.py": "d213eca861031cb105ea250c49d44bbc2630367f9d6447d1a7c5a6da6d3d50c9"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified file retained under qualification source; omitted from public source ZIP"
},
"deployment": false
}
@@ -0,0 +1,106 @@
"""Crossing-level reconstruction using the existing brightness-profile method.
SciPy peak detection supplies observed stripe centres. Robust shared ends and
widths give rectangular paint. No site coordinates or arbitrary missing slots.
"""
import numpy as np,cv2,shapely
from shapely.geometry import shape,Polygon
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks,peak_widths
from scipy.optimize import least_squares
from crosswalk_family import rectangle_info
def observations(features):
out=[]
for f in features:
if f['properties'].get('subtype')!='crosswalk':continue
p=shapely.force_2d(shape(f['geometry']))
if p.geom_type!='Polygon':continue
box,c,u,v=rectangle_info(np.asarray(p.exterior.coords));a=(box-c)@u;b=(box-c)@v;L=np.ptp(a);W=np.ptp(b)
if L>1 and .12<W<1.5 and L/W>2:out.append(dict(f=f,p=p,box=box,center=c,u=u,v=v,L=L,W=W))
return out
def groups(obs):
parent=list(range(len(obs)))
def root(i):
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
return i
for i,a in enumerate(obs):
for j,b in enumerate(obs[:i]):
delta=b['center']-a['center']
if abs(a['u']@b['u'])<np.cos(np.deg2rad(12)):continue
if abs(delta@a['u'])>max(1.2,.25*max(a['L'],b['L'])):continue
if abs(delta@a['v'])>6 or abs(a['L']-b['L'])>.55*max(a['L'],b['L']):continue
parent[root(i)]=root(j)
result={}
for i in range(len(obs)):result.setdefault(root(i),[]).append(obs[i])
return list(result.values())
def model(group):
angles=np.array([np.arctan2(o['u'][1],o['u'][0])for o in group]);theta=.5*np.arctan2(np.sin(2*angles).sum(),np.cos(2*angles).sum());u=np.array([np.cos(theta),np.sin(theta)]);v=np.array([-u[1],u[0]]);origin=np.mean([o['center']for o in group],axis=0)
centers=np.array([(o['center']-origin)@v for o in group]);lo=np.array([((o['box']-origin)@u).min()for o in group]);hi=np.array([((o['box']-origin)@u).max()for o in group])
def fit(y):
A=np.c_[np.ones(len(centers)),centers];x=np.linalg.lstsq(A,y,rcond=None)[0];x[1]=np.clip(x[1],-.35,.35)
return least_squares(lambda x:A@x-y,x,bounds=([-np.inf,-.35],[np.inf,.35]),loss='soft_l1',f_scale=.12).x
left,right=fit(lo),fit(hi);width=float(np.median([o['W']for o in group]))
return dict(origin=origin,u=u,v=v,left=left,right=right,width=width,centers=centers)
def recover(m,sampler):
"""sampler(xy) returns Gaussian RGB and vehicle/road/crosswalk support."""
step=.025;c=m['centers'];s=np.arange(c.min()-2.,c.max()+2.+step,step);left=m['left'][0]+m['left'][1]*s;right=m['right'][0]+m['right'][1]*s
t=left[:,None]+(right-left)[:,None]*np.linspace(.2,.8,48)[None,:];xy=m['origin']+t[:,:,None]*m['u']+s[:,None,None]*m['v']
rgb,veh,road,cross=sampler(xy.reshape(-1,2));rgb=rgb.reshape(len(s),48,3).astype('uint8');gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY).astype(float)
interior=(s>=c.min()-.3)&(s<=c.max()+.3)
valid=(veh.reshape(len(s),48)<.3)&((road.reshape(len(s),48)>.5)|interior[:,None]);values=np.where(valid,gray,np.nan)
count=np.sum(valid,axis=1);signal=np.divide(np.nansum(values,axis=1),count,out=np.zeros(len(s)),where=count>0)
known=count>=32
# Unknown samples must not become artificial black troughs with bright peaks
# on their sides. Interpolation is used only for signal analysis, not evidence.
signal=np.interp(s,s[known],signal[known])if known.any()else np.zeros(len(s));signal=gaussian_filter1d(signal,1.)
peaks,props=find_peaks(signal,prominence=10,distance=int(.6/step));width_info=peak_widths(signal,peaks,rel_height=.5);widths=width_info[0]*step;midpoints=s[0]+(width_info[2]+width_info[3])*.5*step
candidates=[]
for j,k in enumerate(peaks):
if not .20<=widths[j]<=.95 or count[k]<32:continue
candidates.append(dict(center=float(midpoints[j]),width=float(widths[j]),prominence=float(props['prominences'][j]),observed=True,cross_support=float(np.mean(cross.reshape(len(s),48)[k]>.2))))
# Alternating white/yellow crossings need colour evidence: luminance peaks
# alone merge adjacent colours or keep only the brighter white bands.
hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV);bright=hsv[:,:,1][(gray>100)&valid];sat=float(cv2.threshold(bright,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[0])if len(bright)else 70;sat=float(np.clip(sat,35,85));yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>sat)&(hsv[:,:,2]>100)&valid
ys=gaussian_filter1d(np.mean(yellow,axis=1),1.);yp,yprop=find_peaks(ys,prominence=.3,height=.45,distance=int(.35/step));yw=peak_widths(ys,yp,rel_height=.5)
yellows=[]
for j,k in enumerate(yp):
width=yw[0][j]*step;center=s[0]+(yw[2][j]+yw[3][j])*.5*step
if .2<=width<=.85 and count[k]>=32:yellows.append(dict(center=float(center),width=float(width),prominence=float(yprop['prominences'][j]*100),observed=True,color_evidence='yellow',cross_support=float(np.mean(cross.reshape(len(s),48)[k]>.2))))
if len(yellows)>=3:
gval=gray[valid].astype('uint8');bright_threshold=float(cv2.threshold(gval,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[0])if len(gval)else 115
white=(~yellow)&(gray>max(100,bright_threshold))&valid;ws=gaussian_filter1d(np.mean(white,axis=1),1.);wp,wprop=find_peaks(ws,prominence=.3,height=.45,distance=int(.35/step));ww=peak_widths(ws,wp,rel_height=.5);whites=[]
for j,k in enumerate(wp):
width=ww[0][j]*step;center=s[0]+(ww[2][j]+ww[3][j])*.5*step
if .2<=width<=.85 and count[k]>=32:whites.append(dict(center=float(center),width=float(width),prominence=float(wprop['prominences'][j]*100),observed=True,color_evidence='white',cross_support=float(np.mean(cross.reshape(len(s),48)[k]>.2))))
if len(whites)>=3:candidates=sorted(whites+yellows,key=lambda p:p['center'])
if candidates:
threshold=max(10,.3*np.median([p['prominence']for p in candidates]));candidates=[p for p in candidates if p['prominence']>=threshold]
inside=[p for p in candidates if c.min()-.2<=p['center']<=c.max()+.2];positions=np.array(sorted(p['center']for p in inside));deltas=np.diff(positions);deltas=deltas[(deltas>.65)&(deltas<1.7)];period=float(np.median(deltas))if len(deltas)>=2 else None
def exterior_allowed(p):
if c.min()-.2<=p['center']<=c.max()+.2:return True
if period is None:return p['cross_support']>.6
distance=float(np.min(abs(positions-p['center'])));slots=round(distance/period)
return 1<=slots<=2 and abs(distance-slots*period)<.18 and p['prominence']>max(15,.3*np.median([r['prominence']for r in inside]))
candidates=[p for p in candidates if exterior_allowed(p)]
# Align retained observations to actual peaks, deduplicating previous overlaps.
result=[];observed_width=float(np.median([p['width']for p in candidates]))if candidates else m['width'];separation=max(.25,.85*observed_width)
for seed in sorted(c):
near=min(candidates,key=lambda p:abs(p['center']-seed),default=None)
rec=near.copy()if near and abs(near['center']-seed)<.42 else dict(center=float(seed),width=m['width'],observed=False)
if any(abs(rec['center']-x['center'])<separation for x in result):continue
rec['new']=False;result.append(rec)
for rec in candidates:
if any(abs(rec['center']-x['center'])<separation for x in result):continue
rec={**rec,'new':True};result.append(rec)
result.sort(key=lambda p:p['center'])
measured=[r['width']for r in result if r['observed']];width=float(np.clip(np.median(measured)if measured else m['width'],.25,.8))
if len(result)>1:width=min(width,.95*min(np.diff([r['center']for r in result])))
for r in result:
s0=r['center'];lo=m['left'][0]+m['left'][1]*s0;hi=m['right'][0]+m['right'][1]*s0
uv=np.array([[lo,s0-width/2],[hi,s0-width/2],[hi,s0+width/2],[lo,s0+width/2],[lo,s0-width/2]])
r['polygon']=Polygon(m['origin']+uv[:,0,None]*m['u']+uv[:,1,None]*m['v'])
return result,dict(observed_peaks=len(candidates),new_stripes=sum(r['new']for r in result),input_observations=len(c),output_stripes=len(result),width_m=width,yellow_peaks=len(yellows),saturation_threshold=sat,peak_prominences=[r.get('prominence')for r in result],centers=[dict(center=r['center'],observed=r['observed'],new=r['new'],color=r.get('color_evidence','luminance'))for r in result],matched_observations=sum(r['observed']and not r['new']for r in result))
@@ -0,0 +1,60 @@
"""Complete periodic dash families, including short intersection guide dashes.
OpenCV robust line fits and median period/width estimates; no site constants.
Only bounded internal slots may be reconstructed, never a new exterior lane.
"""
import numpy as np,cv2,shapely
from shapely.geometry import shape,Polygon,LineString
from layer_common import feature
def normalize(features,lift,admit):
records=[];untouched=[]
for f in features:
g=shapely.force_2d(shape(f['geometry']))
if f['properties'].get('subtype')!='linear_marking' or g.geom_type!='Polygon':untouched.append(f);continue
rect=cv2.minAreaRect(np.asarray(g.exterior.coords,np.float32));box=cv2.boxPoints(rect);edges=np.roll(box,-1,axis=0)-box;k=np.argmax(np.linalg.norm(edges,axis=1));L=np.linalg.norm(edges[k]);W=min(rect[1]);u=edges[k]/L
if not( .25<L<12 and .06<W<.4 and L/W>2.5 and g.area/(L*W)>.68):untouched.append(f);continue
records.append(dict(f=f,g=g,center=np.array(rect[0]),axis=u,L=L,W=W))
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):
u=a['axis'];n=np.array([-u[1],u[0]])
for j,b in enumerate(records[:i]):
delta=b['center']-a['center']
if abs(u@b['axis'])<np.cos(np.deg2rad(3))or abs(delta@n)>.18:continue
gap=abs(delta@u)-(a['L']+b['L'])/2
if gap>12 or abs(delta@u)>55:continue
parent[root(i)]=root(j)
groups={}
for i in range(len(records)):groups.setdefault(root(i),[]).append(i)
output=list(untouched);audit=[]
for ids in groups.values():
originals=[records[i]['f']for i in ids]
if len(ids)<2:output.extend(originals);continue
samples=np.concatenate([records[i]['center']+np.linspace(-records[i]['L']/2,records[i]['L']/2,max(3,int(records[i]['L']/.5)))[:,None]*records[i]['axis']for i in ids])
fit=cv2.fitLine(samples.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=fit[:2];o=fit[2:];n=np.array([-u[1],u[0]])
if np.max(abs((samples-o)@n))>.24:output.extend(originals);continue
ranges=sorted([((records[i]['center']-o)@u-records[i]['L']/2,(records[i]['center']-o)@u+records[i]['L']/2)for i in ids]);merged=[]
for a,b in ranges:
if merged and a<=merged[-1][1]+.15:merged[-1][1]=max(b,merged[-1][1])
else:merged.append([a,b])
widths=[records[i]['W']for i in ids];width=float(np.median(widths));lengths=np.array([b-a for a,b in merged]);centers=np.array([(a+b)/2 for a,b in merged]);gaps=np.array([b[0]-a[1]for a,b in zip(merged[:-1],merged[1:])])
intervals=None;mode=None;added=0
if len(merged)>=3 and np.std(lengths)/np.mean(lengths)<.35:
deltas=np.diff(centers);period=float(np.median(deltas[deltas<=np.quantile(deltas,.65)]));L=float(np.median(lengths))
if period>L*1.3 and period<15:
slots=np.rint((centers-centers[0])/period).astype(int);phase=float(np.median(centers-slots*period))
residual=np.max(abs(centers-(phase+slots*period)))
if residual<min(.25,.18*period) and np.max(np.diff(slots))<=3:
targets=np.arange(slots[0],slots[-1]+1);intervals=[[phase+t*period-L/2,phase+t*period+L/2]for t in targets];mode='periodic-dash-family';added=int(len(targets)-len(slots))
if intervals is None:output.extend(originals);continue
polygons=[]
for a,b in intervals:
xy=o+np.array([[a,-width/2],[b,-width/2],[b,width/2],[a,width/2],[a,-width/2]])@np.stack([u,n]);polygons.append(Polygon(xy))
if not all(admit(p)for p in polygons):output.extend(originals);continue
ids_source=[r['id']for r in originals]
for p in polygons:output.append(feature(lift(p),'road_marking',subtype='linear_marking',method=mode,source_ids=ids_source,inferred_internal_completion=bool(added),template_width_m=width))
audit.append(dict(method=mode,input_objects=len(ids),output_objects=len(polygons),width_m=width,added_internal_m_or_slots=added,source_ids=ids_source,bounds_xy=shapely.union_all(polygons).bounds))
return output,audit
@@ -0,0 +1,44 @@
from pathlib import Path
import json,os,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
from fit_scene import project
from crossing_completion import observations,groups,model,recover
cv2.setNumThreads(3);start=time.monotonic();old=json.loads(Path('/fullplan/full-map.json').read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
with np.load('/evidence_plan/fields.npz')as z:height=z['z'];labels=z['labels'];low,high=z['bounds']
def lift(g):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),g)
changes={};added=[];reports=[]
for gi,group in enumerate(groups(observations(old['features']))):
ids=[o['f']['id']for o in group];rec=dict(group=gi,source_ids=ids,input_stripes=len(group),accepted=False)
if len(group)<3:rec['reason']='insufficient-family';reports.append(rec);continue
m=model(group);center=m['origin'];tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];rec['source_tile']=name;g=dict(np.load(S/name/'top.geometry.npz'));rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB'));factor=rgb.shape[0]/1200
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle']
with np.load(Path('/evidence_plan/evidence')/(name+'.npz'))as z:cross=z['crosswalk']
def sampler(xy):
uv=project(xy,g).astype('float32');coord=lambda a,scale:cv2.remap(a.astype('float32'),(uv[:,0]*scale).reshape(-1,48),(uv[:,1]*scale).reshape(-1,48),cv2.INTER_LINEAR).reshape(len(xy),-1)
return coord(rgb,factor),coord(vehicle,1).ravel(),(sample(labels,xy,low,high)==1).astype(float),coord(cross,1).ravel()
stripes,stats=recover(m,sampler);rec.update(stats)
if stats['matched_observations']<max(2,.45*len(stripes)):
rec['reason']='insufficient-brightness-agreement';reports.append(rec);continue
# Whole-object replacement prevents old fragments overlapping fitted stripes.
for key in ids:changes[key]=None
for stripe in stripes:
added.append(feature(lift(stripe['polygon']),'road_marking',subtype='crosswalk',method='observed-profile-crosswalk-family',source_ids=ids,source_tile=name,crosswalk_family=gi,observed_center=stripe['observed'],recovered_stripe=stripe['new'],ends_source='robust-shared-family',shared_width_m=stats['width_m']))
rec['accepted']=True;rec['bounds_xy']=shapely.union_all([r['polygon']for r in stripes]).bounds;rec['source_image_sha256']=hashlib.sha256((Path('/ortho/evidence')/(name+'.ground.png')).read_bytes()).hexdigest();reports.append(rec);print('CROSSING',gi,name,stats,flush=True)
features=[f for f in old['features']if f['id']not in changes]+added
from line_family_completion import normalize
crossings=shapely.union_all([shapely.force_2d(shape(f['geometry']))for f in features if f['properties'].get('subtype')=='crosswalk'])
def admit_line(p):
if p.intersection(crossings).area>.02:return False
ring=shapely.force_2d(p).exterior;xy=np.array([ring.interpolate(t).coords[0]for t in np.linspace(0,ring.length,max(5,int(ring.length/.2)))])
return float(np.mean(sample(labels,xy,low,high)==1))>.8
features,line_audit=normalize(features,lift,admit_line)
(O/'line-families.json').write_text(json.dumps(line_audit,indent=2,allow_nan=False))
result={**old,'features':features,'review_status':'unreviewed','paint_refinement':'crosswalk-brightness-profile-v1'}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'crosswalk-families.json').write_text(json.dumps(reports,indent=2,allow_nan=False))
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(Path('/fullplan/full-map.json').read_bytes()).hexdigest(),groups=len(reports),accepted_groups=sum(r['accepted']for r in reports),replaced_stripes=len(changes),result_stripes=len(added),recovered_stripes=sum(r.get('new_stripes',0)for r in reports if r['accepted']),manual_geometry=False,manual_rois=[],policy_version='crosswalk-brightness-profile-v1')
report.update(periodic_line_families=len(line_audit),filled_dash_slots=sum(r['added_internal_m_or_slots']for r in line_audit))
(O/'paint-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,37 @@
from pathlib import Path
import json,os,shutil
from datetime import datetime,timezone
import numpy as np
from PIL import Image,ImageDraw,ImageFont
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=json.loads((O/'crosswalk-families.json').read_text());font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('crosswalk-*.jpg'):
history=O/'attempts'/('crosswalk-render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));history.mkdir(parents=True,exist_ok=True);shutil.move(p,history/p.name)
def draw(im,g,features,subtypes=('crosswalk',)):
im=im.copy();d=ImageDraw.Draw(im);scale=im.width/1200
for f in features:
if f['properties'].get('subtype')not in subtypes:continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*scale],fill='#f1c300',width=max(3,int(scale*2)))
return im
pages=[];frames=[]
for rec in groups:
if not rec['accepted']:continue
gi=rec['group'];name=rec['source_tile'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');scale=raw.width/1200
x0,y0,x1,y1=rec['bounds_xy'];uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*scale;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*2.5/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,'Гауссы'),(draw(raw,g,old['features']),'До: '+str(rec['input_stripes'])),(draw(raw,g,new['features']),'После: '+str(rec['output_stripes']))]):
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='crosswalk-%02d.jpg'%gi;frame.save(O/fn,quality=95);frames.append(frame);pages.append(dict(group=gi,file=fn,new_stripes=rec['new_stripes'],source_tile=name))
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/('crosswalk-proof-%02d.jpg'%(start//4+1)),quality=95)
(O/'crosswalk-visual-manifest.json').write_text(json.dumps(pages,indent=2));print('RENDERED',len(pages),'crossings')
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];line_pages=[]
for gi,rec in enumerate(json.loads((O/'line-families.json').read_text())):
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');scale=raw.width/1200
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*scale;center=(uv.min(0)+uv.max(0))/2;extent=max(uv.max(0)-uv.min(0))+raw.width*3/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,'Гауссы'),(draw(raw,g,old['features'],('crosswalk','linear_marking')),'До'),(draw(raw,g,new['features'],('crosswalk','linear_marking')),'После')]):
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='line-family-%02d.jpg'%gi;frame.save(O/fn,quality=95);line_pages.append(dict(group=gi,file=fn,source_tile=name,added_slots=rec['added_internal_m_or_slots']))
(O/'line-visual-manifest.json').write_text(json.dumps(line_pages,indent=2));print('RENDERED',len(line_pages),'line families')
@@ -0,0 +1,38 @@
import numpy as np,cv2,json
from pathlib import Path
from shapely.geometry import Polygon,mapping,shape
from crossing_completion import observations,groups,model,recover
checks={}
def fixture(centers,seed_ids,angle=0,offset=(0,0),occluded=(),black=(),yellow=(),gradient=False):
a=angle;R=np.array([[np.cos(a),-np.sin(a)],[np.sin(a),np.cos(a)]]);o=np.array(offset);fs=[]
for j in seed_ids:
p=np.array([[-2,centers[j]-.25],[2,centers[j]-.25],[2,centers[j]+.25],[-2,centers[j]+.25]])@R.T+o
fs.append(dict(id=str(j),geometry=mapping(Polygon(p)),properties=dict(subtype='crosswalk')))
m=model(observations(fs))
def sampler(xy):
uv=(xy-o)@R;white=np.zeros(len(xy),bool);veh=np.zeros(len(xy))
for j,s in enumerate(centers):
stripe=(abs(uv[:,1]-s)<.25)&(abs(uv[:,0])<2)
if j not in black:white|=stripe
if j in occluded:veh[stripe]=1
rgb=np.repeat(np.where(white,220,65)[:,None],3,axis=1).astype('uint8')
for j,s in enumerate(centers):
stripe=(abs(uv[:,1]-s)<.25)&(abs(uv[:,0])<2)
if j in yellow:rgb[stripe]=[235,190,55]
elif gradient:rgb[stripe]=np.repeat((180+120*(uv[stripe,1]-s+.25))[:,None],3,axis=1).astype('uint8')
return rgb,veh,np.ones(len(xy)),np.zeros(len(xy))
return recover(m,sampler)
r,stats=fixture(np.arange(9),[0,1,3,4,7,8]);checks['three_observed_missing_stripes_recovered']=stats['new_stripes']==3 and len(r)==9
r,stats=fixture(np.arange(9),[0,1,3,4,7,8],black=[2,5,6]);checks['no_invisible_stripes_invented']=stats['new_stripes']==0
r,stats=fixture(np.arange(9),[0,1,3,4,7,8],occluded=[2,5,6]);checks['vehicle_is_not_paint']=stats['new_stripes']==0
r,stats=fixture(np.arange(9),[0,1,3,4,7,8],angle=.72,offset=(500,-300));checks['rigid_transform_invariant']=stats['new_stripes']==3 and len(r)==9
checks['rectangles_do_not_overlap']=not any(a['polygon'].intersection(b['polygon']).area>1e-6 for i,a in enumerate(r)for b in r[:i])
r,stats=fixture(np.arange(9),[0,1,3,4,7,8]);checks['no_invisible_exterior_generation']=len(r)==9 and all(-.2<x['polygon'].centroid.y<8.2 for x in r)
r,stats=fixture(np.arange(9),[1,2,4,5,7]);checks['observed_periodic_end_stripes_recovered']=len(r)==9
r,stats=fixture(np.arange(9),[0,1,3,4,7,8],gradient=True);checks['brightness_gradient_does_not_shift_center']=len(r)==9 and max(abs(x['polygon'].centroid.y-round(x['polygon'].centroid.y))for x in r)<.1
r,stats=fixture(np.arange(13)*.55,[0,2,4,6,8,10,12],yellow=[1,3,5,7,9,11]);checks['white_yellow_interleaving']=len(r)==13
from line_family_completion import normalize
fs=[dict(id=str(i),geometry=mapping(Polygon([(i-.25,-.05),(i+.25,-.05),(i+.25,.05),(i-.25,.05)])),properties=dict(subtype='linear_marking',**{'class':'road_marking'}))for i in [0,1,3,4]]
out,audit=normalize(fs,lambda p:p,lambda p:True);checks['short_dash_gap_filled_without_solid_line']=len(out)==5 and sum(x['added_internal_m_or_slots']for x in audit)==1 and all(abs(shape(f['geometry']).area-.05)<1e-5 for f in out)
out,audit=normalize(fs,lambda p:p,lambda p:False);checks['crosswalk_veto_preserves_original_dashes']=out==fs and not audit
report=dict(passed=all(checks.values()),checks=checks);Path('/out/family-tests.json').write_text(json.dumps(report,indent=2));print(json.dumps(report));assert report['passed']