Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/plan_coverage.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
4.3 KiB
Python

"""Shared semantic-area geometry for offline urban plans.
Classes are 0 unknown, 1 carriageway, 2 pedestrian area. Pixel costs are model
observations, not calibrated safety probabilities. All metric tolerances are
engineering defaults; they are not a survey-accuracy claim.
"""
import numpy as np
import cv2
import shapely
from shapely.geometry import shape
from shapely.ops import unary_union, polygonize
from rasterio.features import shapes
from affine import Affine
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import maximum_flow, breadth_first_order
CELL = .1
def grid_edges(rgb,weight):
h,w=rgb.shape[:2];ids=np.arange(h*w).reshape(h,w);us=[];vs=[];ws=[]
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY).astype(float)
gray=cv2.GaussianBlur(gray,(0,0),2)
for dy,dx,scale in [(0,1,1),(1,0,1),(1,1,.7071),(1,-1,.7071)]:
ya=slice(0,h-dy);yb=slice(dy,h)
xa=slice(max(0,-dx),min(w,w-dx));xb=slice(max(0,dx),min(w,w+dx))
us.append(ids[ya,xa].ravel());vs.append(ids[yb,xb].ravel())
diff=np.abs(gray[ya,xa]-gray[yb,xb]).ravel()
ws.append(weight*scale*(.4+.6*np.exp(-diff**2/(2*12**2))))
return np.concatenate(us),np.concatenate(vs),np.concatenate(ws)
def energy(labels,costs,edges):
l=labels.ravel();u,v,w=edges
return float(costs.reshape(3,-1)[l,np.arange(len(l))].sum()+np.sum(w*(l[u]!=l[v])))
def potts(labels,costs,rgb,weight=3,iterations=2):
labels=np.asarray(labels)
costs=np.asarray(costs)
if labels.ndim != 2 or costs.shape != (3,*labels.shape) or rgb.shape != (*labels.shape,3):
raise ValueError("Labels, unary costs and RGB must have matching grids")
if not np.isfinite(costs).all() or not np.isfinite(rgb).all() or costs.min()<0 or not np.isin(labels,[0,1,2]).all():
raise ValueError("Invalid semantic-area observations")
if weight<0 or iterations<1 or iterations>10:
raise ValueError("Invalid optimisation limits")
labels=labels.astype('uint8',copy=True);h,w=labels.shape;n=h*w;ids=np.arange(n);edges=grid_edges(rgb,weight);a,b,pair=edges
trace=[energy(labels,costs,edges)]
for cycle in range(iterations):
for alpha in [0,1,2]:
l=labels.ravel();D=costs.reshape(3,-1);u0=D[l,ids].astype(float);u1=D[alpha].astype(float).copy()
e00=pair*(l[a]!=l[b]);e01=pair*(l[a]!=alpha);e10=pair*(alpha!=l[b])
c=(e01+e10-e00)/2
np.add.at(u1,a,e10-e00-c);np.add.at(u1,b,e01-e00-c)
shift=np.minimum(u0,u1);u0-=shift;u1-=shift
row=np.r_[np.full(n,n),ids,a,b];col=np.r_[ids,np.full(n,n+1),b,a]
cap=np.maximum(np.rint(np.r_[u0,u1,c,c]*1000),0).astype('int64')
graph=coo_matrix((cap,(row,col)),shape=(n+2,n+2)).tocsr();graph.eliminate_zeros()
flow=maximum_flow(graph,n,n+1);res=graph-flow.flow;res.data=(res.data>0).astype('int64');res.eliminate_zeros()
reachable=breadth_first_order(res,n,directed=True,return_predecessors=False);reachable=reachable[reachable<n]
trial=labels.copy().ravel();trial[reachable]=alpha;trial=trial.reshape(h,w)
value=energy(trial,costs,edges)
if value<trace[-1]:labels=trial;trace.append(value)
return labels,trace
def vectorize(labels,tolerance=.3,transform=None):
transform=transform or Affine(CELL,0,0,0,-CELL,labels.shape[0]*CELL)
polygons=[];classes=[]
for geom,cls in shapes(labels,transform=transform,connectivity=4):
p=shapely.make_valid(shape(geom))
pieces=[p] if p.geom_type=='Polygon' else [g for g in p.geoms if g.geom_type=='Polygon']
polygons.extend(pieces);classes.extend([int(cls)]*len(pieces))
# Exact coverage first, simplification second. No class is independently rounded.
if not shapely.coverage_is_valid(polygons):
# Explicitly node all class interfaces, including raster T-junctions.
network=unary_union([shapely.set_precision(p,0.00001).boundary for p in polygons])
polygons=list(polygonize(network));classes=[];inv=~transform
for p in polygons:
xy=p.representative_point();c,r=inv*(xy.x,xy.y);classes.append(int(labels[min(labels.shape[0]-1,max(0,int(r))),min(labels.shape[1]-1,max(0,int(c)))]))
assert shapely.coverage_is_valid(polygons)
result=shapely.coverage_simplify(polygons,tolerance=tolerance,simplify_boundary=False)
assert shapely.coverage_is_valid(result)
return result,classes