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,96 @@
"""Bounded Gaussian-only refinement qualification; all calculation runs on Worker."""
from pathlib import Path
import json,copy,unittest,hashlib,numpy as np
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape,LineString,Point,box,mapping
from shapely.ops import substring
import qualify_junctions as q
from plan_refinement import refine_profile,replace_interval
from refinement_evidence import Field
from plan_scene import clip_inferred
from driveway_refinement import fit_access,split_access
from long_edge_refinement import refine_long_edge
from qualify_scene_assembly import make_overview
from audit_refinement import audit
def render_review(h,field,oldcurbs,curbs):
lo=np.array(h['bounds'][:2]);hi=np.array(h['bounds'][2:]);resolution=.05
xs=np.arange(lo[0],hi[0],resolution);ys=np.arange(hi[1],lo[1],-resolution);xx,yy=np.meshgrid(xs,ys);xy=np.c_[xx.ravel(),yy.ravel()]
ids=field.owners(xy);pixels=np.full((len(xy),3),255,dtype=np.uint8)
for i in np.unique(ids):
if i<0:continue
keep=ids==i;e=field.load(field.frames[i][0]);uv=q.project(xy[keep],e.g)
pixels[keep]=np.array([q.sample(e.image[:,:,c],uv)for c in range(3)]).T
source=Image.fromarray(pixels.reshape(len(ys),len(xs),3));before=source.copy();after=source.copy()
for features,image in [(oldcurbs,before),(curbs,after)]:
d=ImageDraw.Draw(image)
for f in features:
p=np.array(f['geometry']['coordinates']);uv=np.c_[(p[:,0]-lo[0])/resolution,(hi[1]-p[:,1])/resolution]
d.line([tuple(v)for v in uv],fill='#ed8728',width=3)
for suffix,image in [('source',source),('before',before),('after',after)]:image.save(q.O/(h['id']+'.'+suffix+'.jpg'),quality=98)
try:font=ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',20)
except OSError:font=ImageFont.load_default()
panel=Image.new('RGB',(source.width*2,source.height+38),'#f5f5f1');panel.paste(before,(0,38));panel.paste(after,(source.width,38));d=ImageDraw.Draw(panel)
d.text((12,7),h['id']+' / BEFORE',fill='#243540',font=font);d.text((source.width+12,7),h['id']+' / AFTER',fill='#243540',font=font)
panel.save(q.O/(h['id']+'.comparison.jpg'),quality=98)
def main():
q.O=Path('/out');base=json.loads(Path('/baseline/whole-map.json').read_text());hints=json.loads(Path('/candidate/review-hints.json').read_text());result=copy.deepcopy(base)
suite=unittest.defaultTestLoader.loadTestsFromNames(['test_plan_refinement','test_plan_junctions','test_plan_continuity','test_plan_scene'])
tests=unittest.TextTestRunner(verbosity=2).run(suite);assert tests.wasSuccessful()
curbs=[f for f in result['features']if f['properties']['class']=='road_boundary'];oldcurbs=[f for f in base['features']if f['properties']['class']=='road_boundary'];reports=[]
baseline_sha=hashlib.sha256(Path('/baseline/whole-map.json').read_bytes()).hexdigest()
for f in curbs:
p=f['properties'];p['prior_construction']=p.pop('construction',[]);p['construction']=[dict(kind='baseline-curb',parents=[dict(id=f['id'],interval_m=[0.,shape(f['geometry']).length])])]
review_boxes=[box(*h['bounds'])for h in hints['cases']];tiles=[]
for mask in sorted(q.E.glob('tile-*.normal.npz')):
name=mask.name.removesuffix('.normal.npz')
if not(q.E/'road-prompt'/mask.name).exists():continue
job=json.loads((q.S/name/'job.json').read_text());lo,hi=job['bounds_xy'];domain=box(*lo,*hi)
if any(domain.intersects(bounds)for bounds in review_boxes):tiles.append(name)
field=Field(tiles)
for h in hints['cases']:
f=min(curbs,key=lambda f:shape(f['geometry']).distance(Point(h['center'])));line=shape(f['geometry'])
if h['kind']=='driveway':
e=field.load(h['tile']);corners,ends,model=fit_access(line,h['center'],e,h['bounds']);a,b,opening=split_access(f['geometry']['coordinates'],corners,ends);children=[]
intervals=[[0.,opening['source_interval_m'][0]],[opening['source_interval_m'][1],line.length]]
for i,part in enumerate((a,b)):
child=copy.deepcopy(f);child['id']=f['id']+'-access-'+str(i);child['geometry']=mapping(LineString(part));p=child['properties'];p['length_m']=LineString(part).length
p['construction']=[dict(kind='reviewed-access-refinement',parents=[dict(id=f['id'],interval_m=intervals[i])])]
p['inferred_spans']=clip_inferred(p.get('inferred_spans',[]),LineString(part));p['inferred_spans'].append(dict(status='inferred',method=model['method'],coordinates=(part[-2:]if i==0 else part[:2]).tolist(),source_review=h['id']))
p['access_model']=model;p['known_opening']=opening;p['end_reason'if i==0 else'start_reason']='reviewed-access-extent';children.append(child)
curbs.remove(f);curbs.extend(children);result['features'].remove(f);result['features'].extend(children);reports.append(dict(id=h['id'],feature_id=f['id'],model=model,opening=opening))
else:
clipped=line.intersection(box(*h['bounds']));parts=[clipped]if clipped.geom_type=='LineString'else [g for g in clipped.geoms if g.geom_type=='LineString'];part=min(parts,key=lambda p:p.distance(Point(h['center'])))
a,b=sorted(line.project(Point(p[:2]))for p in np.array(part.coords)[[0,-1]]);p=np.array(substring(line,a,b).coords)
curve,model,profiles=refine_long_edge(p,field,band=2.)if h['kind']=='long-edge'else refine_profile(p,field,band=1.5,spacing=2.5,smoothness=.8)
new=replace_interval(np.array(line.coords),a,b,curve);new_line=LineString(new);f['geometry']=mapping(new_line)
oldspans=f['properties'].get('inferred_spans',[]);oldspans.append(dict(status='inferred',method=model.get('method','image-profile-clamped-bspline'),coordinates=curve.tolist(),source_review=h['id']))
f['properties']['inferred_spans']=clip_inferred(oldspans,new_line);f['properties']['length_m']=new_line.length;f['properties'].setdefault('refinement_models',[]).append(model)
reports.append(dict(id=h['id'],feature_id=f['id'],source_interval_m=[a,b],model=model,profiles=profiles))
print('REFINEMENT',h['id'],json.dumps({k:v for k,v in model.items()if k not in ['knots','control_xy']}),flush=True)
for name in ['assembly','continuity']:result['prior_'+name]=result.pop(name,None)
result['refinement']=dict(scope='owner-reviewed-regions',methods=['OpenCV LSD / line consensus / Huber','normal-profile dynamic programming / clamped cubic B-spline'],cases=[r['id']for r in reports],height='inherited-not-refitted',baseline_sha256=baseline_sha)
result['assembly']=dict(output_curbs=len(curbs),crossings=0,height_status='inherited-not-refitted',source_accounting='baseline-curb-intervals-with-explicit-known-opening')
result['review_status']='candidate-unreviewed'
nodes=[dict(id=f['id']+':'+str(e),coordinates=f['geometry']['coordinates'][0 if e==0 else -1],degree=1,status=f['properties'].get('start_reason'if e==0 else'end_reason','open-curb-end'))for f in curbs for e in(0,1)]
edges=[dict(id=f['id'],start_node=f['id']+':0',end_node=f['id']+':1',geometry=f['geometry'],construction=f['properties']['construction'])for f in curbs]
graph=dict(schema='missioncore.boundary-graph/v1',nodes=nodes,edges=edges,baseline_sha256=baseline_sha,route_permission='unassigned')
(q.O/'whole-map.json').write_text(json.dumps(result,allow_nan=False));(q.O/'boundary-graph.json').write_text(json.dumps(graph,allow_nan=False))
saved=json.loads((q.O/'whole-map.json').read_text());saved_graph=json.loads((q.O/'boundary-graph.json').read_text());checks=audit(base,saved,hints,reports,saved_graph)
checks.update(tests_passed=tests.testsRun,baseline_sha256=baseline_sha,world_map_sha256=hashlib.sha256((q.O/'whole-map.json').read_bytes()).hexdigest())
(q.O/'independent-audit.json').write_text(json.dumps(checks,indent=2,allow_nan=False));(q.O/'refinement-report.json').write_text(json.dumps(dict(cases=reports,topology=checks),indent=2,allow_nan=False))
for h in hints['cases']:render_review(h,field,oldcurbs,curbs)
for tile in sorted((q.E).glob('tile-*.normal.npz')):
name=tile.name.removesuffix('.normal.npz')
if not(q.E/'road-prompt'/tile.name).exists():continue
image=Image.open(q.S/name/'top.png').convert('RGB');image.save(q.O/(name+'.source.jpg'),quality=95);d=ImageDraw.Draw(image)
with np.load(q.S/name/'top.geometry.npz')as z:g={k:z[k]for k in ['view','intrinsics']}
for f in curbs:d.line([tuple(p)for p in q.project(f['geometry']['coordinates'],g)],fill='#ed8728',width=3)
image.save(q.O/(name+'.assembled.jpg'),quality=95)
make_overview(q,base,curbs)
print('AUDIT',json.dumps({k:v for k,v in checks.items()if k!='source_accounting'}),flush=True)
if __name__=='__main__':main()