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,54 @@
Full observed urban plan (offline research)
=========================================
Four logical layers: preserved accepted road boundaries, observed pedestrian
coverage and pedestrian/terrain interfaces, observed building frontages, and
parametric paint. This is an offline Gaussian-only candidate, not a published
navigation map or survey-grade deliverable.
Run semantic_layers.py, test_layers.py, assemble_layers.py and render_layers.py
on the reserved external Worker. No per-scene parameters or manual processing
ROIs are supported. Scene names only label diagnostic pictures.
Read-only inputs: /survey (Gaussian orthographic captures), /ortho (native RGB,
terrain, existing vehicle masks), /multiview (pinned class fusion), /base (frozen
v8 road vectors and fields), /input (original Gaussian PLY with covariance and
SH attributes). /out owns all new outputs. No collider or point-cloud input.
The pinned SAM3 model nominates road paint using uniform overlapping 15 m
windows. Paint must also have observed photometric support. Existing OpenCV
rectangle fits, SciPy joint crosswalk fitting and reusable arrow/A hypotheses
produce clean geometry. Unsupported symbols are recorded separately, never
exported as ragged approximations. Bicycle and parking-symbol templates remain
unsupported. A crosswalk family requires three compatible observed stripes;
this conservative admission can omit partially scanned crossings.
Observed sidewalk polygons explicitly describe semantic coverage, not physical
curbs or navigation permission. Unknown scan ends are not drawn as physical
boundaries. Additional green boundaries require independently observed terrain.
The preserved road vectors are shared physical boundaries, and are byte-for-byte
identical feature records from /base. Pedestrian coverage silhouettes are not
claimed to have been snapped to engineering road curves.
Building planes reuse the earlier covariance/height/Huber pipeline and bounded
frontage joins. The existing frontage envelope suppresses hidden parallel planes
only when observed ground establishes the exposed side; ambiguous orientation
retains both observations. Only observed first-floor vertical planes are exported; no roof
footprints or hidden rear walls are invented. The extra top-view building
prompt is diagnostic evidence only, not a required geometry gate. It returned
no buildings on the height-cut Smolensk images; facade geometry is independently
supported by Gaussian covariance and vertical span. False fronts and fragmented
runs remain possible and require visual assessment. The current geometry-only
frontage admission does not independently classify building versus fence/wall;
blue frontage candidates must not be treated as verified building identities.
All algorithms use the same metric thresholds on every scene. Input hashes,
source hashes, model pins, rejected paint candidates and scene results are
retained with each execution. Synthetic topology tests and structural validity
are separate from visual review. There is no independent position-accuracy or
complete-detection score. Do not interpret feature count as accuracy.
Render labels use an optional externally supplied /candidate/review-font.ttf
(Cyrillic-capable system font); no font is part of the algorithm. Review tiles
are automatically selected for class diversity and spacing and are not input
ROIs. No HTML output.
@@ -0,0 +1,150 @@
"""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))
# Detect paint in the detailed Gaussian ground image, then fit reusable geometry.
paint_candidates=[];rejected=[];cross_candidates=[]
road_dist=distance_transform_edt(~road)*cell
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));m=np.load(O/'evidence'/(name+'.npz'));veh=np.load(Path('/ortho/evidence')/(name+'.normal.npz'))['vehicle'];path=Path('/ortho/evidence')/(name+'.ground.png')
from PIL import Image
im=np.asarray(Image.open(path).convert('RGB'));size=im.shape[0];mpp=60/size;small=lambda a:cv2.resize(a.astype('float32'),(size,size),interpolation=cv2.INTER_LINEAR)
marking=small(m['road marking']);cross=small(m['crosswalk']);vehicles=cv2.dilate((small(veh)>.25).astype('uint8'),np.ones((max(3,int(.25/mpp)),)*2,np.uint8))>0
hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV);gray=cv2.cvtColor(im,cv2.COLOR_RGB2GRAY);contrast=gray.astype('float32')-cv2.GaussianBlur(gray.astype('float32'),(0,0),.35/mpp)
paint=((hsv[:,:,1]<70)&(gray>130)&(contrast>12))|((hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>55)&(gray>100)&(contrast>5))
candidate=paint&((marking>.3)|(cross>.3))&~vehicles
candidate=cv2.morphologyEx(candidate.astype('uint8'),cv2.MORPH_CLOSE,np.ones((max(3,int(.04/mpp)),)*2,np.uint8))
contours,hier=cv2.findContours(candidate,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE)
if hier is None:continue
def xy_native(p):return world((np.asarray(p)+.5)*1200/size-.5,g)
for i,c in enumerate(contours):
if hier[0,i,3]>=0 or cv2.contourArea(c)*mpp*mpp<.06:continue
rect=cv2.minAreaRect(c);short,long=sorted(rect[1]);short*=mpp;long*=mpp
if short<.045 or long<.35 or short>5:continue
ring=cv2.approxPolyDP(c,.035/mpp,True)[:,0];holes=[];j=hier[0,i,2]
while j>=0:
if cv2.contourArea(contours[j])*mpp*mpp>.03:holes.append(xy_native(cv2.approxPolyDP(contours[j],.035/mpp,True)[:,0]))
j=hier[0,j,0]
poly=shapely.make_valid(Polygon(xy_native(ring),holes))
if poly.geom_type!='Polygon':continue
coords=np.array(poly.exterior.coords);supported=np.mean(sample(road_dist,coords,low,high)<.75)
if supported<.5:continue
rxy=np.rint(rect[0]).astype(int);rxy=np.clip(rxy,0,size-1);is_cross=cross[rxy[1],rxy[0]]>.3
if is_cross and .18<short<1.2 and 1.0<long<12 and long/short>2 and poly.area/(short*long)>.55:
box=Polygon(xy_native(cv2.boxPoints(rect)));cross_candidates.append((box,dict(source_tile=name,subtype='crosswalk',method='parametric-rectangle')))
else:paint_candidates.append((poly,dict(source_tile=name,semantic_support=float(marking[rxy[1],rxy[0]]))))
m.close();print('PAINT',name,len(paint_candidates),len(cross_candidates),flush=True)
def dedup(records):
result=[]
for p,props in sorted(records,key=lambda x:-x[0].area):
if any(p.intersection(q).area/min(p.area,q.area)>.5 for q,_ in result):continue
result.append((p,props))
return result
cross_candidates=dedup(cross_candidates);paint_candidates=dedup(paint_candidates);paint=[]
# Group neighboring parallel stripes without fixture coordinates, then run existing joint fit.
obs=[]
for i,(p,props)in enumerate(cross_candidates):
points=np.asarray(p.exterior.coords);box,center,u,v=rectangle_info(points);obs.append(dict(id=str(i),points=points,box=box,center=center,u=u,v=v))
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=a['center']-b['center']
if abs(a['u']@b['u'])>np.cos(np.deg2rad(12))and abs(delta@a['u'])<1 and abs(delta@a['v'])<2:parent[root(i)]=root(j)
groups={}
for i in range(len(obs)):groups.setdefault(root(i),[]).append(i)
for ids in groups.values():
if len(ids)<3:rejected.extend(dict(kind='crosswalk',reason='insufficient-family-support')for i in ids);continue
fitted,rec=joint_rectangles([obs[i]for i in ids])
if not rec['optimizer_success']or rec['boundary_residual_p95_m']>.15:rejected.append(dict(kind='crosswalk',reason='joint-fit-disagreement',stripes=len(ids)));continue
for f,i in zip(fitted,ids):paint.append(feature(lift(Polygon(f['points'])),'road_marking',**cross_candidates[i][1],family_size=len(ids),fit_p95_m=f['fit_p95_m']))
for p,props in paint_candidates:
if any(p.intersection(q).area>.2*p.area for q,_ in cross_candidates):continue
fitted,method=regularize_paint(p)
if method=='parametric-paint-strip':
paint.append(feature(lift(fitted),'road_marking',subtype='linear_marking',method=method,**props));continue
rect=cv2.minAreaRect(np.asarray(p.exterior.coords,np.float32));a,b=sorted(rect[1]);iou=p.area/max(a*b,1e-8)
if a>.045 and a<.5 and b>.5 and b/a>3 and iou>.72 and not p.interiors:
paint.append(feature(lift(Polygon(cv2.boxPoints(rect))),'road_marking',subtype='linear_marking',method='rectangle-template',**props));continue
f=fit_symbol(p)
if f is not None:
fitted,iou,kind,recall,params=f;paint.append(feature(lift(fitted),'road_marking',subtype=kind,method='symbol-template',fit_iou=iou,fit_recall=recall,template_parameters=params,**props))
else:rejected.append(dict(kind='symbol',reason='no-template-admitted',geometry=mapping(p),**props))
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)
@@ -0,0 +1,22 @@
"""Independent artifact checks; report unresolved physical conflicts honestly."""
from pathlib import Path
import json,hashlib
import numpy as np,shapely
from shapely.geometry import shape,Point
O=Path('/out');B=Path('/base');d=json.loads((O/'full-map.json').read_text());b=json.loads((B/'whole-map.json').read_text())
roads=[f for f in d['features']if f['properties']['class']=='road_boundary'];assert roads==b['features']
facades=[f for f in d['features']if f['properties']['class']=='building_facade'];crossings=[]
for i,f in enumerate(facades):
a=shapely.force_2d(shape(f['geometry']))
for q in facades[:i]:
other=shapely.force_2d(shape(q['geometry']));p=a.intersection(other)
if p.geom_type=='Point' and .3<a.project(p)<a.length-.3 and .3<other.project(p)<other.length-.3:crossings.append([f['id'],q['id']])
polys=[shapely.force_2d(shape(f['geometry']))for f in d['features']if f['properties']['class']=='pedestrian_area'];overlaps=[]
for i,a in enumerate(polys):
for j,b in enumerate(polys[:i]):
area=a.intersection(b).area
if area>.01:overlaps.append(dict(i=i,j=j,area=area))
for f in d['features']:
g=shape(f['geometry']);assert g.is_valid and np.isfinite(shapely.get_coordinates(g,include_z=True)).all()
report=dict(road_features_exactly_preserved=True,facade_interior_crossings=crossings,pedestrian_polygon_overlaps=overlaps,topology_passed=not crossings and not overlaps,all_geometry_valid=True,source_unchanged=hashlib.sha256((B/'whole-map.json').read_bytes()).hexdigest()==d['road_baseline_sha256'],metric_accuracy_measured=False)
(O/'independent-audit.json').write_text(json.dumps(report,indent=2));print(json.dumps(report))
@@ -0,0 +1,27 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"files": {
"assemble_layers.py": "full_plan/assemble_layers.py",
"audit_layers.py": "full_plan/audit_layers.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",
"render_layers.py": "full_plan/render_layers.py",
"semantic_layers.py": "full_plan/semantic_layers.py",
"source_facade_planes.py": "full_plan/source_facade_planes.py",
"test_layers.py": "full_plan/test_layers.py",
"frontage_chains.py": "frontage_chains.py",
"paint_templates.py": "paint_templates.py",
"plan_acceptance.py": "plan_acceptance.py",
"plan_boundaries.py": "plan_boundaries.py",
"plan_coverage.py": "plan_coverage.py",
"plan_primitives.py": "plan_primitives.py",
"test_observed_plan.py": "test_observed_plan.py",
"test_plan_geometry.py": "test_plan_geometry.py",
"ortho_windows.py": "orthophoto/ortho_windows.py"
},
"root": "simulation/urban-plan-research",
"external_review_asset": "optional Cyrillic-capable review-font.ttf",
"reference_qualification": "full-plan-20261012",
"deployment": false
}
@@ -0,0 +1,38 @@
import numpy as np, cv2
from scipy.optimize import least_squares
from shapely.geometry import LineString
def rectangle_info(p):
rect=cv2.minAreaRect(np.asarray(p[:,:2],np.float32));box=cv2.boxPoints(rect).astype(float);edges=np.roll(box,-1,axis=0)-box;j=np.argmax(np.linalg.norm(edges,axis=1));u=edges[j]/np.linalg.norm(edges[j]);theta=np.arctan2(u[1],u[0]);u=np.array([np.cos(theta),np.sin(theta)]);v=np.array([-u[1],u[0]])
return box,np.mean(box,axis=0),u,v
def joint_rectangles(observations):
"""One family: parallel rectangles with shared width and aligned endpoints.
Optimise angle, end position/slope, length/length-slope, width and stripe
centres together. Sloping group ends are admitted without shearing a stripe.
The input remains a set of observations; no unsupported stripe is generated.
"""
angles=np.array([np.arctan2(o['u'][1],o['u'][0]) for o in observations]);theta=.5*np.arctan2(np.sin(2*angles).sum(),np.cos(2*angles).sum());origin=np.mean([o['center'] for o in observations],axis=0)
u=np.array([np.cos(theta),np.sin(theta)]);v=np.array([-u[1],u[0]])
# Use edge points rather than minimum rectangles as residual observations.
ps=[(o['points'][:,:2]-origin) for o in observations];uv=[np.column_stack([p@u,p@v]) for p in ps]
centers=np.array([np.mean([a[:,1].min(),a[:,1].max()]) for a in uv]);lo=np.array([np.quantile(a[:,0],.02) for a in uv]);hi=np.array([np.quantile(a[:,0],.98) for a in uv]);widths=np.array([a[:,1].max()-a[:,1].min() for a in uv])
line=np.polyfit(centers,lo,1);length=np.polyfit(centers,hi-lo,1);x0=np.r_[theta,line[1],line[0],length[1],length[0],np.median(widths),centers]
lower=x0-np.r_[np.deg2rad(8),.5,.2,.7,.2,.2,np.full(len(centers),.3)];upper=x0+np.r_[np.deg2rad(8),.5,.2,.7,.2,.2,np.full(len(centers),.3)];lower[3]=max(lower[3],.5);lower[5]=max(lower[5],.15)
def residual(x):
u=np.array([np.cos(x[0]),np.sin(x[0])]);v=np.array([-u[1],u[0]]);pieces=[]
for j,p in enumerate(ps):
t=p@u;s=p@v;vc=x[6+j];left=x[1]+x[2]*vc;right=left+x[3]+x[4]*vc
# Signed distance to the exact rectangle boundary; corners remain 90 degrees.
dx=np.maximum(left-t,t-right);dy=np.abs(s-vc)-x[5]/2
sdf=np.hypot(np.maximum(dx,0),np.maximum(dy,0))+np.minimum(np.maximum(dx,dy),0)
pieces.extend(sdf)
return np.array(pieces)
fit=least_squares(residual,x0,bounds=(lower,upper),loss='soft_l1',f_scale=.07,ftol=1e-6,xtol=1e-6,gtol=1e-6,max_nfev=300)
x=fit.x;u=np.array([np.cos(x[0]),np.sin(x[0])]);v=np.array([-u[1],u[0]]);result=[]
for j,o in enumerate(observations):
vc=x[6+j];lo=x[1]+x[2]*vc;hi=lo+x[3]+x[4]*vc;w=x[5]/2
uv=np.array([[lo,vc-w],[hi,vc-w],[hi,vc+w],[lo,vc+w],[lo,vc-w]])
p=origin+uv[:,0,None]*u+uv[:,1,None]*v;line=LineString(p)
result.append(dict(id=o['id'],points=p,fit_p95_m=float(np.quantile([line.distance(__import__('shapely').geometry.Point(q)) for q in o['points'][::3,:2]],.95))))
return result,dict(angle_degrees=float(np.rad2deg(x[0])),width_m=float(x[5]),stripes=len(result),optimizer_success=bool(fit.success),optimizer_status=int(fit.status),optimizer_evaluations=int(fit.nfev),worst_stripe_p95_m=max(r['fit_p95_m'] for r in result),parameters=x.tolist(),origin=origin.tolist(),boundary_residual_p95_m=float(np.quantile(np.abs(residual(x)),.95)))
@@ -0,0 +1,15 @@
import numpy as np
def resample(p,step=.12):
p=np.asarray(p,float);d=np.r_[0,np.cumsum(np.linalg.norm(np.diff(p[:,:2],axis=0),axis=1))];keep=np.r_[True,np.diff(d)>1e-7];p=p[keep];d=d[keep]
if len(p)<2:return p
t=np.linspace(0,d[-1],max(2,int(np.ceil(d[-1]/step))+1));return np.column_stack([np.interp(t,d,p[:,j]) for j in range(p.shape[1])])
def project(xy,g):
p=np.asarray(xy,float)
if p.shape[1]==2:p=np.c_[p,np.zeros(len(p))]
q=p@g['view'][:3,:3].T+g['view'][:3,3]
return q[:,:2]*np.diag(g['intrinsics'])[:2]+g['intrinsics'][:2,2]-.5
def world(uv,g):
xy=(np.asarray(uv)+.5-g['intrinsics'][:2,2])/np.diag(g['intrinsics'])[:2]
inverse=np.linalg.inv(g['view']);return (np.c_[xy,np.zeros(len(xy))]@inverse[:3,:3].T+inverse[:3,3])[:,:2]
@@ -0,0 +1,13 @@
from pathlib import Path
import numpy as np,json,hashlib
from shapely.geometry import mapping
from scipy.ndimage import map_coordinates
O=Path('/out');S=Path('/survey');B=Path('/base')
def feature(geom,cls,**props):
ident=hashlib.sha256((cls+geom.wkt).encode()).hexdigest()[:20]
return dict(type='Feature',id='plan-'+ident,geometry=mapping(geom),properties={'class':cls,'class_name':cls,'authority':'observation-only','route_permission':'unassigned','review_status':'unreviewed',**props})
def parts(geom,kind='Polygon'):
if geom.geom_type==kind:return [geom]
return [p for g in getattr(geom,'geoms',[])for p in parts(g,kind)]
def sample(a,xy,low,high,cell=.1,default=0):
xy=np.asarray(xy);return map_coordinates(a,[(high[1]-xy[:,1])/cell-.5,(xy[:,0]-low[0])/cell-.5],order=0,mode='constant',cval=default)
@@ -0,0 +1,64 @@
"""Evidence images from metric vectors, not AI-generated imagery."""
from pathlib import Path
import json,os
import numpy as np
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape,box
from fit_scene import project
from layer_common import B,O,S
D=json.loads((O/'full-map.json').read_text());v=json.loads((B/'viewer-data.json').read_text());low,high=np.asarray(v['bounds_xy']);res=v['resolution_m'];fontpath='/candidate/review-font.ttf'
try:font=ImageFont.truetype(fontpath,20)
except OSError:font=ImageFont.load_default()
colors={'road_boundary':(236,124,25),'pedestrian_boundary':(18,165,92),'building_facade':(0,151,224),'road_marking':(241,195,0)}
def draw_plan(im,projector,features,width=3):
rgba=im.convert('RGBA');fill=Image.new('RGBA',im.size);df=ImageDraw.Draw(fill)
for f in features:
if f['properties']['class']!='pedestrian_area':continue
rings=f['geometry']['coordinates']
df.polygon([tuple(q)for q in projector(rings[0])],fill=(25,193,120,58))
for ring in rings[1:]:df.polygon([tuple(q)for q in projector(ring)],fill=(0,0,0,0))
rgba=Image.alpha_composite(rgba,fill);draw=ImageDraw.Draw(rgba)
for cls in ['pedestrian_boundary','building_facade','road_marking','road_boundary']:
for f in features:
if f['properties']['class']!=cls:continue
rings=f['geometry']['coordinates']if f['geometry']['type']=='Polygon'else[f['geometry']['coordinates']]
for ring in rings:
pts=[tuple(q)for q in projector(ring)];draw.line(pts,fill=colors[cls],width=width,joint='curve')
return rgba.convert('RGB')
def title(im,name):
result=Image.new('RGB',(im.width,im.height+68),'white');result.paste(im,(0,68));d=ImageDraw.Draw(result);d.text((15,7),name,font=font,fill='#263640')
x=15
for text,clr in [('Дороги',(236,124,25)),('Пешеходные зоны',(18,165,92)),('Фасады',(0,151,224)),('Разметка',(200,155,0))]:
d.rectangle((x,42,x+20,57),fill=clr);d.text((x+29,37),text,font=font,fill='#263640');x+=int(d.textlength(text,font=font))+64
return result
world=lambda p:np.c_[(np.asarray(p)[:,0]-low[0])/res,(high[1]-np.asarray(p)[:,1])/res]
if (B/'whole-gaussians.jpg').exists():base=Image.open(B/'whole-gaussians.jpg').convert('RGB')
else:
width,height=v['size'];mosaic=np.full((height,width,3),255,np.uint8);weights=np.zeros((height,width),np.float32)
for tile in json.loads((S/'tile-index.json').read_text())['tiles']:
if tile['status']!='surveyed':continue
lo,hi=np.asarray(tile['bounds_xy']);tw,th=np.rint((hi-lo)/res).astype(int);x,y=np.rint([(lo[0]-low[0])/res,(high[1]-hi[1])/res]).astype(int)
im=np.asarray(Image.open(S/tile['id']/'top.png').convert('RGB').resize((tw,th),Image.Resampling.LANCZOS));g=np.load(S/tile['id']/'top.geometry.npz');alpha=np.asarray(Image.fromarray(g['alpha'].astype('float32')).resize((tw,th),Image.Resampling.BILINEAR));g.close()
yy,xx=np.mgrid[:th,:tw];score=(.01+np.minimum.reduce([xx+1,yy+1,tw-xx,th-yy])/max(tw,th))*np.clip(alpha,0,1);sl=np.s_[y:y+th,x:x+tw];take=score>weights[sl];mosaic[sl][take]=im[take];weights[sl][take]=score[take]
base=Image.fromarray(mosaic)
whole=draw_plan(base,world,D['features']);whole.save(O/'whole-overlay.jpg',quality=96)
plan=draw_plan(Image.new('RGB',base.size,'#f5f5f2'),world,D['features']);title(plan,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · инженерные слои').save(O/'whole-plan.jpg',quality=96)
preview=whole.copy();preview.thumbnail((2300,1500));title(preview,{'smolensk':'Смоленский бульвар','maroseyka':'Маросейка','pokrovka':'Покровка'}.get(os.environ['SCENE'],os.environ['SCENE'])+' · четыре слоя поверх гауссов').save(O/'overview.jpg',quality=96)
tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];scores=[];records=[]
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));domain=box(*tile['bounds_xy'][0],*tile['bounds_xy'][1]);features=[f for f in D['features']if shape(f['geometry']).intersects(domain)];counts={c:sum(f['properties']['class']==c for f in features)for c in ['building_facade','road_marking','pedestrian_area','road_boundary']}
image=Image.open(S/name/'top.png').convert('RGB');overlay=draw_plan(image,lambda p:project(p,g),features)
overlay.save(O/(name+'.overlay.jpg'),quality=95);image.save(O/(name+'.source.jpg'),quality=95)
score=sum(v>0 for v in counts.values())*100+min(counts['building_facade'],10)*3+min(counts['road_marking'],20)
scores.append((score,name));records.append(dict(tile=name,counts=counts))
chosen=[]
for score,name in sorted(scores,reverse=True):
if any(abs(int(name.split('-')[1])-int(n.split('-')[1]))<2 for n in chosen):continue
chosen.append(name)
if len(chosen)==3:break
sheet=Image.new('RGB',(1800,950*len(chosen)),'white');draw=ImageDraw.Draw(sheet)
for row,name in enumerate(chosen):
for col,suffix in enumerate(['source','overlay']):
im=Image.open(O/(name+'.'+suffix+'.jpg')).resize((900,900),Image.Resampling.LANCZOS);sheet.paste(im,(900*col,950*row+50));draw.text((900*col+12,950*row+12),name+' · '+('Гауссы'if col==0 else'Все слои'),font=font,fill='#263640')
sheet.save(O/'details.jpg',quality=96)
(O/'visual-manifest.json').write_text(json.dumps(dict(review_only_selection='automatic class diversity with spatial separation',selected=chosen,all_tiles=records,manual_processing_rois=[]),indent=2));print('PICTURES',chosen,flush=True)
@@ -0,0 +1,40 @@
"""Reusable all-tile SAM3 evidence pass for paint and observed structures."""
from pathlib import Path
import json,time,sys,gc,hashlib,os
import numpy as np,cv2,torch
from PIL import Image
sys.path.insert(0,'/release/simulation/ai-polygon/sam3-research')
from qualify import load_exact,sha
import sam3.model_builder as builder
from sam3.model.sam3_image_processor import Sam3Processor
from ortho_windows import windows,merge_instances
S=Path('/survey');E=Path('/ortho/evidence');O=Path('/out/evidence');O.mkdir(exist_ok=True,parents=True)
d=json.loads(Path('/release/simulation/ai-polygon/sam3-research/large-model.json').read_text());assets=Path('/assets')
for n,h in d['files'].items():assert sha(assets/n)==h
builder._load_checkpoint=load_exact;torch.set_num_threads(3);cv2.setNumThreads(3)
model=builder.build_sam3_image_model(bpe_path='/source/assets/bpe_simple_vocab_16e6.txt.gz',checkpoint_path=str(assets/next(iter(d['files']))),load_from_HF=False,enable_segmentation=True,enable_inst_interactivity=False,compile=False,text_encoder_type=d['text_encoder'],text_encoder_context_length=16,device='cuda')
processor=Sam3Processor(model,device='cuda',confidence_threshold=.3)
start=time.monotonic();records=[]
for tile in json.loads((S/'tile-index.json').read_text())['tiles']:
if tile['status']!='surveyed':continue
name=tile['id'];t=time.monotonic();result={};n=0;hashes={}
for kind,width,step,prompts in [('context',30,20,['building']),('ground',15,10,['road marking','crosswalk'])]:
path=E/(name+'.'+kind+'.png');hashes[kind]=sha(path);im=Image.open(path).convert('RGB')
g=np.load(S/name/'top.geometry.npz' if kind=='context'else E/(name+'.ground-dc.geometry.npz'));alpha=g['alpha'];g.close()
sums={p:np.zeros((1200,1200),np.float32)for p in prompts}
for x,y,w,h in windows(60,width,step):
x0,y0,x1,y1=np.rint(np.array([x,y,x+w,y+h])*20).astype(int)
if (alpha[y0:y1,x0:x1]>.7).mean()<.04:continue
box=tuple(np.rint(np.array([x,y,x+w,y+h])*im.width/60).astype(int));crop=im.crop(box);crop.thumbnail((1024,1024),Image.Resampling.LANCZOS)
with torch.inference_mode(),torch.autocast('cuda',dtype=torch.bfloat16):
state=processor.set_image(crop)
for prompt in prompts:
state=processor.set_text_prompt(prompt,state);masks=state['masks'].reshape(-1,crop.height,crop.width).cpu().numpy();scores=state['scores'].float().cpu().numpy().reshape(-1);plane=np.zeros((crop.height,crop.width),np.float32)
for mask,score in zip(masks,scores):np.maximum(plane,np.where(mask,score,0),out=plane)
merge_instances(sums[prompt],cv2.resize(plane,(x1-x0,y1-y0),interpolation=cv2.INTER_AREA),x0,y0)
n+=1
for p in prompts:sums[p][alpha<.5]=0;result[p]=sums[p].astype('float16')
im.close()
np.savez_compressed(O/(name+'.npz'),**result)
records.append(dict(tile=name,windows=n,seconds=time.monotonic()-t,inputs=hashes,sha256=sha(O/(name+'.npz')),pixels={p:int((a>.3).sum())for p,a in result.items()}))
(O/'report.json').write_text(json.dumps(dict(model=d,records=records,manual_rois=[],shared_policy=True,seconds=time.monotonic()-start),indent=2));print('LAYERS',json.dumps(records[-1]),flush=True);gc.collect()
@@ -0,0 +1,88 @@
"""Detect observed frontage planes scene-wide, independent of tile crops."""
from pathlib import Path
import json,time
import numpy as np,cv2,shapely
from scipy.spatial import cKDTree
from scipy.ndimage import map_coordinates
from shapely.geometry import LineString,shape
from fit_scene import resample
from layer_common import feature
S=Path('/survey');R=Path('/out')
def main():
begin=time.monotonic();field=np.load(R/'fields.npz');low,high=field['bounds'];cell=float(field['cell']);ground=field['z'];labels=field['labels'];h,w=labels.shape
def sample(a,xy,default=0):
return map_coordinates(a,[(high[1]-xy[:,1])/cell-.5,(xy[:,0]-low[0])/cell-.5],order=0,mode='constant',cval=default)
from plyfile import PlyData
from scipy.spatial.transform import Rotation
from scipy.ndimage import distance_transform_edt
import hashlib
road_core=distance_transform_edt(labels==1)*cell>.6
nearest=distance_transform_edt(~road_core,return_distances=False,return_indices=True)
ground=ground[nearest[0],nearest[1]];del nearest
first_tile=next(x['id'] for x in json.loads((S/'tile-index.json').read_text())['tiles'] if x['status']=='surveyed');job=json.loads((S/first_tile/'job.json').read_text());src=Path('/input')/job['source']['ply']
with src.open('rb') as stream:assert hashlib.file_digest(stream,'sha256').hexdigest()==job['source']['sha256']
raw=PlyData.read(src,mmap='r')['vertex'].data;T=np.array(job['source']['source_to_world']);near=distance_transform_edt(labels!=2)*cell;pts=[];counts={}
for first in range(0,len(raw),250000):
d=raw[first:first+250000];xyz=np.column_stack([d[n] for n in ['x','y','z']]);p=xyz@T[:3,:3].T+T[:3,3]
valid=((p[:,:2]>=low)&(p[:,:2]<=high)).all(1)&(d['opacity']>0)
z=sample(ground,p[:,:2],default=np.nan);valid&=(p[:,2]>z+.25)&(p[:,2]<z+2.1)&(sample(near,p[:,:2],default=100)<2.0)
d=d[valid];p=p[valid]
if not len(d):continue
scales=np.exp(np.column_stack([d['scale_'+str(i)] for i in range(3)]));order=np.argsort(scales,axis=1)
valid=(scales.max(1)<.65)&(np.min(scales,axis=1)<.12)&(np.min(scales,axis=1)<np.median(scales,axis=1)*.6)
d=d[valid];p=p[valid];axis=order[valid,0]
q=np.column_stack([d['rot_'+str(i)] for i in range(4)]);q/=np.maximum(np.linalg.norm(q,axis=1)[:,None],1e-9)
rot=Rotation.from_quat(q[:,[1,2,3,0]]).as_matrix();normal=rot[np.arange(len(q)),:,axis]@T[:3,:3].T
p=p[np.abs(normal[:,2])<.3];pts.append(p)
p=np.concatenate(pts);_,ids=np.unique(np.rint(p/.075).astype('int32'),axis=0,return_index=True);p=p[ids]
print('source Gaussians',len(raw),'accepted anisotropic vertical Gaussians',len(p),flush=True)
uv=np.c_[(p[:,0]-low[0])/cell,(high[1]-p[:,1])/cell].astype(int);inside=(uv[:,0]>=0)&(uv[:,0]<w)&(uv[:,1]>=0)&(uv[:,1]<h);p=p[inside];uv=uv[inside]
count=np.zeros(h*w,'int32');zmin=np.full(h*w,np.inf,'float32');zmax=np.full(h*w,-np.inf,'float32');linear=uv[:,1]*w+uv[:,0]
np.add.at(count,linear,1);np.minimum.at(zmin,linear,p[:,2]);np.maximum.at(zmax,linear,p[:,2])
wall=((count>=3)&(zmax-zmin>=.75)).reshape(h,w).astype('uint8')*255
lines=cv2.HoughLinesP(wall,1,np.pi/720,threshold=18,minLineLength=25,maxLineGap=15)
if lines is None:raise ValueError('No frontage planes supported')
seeds=sorted(lines[:,0],key=lambda l:-np.hypot(l[2]-l[0],l[3]-l[1]))
tree=cKDTree(p[:,:2]);used=np.zeros(len(p),bool);features=[];rejected=0
for seed in seeds:
xy=np.array([[low[0]+(seed[0]+.5)*cell,high[1]-(seed[1]+.5)*cell],[low[0]+(seed[2]+.5)*cell,high[1]-(seed[3]+.5)*cell]])
near=tree.query_ball_point(resample(xy,.3),.4);ids=np.unique(np.concatenate([x for x in near if len(x)])) if any(len(x) for x in near) else np.empty(0,int)
ids=ids[~used[ids]]
if len(ids)<60:continue
line=cv2.fitLine(p[ids,:2].astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=line[:2].astype(float);u/=np.linalg.norm(u);origin=line[2:].astype(float);n=np.array([-u[1],u[0]])
distance=abs((p[ids,:2]-origin)@n);ids=ids[distance<.22]
if len(ids)<60:continue
t=(p[ids,:2]-origin)@u;order=np.argsort(t);ids=ids[order];t=t[order]
for run in np.split(np.arange(len(ids)),np.flatnonzero(np.diff(t)>1.5)+1):
local=ids[run]
if len(local)<60:continue
a,b=np.quantile(t[run],[.005,.995]);q=origin+np.array([a,b])[:,None]*u
if b-a<2.5 or np.ptp(np.quantile(p[local,2],[.05,.95]))<.85:continue
check=resample(q,.2);support=np.zeros(len(check),bool)
for distance in [.6,1.2,1.8]:
plus=sample(labels,check+n*distance);minus=sample(labels,check-n*distance)
support|=((plus>0)&(minus==0))|((plus==0)&(minus>0))
if support.mean()<.65:rejected+=1;continue
geom=LineString(q)
# Keep the best-supported plane once, not every Hough detection.
redundant=any(geom.intersection(shapely.force_2d(shape(f['geometry'])).buffer(.3,cap_style=2)).length>.65*geom.length for f in features)
if redundant:continue
xyz=np.c_[q,sample(ground,q)]
features.append(feature(LineString(xyz),'building_facade',method='global-gaussian-surface-plane',point_support=len(local),vertical_span_m=float(np.ptp(np.quantile(p[local,2],[.05,.95]))),frontage_support=float(support.mean()),fit_residual_p95_m=float(np.quantile(abs((p[local,:2]-origin)@n),.95)),closed_footprint=False))
used[local]=True
# Remove mutually crossing alternatives; a frontage map cannot retain an X.
keep=[];conflicts=[]
for f in sorted(features,key=lambda f:-f['properties']['point_support']):
l=shapely.force_2d(shape(f['geometry']));bad=False
for other in keep:
b=shapely.force_2d(shape(other['geometry']));x=l.intersection(b)
if x.geom_type=='Point' and .3<l.project(x)<l.length-.3 and .3<b.project(x)<b.length-.3:bad=True;conflicts.append(f['id']);break
if not bad:keep.append(f)
doc=json.loads((R/'map.base.json').read_text());doc['features']+=keep
(R/'map.source-facades-v3.json').write_text(json.dumps(doc,allow_nan=False))
report=dict(seconds=time.monotonic()-begin,input_points=len(p),hough_proposals=len(seeds),facades=len(keep),total_length_m=sum(shape(f['geometry']).length for f in keep),rejected_frontages=rejected,conflicting_planes=conflicts,manual_geometry=False,closed_footprints_invented=0)
(R/'source-facade-report-v3.json').write_text(json.dumps(report,indent=2));print(json.dumps(report),flush=True)
if __name__=='__main__':main()
@@ -0,0 +1,6 @@
import unittest,json
from pathlib import Path
from shapely.geometry import shape
suite=unittest.defaultTestLoader.loadTestsFromNames(['test_observed_plan','test_plan_geometry']);result=unittest.TextTestRunner(verbosity=2).run(suite)
assert result.wasSuccessful()
Path('/out/tests.json').write_text(json.dumps(dict(tests=result.testsRun,passed=result.wasSuccessful())))