Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/systematic/assemble_surfaces.py
T
DCCONSTRUCTIONS 69dc566665 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.
2026-10-29 09:10:00 +03:00

82 lines
6.8 KiB
Python

"""Four logical layers with frozen curbs, observed fronts and object-level paint.
No tile-specific policy, manual coordinates, point cloud or collider inputs.
"""
from pathlib import Path
import json,hashlib,time,os
import numpy as np,cv2,shapely
from shapely.geometry import shape,Polygon,LineString,mapping
from shapely.ops import unary_union,transform
from rasterio.features import shapes
from affine import Affine
from scipy.ndimage import distance_transform_edt,gaussian_filter1d,binary_closing
from layer_common import O,S,B,feature,parts,sample
from fit_scene import world,resample
from plan_boundaries import split_observed_boundary
from plan_coverage import vectorize
from plan_primitives import regularize_paint,frontage_envelope
from frontage_chains import join_planes
from paint_templates import fit_symbol
from crosswalk_family import rectangle_info,joint_rectangles
cv2.setNumThreads(3);start=time.monotonic();report={};tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed']
evidence_receipt=json.loads((O/'evidence/report.json').read_text())
for rec in evidence_receipt['records']:
assert hashlib.sha256((O/'evidence'/(rec['tile']+'.npz')).read_bytes()).hexdigest()==rec['sha256']
assert {rec['tile']for rec in evidence_receipt['records']}=={t['id']for t in tiles}
input_hashes={str(p):hashlib.sha256(p.read_bytes()).hexdigest()for p in [S/'tile-index.json',B/'whole-map.json',B/'observed-lines-v1/fields.npz',B/'regions/whole/fields.npz',Path('/multiview/mapillary/atlas-sparse.npz'),O/'evidence/report.json']}
base=json.loads((B/'whole-map.json').read_text());road_bytes=(B/'whole-map.json').read_bytes();fields=np.load(B/'observed-lines-v1/fields.npz');low,high=fields['bounds'];road=fields['road']>.5;side=fields['side']>.5;alpha=fields['alpha'];height=np.load(B/'regions/whole/fields.npz')['z'];h,w=side.shape;fields.close();cell=.1
labels=np.where(side,2,np.where(road,1,0)).astype('uint8')
np.savez_compressed(O/'fields.npz',bounds=np.array([low,high]),labels=labels,z=height,cell=cell)
(O/'map.base.json').write_text(json.dumps(base,allow_nan=False))
def lift(g):
def f(x,y,z=None):
xy=np.c_[x,y];zz=sample(height,xy,low,high);return x,y,zz
return transform(f,g)
# Coverage polygons identify observed sidewalk, not physical scan-end curbs.
walk=[]
coverage,classes=vectorize(labels,tolerance=.25,transform=Affine(cell,0,low[0],0,-cell,high[1]))
for p,cls in zip(coverage,classes):
if cls!=2 or p.area<3:continue
walk.append(feature(lift(p),'pedestrian_area',method='shared-semantic-coverage-GEOS',boundary_role='coverage-outline-not-physical-curb',area_m2=p.area,physical_boundary_ids=[f['id']for f in base['features']if shape(f['geometry']).distance(p)<.6]))
del coverage,classes
# Facades reuse the existing Gaussian covariance/vertical-plane detector.
import source_facade_planes
source_facade_planes.main()
facade_doc=json.loads((O/'map.source-facades-v3.json').read_text());rawfacades=[f for f in facade_doc['features']if f['properties']['class']=='building_facade']
planes=[shapely.force_2d(shape(f['geometry']))for f in rawfacades]
def ground_side(points,normal):
plus=sum(np.mean(sample(labels,points+normal*d,low,high)>0)for d in [.5,1.,1.5])
minus=sum(np.mean(sample(labels,points-normal*d,low,high)>0)for d in [.5,1.,1.5])
return float(np.sign(plus-minus))
envelope,envelope_report=frontage_envelope(planes,ground_side)
joined=join_planes([g for g,ids in envelope]);facades=[]
for p,ids in joined:
g=LineString(p)
facades.append(feature(lift(g),'building_facade',method='gaussian-covariance-vertical-planes-huber-join',source_plane_ids=sorted({rawfacades[j]['id']for i in ids for j in envelope[i][1]}),closed_footprint=False,hidden_backs_invented=False))
# Additional true pedestrian/terrain interfaces; never raster coverage caps.
a=np.load('/multiview/mapillary/atlas-sparse.npz');terrain=np.zeros((h,w),np.float32);terrain[a['rows'],a['cols']]=a['posterior'][4];a.close();near_terrain=distance_transform_edt(terrain<.45)*cell
contours,_=cv2.findContours(side.astype('uint8'),cv2.RETR_LIST,cv2.CHAIN_APPROX_NONE);walk_edges=[]
road_geom=unary_union([shapely.force_2d(shape(f['geometry']))for f in base['features']]);facade_geom=unary_union([shapely.force_2d(shape(f['geometry']))for f in facades])
for c in contours:
if len(c)<30:continue
p=c[:,0];xy=np.c_[low[0]+(p[:,0]+.5)*cell,high[1]-(p[:,1]+.5)*cell];xy=resample(np.vstack([xy,xy[0]]),.15)[:-1]
seen=sample(alpha,xy,low,high)>.75;physical=sample(near_terrain,xy,low,high)<.5
physical=binary_closing(physical,structure=np.ones(7))&seen
for chain in split_observed_boundary(xy,physical,seen,minimum_length=3):
g=LineString(chain.points).simplify(.2,preserve_topology=True)
for piece in parts(g.difference(road_geom.buffer(.65)).difference(facade_geom.buffer(.5)),'LineString'):
if piece.length>3:walk_edges.append(feature(lift(piece),'pedestrian_boundary',method='observed-walk-terrain-interface',closed=piece.is_closed))
paint=[];rejected=[]
result={**base,'schema_version':'missioncore.full-observed-plan-research/v1','features':base['features']+walk+walk_edges+facades+paint,'review_status':'unreviewed','road_baseline_sha256':hashlib.sha256(road_bytes).hexdigest(),'logical_layers':['roads','pedestrian_zones','buildings','road_markings']}
# Validation is structural, separate from visual and metric accuracy.
invalid=[]
for f in result['features']:
geom=shape(f['geometry']);coords=shapely.get_coordinates(geom,include_z=True)
if not geom.is_valid or not np.isfinite(coords).all():invalid.append(f['id'])
assert not invalid,invalid
assert result['features'][:len(base['features'])]==base['features']
assert all(shape(f['geometry']).geom_type=='LineString'and not shape(f['geometry']).is_closed for f in facades)
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
(O/'unresolved-markings.json').write_text(json.dumps(rejected,allow_nan=False))
report=dict(frontage_envelope=envelope_report,input_sha256=input_hashes,scene=os.environ['SCENE'],seconds=time.monotonic()-start,road_curbs_preserved_exactly=True,road_baseline_sha256=hashlib.sha256(road_bytes).hexdigest(),counts={c:sum(f['properties']['class']==c for f in result['features'])for c in ['road_boundary','pedestrian_area','pedestrian_boundary','building_facade','road_marking']},pedestrian_area_m2=sum(shape(f['geometry']).area for f in walk),facade_length_m=sum(shape(f['geometry']).length for f in facades),paint_subtypes={c:sum(f['properties']['subtype']==c for f in paint)for c in sorted(set(f['properties']['subtype']for f in paint))},unresolved_markings=len(rejected),manual_rois=[],manual_geometry=False,point_clouds=False,colliders=False,metric_accuracy_measured=False,source_gaussian_planes_reused=True,hidden_building_backs_invented=0,all_geometry_valid_finite_xyz=True)
(O/'report.json').write_text(json.dumps(report,indent=2));print('FULL-PLAN',json.dumps(report),flush=True)