Files
NODEDC_MISSION_CORE/simulation/urban-plan-research/systematic/crossing_fit.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

59 lines
4.3 KiB
Python

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 boundary_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)
# Each primary observation is an oriented rectangle. Associate its four
# corners with its measured end/side once, before optimization. A nearest-edge
# SDF switches branches at every corner and can stall despite a tiny residual.
# The original boundary-distance gate remains the independent final metric.
fit_points=[];assignments=[]
for observation,p in zip(observations,ps):
q=p[:-1] if len(p)>1 and np.array_equal(p[0],p[-1]) else p
if len(q)!=4:raise ValueError('Crossing fit expects four measured rectangle corners')
axis=np.asarray(observation['u'],float)
if axis@u<0:axis=-axis
normal=np.array([-axis[1],axis[0]])
t=q@axis;s=q@normal
fit_points.append(q);assignments.append((t>(t.min()+t.max())/2,s>(s.min()+s.max())/2))
def residual(x):
axis=np.array([np.cos(x[0]),np.sin(x[0])]);normal=np.array([-axis[1],axis[0]])
pieces=[]
for j,(p,(right_side,upper_side))in enumerate(zip(fit_points,assignments)):
vc=x[6+j];left=x[1]+x[2]*vc;right=left+x[3]+x[4]*vc
pieces.extend(p@axis-np.where(right_side,right,left))
pieces.extend(p@normal-(vc+np.where(upper_side,x[5]/2,-x[5]/2)))
return np.asarray(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(boundary_residual(x)),.95)))