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,24 @@
from pathlib import Path
import json,numpy as np,hashlib,shapely
from shapely.geometry import shape
from surface_height import sample,POLICY
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads(Path('/out/full-map.json').read_text());ref=dict(np.load('/ortho/terrain-reference.npz'));field=dict(np.load('/out/surface-reference.npz'))
assert len(old['features'])==len(new['features']);stats={};checks=[]
def rings(f):return f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']]
for a,b in zip(old['features'],new['features']):
assert a['id']==b['id'];cls=a['properties']['class']
if cls not in ['pedestrian_area','pedestrian_boundary']:assert a==b;continue
ga,gb=shape(a['geometry']),shape(b['geometry']);assert ga.is_valid and gb.is_valid
assert len(rings(a))==len(rings(b));assert shapely.hausdorff_distance(shapely.force_2d(ga),shapely.force_2d(gb))<1e-7
if ga.geom_type=='Polygon':assert abs(ga.area-gb.area)<1e-7 and len(ga.interiors)==len(gb.interiors)
for label,f in [('before',a),('after',b)]:
k=stats.setdefault(label,dict(vertices=0,over_one_metre=0,steep_segments=0,max_height_residual=0,max_segment_grade=0))
for ring in rings(f):
xyz=np.array(ring);assert np.isfinite(xyz).all();delta=xyz[:,2]-sample(ref,xyz[:,:2]);seg=np.diff(xyz,axis=0);grade=abs(seg[:,2])/np.maximum(np.linalg.norm(seg[:,:2],axis=1),1e-6)
k['vertices']+=len(xyz);k['over_one_metre']+=int((delta>1).sum());k['steep_segments']+=int((grade>1).sum());k['max_height_residual']=max(k['max_height_residual'],float(delta.max()));k['max_segment_grade']=max(k['max_segment_grade'],float(grade.max()))
if label=='after':assert np.max(abs(xyz[:,2]-sample(field,xyz[:,:2])))<1e-6
assert {k:v for k,v in b['properties'].items()if k!='height_projection'}==a['properties']
checks=['same_ids_counts_and_xy','holes_and_open_ends_preserved','road_facade_markings_exactly_unchanged','finite_valid_surface','exact_shared_ground_projection','no_metre_height_spikes']
assert stats['after']['over_one_metre']==0 and stats['after']['steep_segments']==0,stats
result=dict(passed=True,checks=checks,metrics=stats,full_map_sha256=hashlib.sha256(Path('/out/full-map.json').read_bytes()).hexdigest())
Path('/out/surface-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result))
@@ -0,0 +1,10 @@
{
"source_snapshot": "8abe9982c976385e0e72",
"sha256": {
"surface_height.py": "62e2d61ab548c43898dbcf94516a8fb0f48e68be6133abc5b952677c3f265fcf",
"refine_surface.py": "f691e5a9cad3d548fdf3019dba5db45fe55cf13a641fe81a2779a8cb8847328e",
"audit_surface.py": "2d16fc34ae7d6269066a7e34a6780cedfb691f2725343f8c568758f6f3deac2b",
"diagnose_surface.py": "bc67d2cc2b59ebbd6dac5ababd829c80914bf014f275513a77c226e36a03aac7",
"test_surface.py": "81525fd8abf49276f05959ad1bb17e4c2787b32eba2d7ff3f7c21fbcfb0338ee"
}
}
@@ -0,0 +1,15 @@
from pathlib import Path
import numpy as np,json,hashlib
from scipy.ndimage import map_coordinates
from collections import defaultdict
plan=json.loads(Path('/fullplan/full-map.json').read_text());field=dict(np.load('/ortho/terrain-reference.npz'))
report=dict(terrain={k:dict(shape=list(v.shape),dtype=str(v.dtype))for k,v in field.items()},classes={})
by=defaultdict(list)
def rings(f):return f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']]
for f in plan['features']:
for ring in rings(f):
xyz=np.array(ring);uv=(xyz[:,:2]-field['low'])/float(field['cell_m'])-.5;z=map_coordinates(field['height'],[uv[:,1],uv[:,0]],order=1,mode='nearest');distance=map_coordinates(field['ground_distance'],[uv[:,1],uv[:,0]],order=1,mode='nearest');delta=xyz[:,2]-z
seg=np.diff(xyz,axis=0);slope=np.abs(seg[:,2])/np.maximum(np.linalg.norm(seg[:,:2],axis=1),1e-6)
by[f['properties']['class']].append(dict(id=f['id'],vertices=len(xyz),max_height_delta=float(delta.max()),min_height_delta=float(delta.min()),high_vertices=int((delta>1).sum()),steep_segments=int((slope>1).sum()),height_range=[float(xyz[:,2].min()),float(xyz[:,2].max())],terrain_distance_max=float(distance.max())))
for c,rows in by.items():report['classes'][c]=dict(rings=len(rows),vertices=sum(x['vertices']for x in rows),high_vertices=sum(x['high_vertices']for x in rows),steep_segments=sum(x['steep_segments']for x in rows),max_height_delta=max(x['max_height_delta']for x in rows),min_height_delta=min(x['min_height_delta']for x in rows),worst=sorted(rows,key=lambda x:-x['max_height_delta'])[:3])
report['terrain_report']=json.loads(Path('/ortho/terrain-report.json').read_text());Path('/out/diagnosis.json').write_text(json.dumps(report,indent=2));print(json.dumps({c:{k:v for k,v in r.items()if k!='worst'}for c,r in report['classes'].items()}))
@@ -0,0 +1,17 @@
from pathlib import Path
import numpy as np,json,hashlib,time,copy
from surface_height import ground_reference,project_ring,POLICY
start=time.monotonic();P=Path('/fullplan/full-map.json');raw=P.read_bytes();plan=json.loads(raw);old=copy.deepcopy(plan)
reference=dict(np.load('/ortho/terrain-reference.npz'))
with np.load('/evidence_plan/fields.npz')as f:field,measure=ground_reference(reference,f['labels'],f['z'],f['bounds'][0],f['bounds'][1],float(f['cell']))
np.savez_compressed('/out/surface-reference.npz',**field)
sha=hashlib.sha256(Path('/out/surface-reference.npz').read_bytes()).hexdigest();changed=[]
for f in plan['features']:
if f['properties']['class'] not in ['pedestrian_area','pedestrian_boundary']:continue
g=f['geometry'];rings=g['coordinates']if g['type']=='Polygon'else[g['coordinates']]
rings=[project_ring(r,field)for r in rings];g['coordinates']=rings if g['type']=='Polygon'else rings[0]
f['properties']['height_projection']=dict(method='gaussian-terrain-sidewalk-offset-v1',surface_sha256=sha,metric_accuracy_measured=False)
changed.append(f['id'])
Path('/out/full-map.json').write_text(json.dumps(plan,allow_nan=False))
report=dict(policy=POLICY,method='gaussian-terrain-sidewalk-offset-v1',measurements=measure,changed_ids=changed,baseline_sha256=hashlib.sha256(raw).hexdigest(),input_sha256={p:hashlib.sha256(Path(p).read_bytes()).hexdigest()for p in ['/ortho/terrain-reference.npz','/ortho/terrain-report.json','/evidence_plan/fields.npz']},surface_sha256=sha,seconds=time.monotonic()-start,manual_rois=[],manual_geometry=False,point_clouds=False,colliders=False)
Path('/out/surface-report.json').write_text(json.dumps(report,indent=2));print(json.dumps(report))
@@ -0,0 +1,34 @@
"""Pedestrian ground projection using Gaussian terrain and robust sidewalk offsets."""
import numpy as np
from scipy.ndimage import map_coordinates, binary_erosion, distance_transform_edt, gaussian_filter
from scipy.stats import binned_statistic_2d
POLICY = dict(max_reference_residual_m=.6, interior_margin_m=.3, offset_smooth_m=1., max_segment_m=2.)
def sample(field, xy, key='height'):
xy=np.asarray(xy,float); uv=(xy-field['low'])/float(field['cell_m'])-.5
return map_coordinates(field[key], [uv[:,1],uv[:,0]], order=1,mode='nearest')
def ground_reference(reference, labels, raw_height, low, high, cell):
"""Reject facade/vehicle height, median-bin interior observations, smooth residuals."""
step=max(1,round(POLICY['interior_margin_m']/cell))
interior=binary_erosion(labels==2,iterations=step)
rr,cc=np.where(interior & np.isfinite(raw_height)); rr,cc=rr[::3],cc[::3]
xy=np.c_[low[0]+(cc+.5)*cell,high[1]-(rr+.5)*cell]
residual=raw_height[rr,cc]-sample(reference,xy)
keep=np.abs(residual)<=POLICY['max_reference_residual_m'];xy=xy[keep];residual=residual[keep]
h,w=reference['height'].shape; spacing=float(reference['cell_m']);origin=reference['low']
if len(xy)<100:raise ValueError('Insufficient uncontaminated sidewalk ground observations')
offset,_,_,_=binned_statistic_2d(xy[:,1],xy[:,0],residual,statistic='median',bins=(h,w),range=((origin[1],origin[1]+h*spacing),(origin[0],origin[0]+w*spacing)))
known=np.isfinite(offset);distance,near=distance_transform_edt(~known,sampling=spacing,return_indices=True)
filled=offset[tuple(near)];sigma=POLICY['offset_smooth_m']/spacing
# Nearest measured local sidewalk offset supplies masked gaps, never wall depth.
smooth=gaussian_filter(filled,sigma)
field=dict(height=reference['height']+smooth,low=origin,cell_m=spacing,offset=smooth,offset_distance=distance)
return field,dict(interior_samples=len(rr),accepted_samples=int(keep.sum()),rejected_samples=int((~keep).sum()),median_offset_m=float(np.median(residual)),offset_range_m=[float(smooth.min()),float(smooth.max())])
def project_ring(ring,field):
xyz=np.asarray(ring,float);parts=[]
for a,b in zip(xyz[:-1],xyz[1:]):
n=max(1,int(np.ceil(np.linalg.norm(b[:2]-a[:2])/POLICY['max_segment_m'])))
parts.extend(a[:2]+(b[:2]-a[:2])*t/n for t in range(n))
parts.append(xyz[-1,:2]);xy=np.asarray(parts);return np.c_[xy,sample(field,xy)].tolist()
@@ -0,0 +1,18 @@
import unittest,numpy as np,json
from pathlib import Path
from surface_height import ground_reference,project_ring,sample
class SurfaceTest(unittest.TestCase):
def setUp(self):
yy,xx=np.mgrid[:30,:30];self.ref=dict(height=2.+.02*xx+.03*yy,low=np.array([0.,0.]),cell_m=1.)
self.xy=np.c_[xx.ravel()+.5,yy.ravel()+.5];self.raw=(sample(self.ref,self.xy)+.12).reshape(30,30)[::-1].copy();self.labels=np.full((30,30),2,np.uint8)
def test_facade_rejected_and_slope_retained(self):
self.raw[10:12,5:25]+=4
f,r=ground_reference(self.ref,self.labels,self.raw,np.array([0.,0.]),np.array([30.,30.]),1.)
self.assertGreater(r['rejected_samples'],0);np.testing.assert_allclose(f['height'],self.ref['height']+.12,atol=1e-6)
def test_no_false_ground_without_support(self):
with self.assertRaises(ValueError):ground_reference(self.ref,self.labels,self.raw+4,np.array([0.,0.]),np.array([30.,30.]),1.)
def test_closed_ring_follows_ground_without_xy_deformation(self):
p=np.array(project_ring([[2,2,100],[20,2,100],[20,10,100],[2,2,100]],self.ref));np.testing.assert_equal(p[0],p[-1]);self.assertTrue((np.linalg.norm(np.diff(p[:,:2],axis=0),axis=1)<=2.000001).all());np.testing.assert_allclose(p[:,2],sample(self.ref,p[:,:2]))
def test_open_end_remains_open(self):
p=project_ring([[2,2,100],[20,2,100]],self.ref);self.assertNotEqual(p[0],p[-1]);np.testing.assert_equal(np.array(p)[[0,-1],:2],[[2,2],[20,2]])
r=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromTestCase(SurfaceTest));Path('/out/surface-tests.json').write_text(json.dumps(dict(passed=r.wasSuccessful(),tests=r.testsRun)));raise SystemExit(not r.wasSuccessful())