"""Evidence-guided curb refinement from normal profiles and clamped B-splines. Review bounds select where to inspect; they do not specify target vertices. A smooth evidence path is followed before the engineering curve is fitted. """ import numpy as np from scipy.interpolate import BSpline from shapely.geometry import LineString,Point from shapely.ops import substring from plan_continuity import resample,distances from plan_junctions import unit def smooth_profile_path(scores,weights,offsets,step,prior=.025,transition=.14): scores=np.asarray(scores,float);weights=np.asarray(weights,float);offsets=np.asarray(offsets,float) if scores.shape!=weights.shape or scores.shape[1]!=len(offsets) or not np.isfinite(scores).all():raise ValueError('finite rectangular profiles required') emission=-scores*weights+prior*offsets[None,:]**2 # A common station weight prevents missing data favouring a different ray. zero=int(np.argmin(abs(offsets)));cost=emission[0].copy()+20*offsets**2;back=[] change=transition*((offsets[:,None]-offsets[None,:])/step)**2 for row in emission[1:]: allcost=cost[:,None]+change;previous=np.argmin(allcost,axis=0);back.append(previous);cost=row+allcost[previous,np.arange(len(offsets))] j=int(np.argmin(cost+20*offsets**2));indices=[j] for previous in back[::-1]:j=int(previous[j]);indices.append(j) indices=np.asarray(indices[::-1]);return offsets[indices],indices def clamped_spline(reference,target,weights,spacing=3.,smoothness=.6): """Cubic fit with exactly pinned endpoint positions and endpoint tangents.""" reference=np.asarray(reference,float);target=np.asarray(target,float);t=distances(reference);length=t[-1] if length<3:raise ValueError('Insufficient extent for a constrained spline') internal=np.linspace(0,length,max(2,int(np.ceil(length/spacing))+1))[1:-1] knots=np.r_[[0.]*4,internal,[length]*4];n=len(knots)-4;basis=BSpline(knots,np.eye(n),3);B=basis(t);D=basis.derivative(2)(np.linspace(0,length,len(t))) control=np.zeros((n,2));control[0]=reference[0,:2];control[-1]=reference[-1,:2] control[1]=control[0]+unit(reference[1,:2]-reference[0,:2])*(knots[4]/3) control[-2]=control[-1]-unit(reference[-1,:2]-reference[-2,:2])*((length-knots[-5])/3) fixed=np.array([0,1,n-2,n-1]);free=np.arange(2,n-2);w=np.clip(weights,.03,1) if not len(free):raise ValueError('Spline requires interior degrees of freedom') for _ in range(4): W=np.sqrt(w)[:,None];A=np.vstack([B[:,free]*W,np.sqrt(smoothness)*D[:,free]]) y=np.vstack([(target[:,:2]-B[:,fixed]@control[fixed])*W,-np.sqrt(smoothness)*D[:,fixed]@control[fixed]]) control[free]=np.linalg.lstsq(A,y,rcond=None)[0] residual=np.linalg.norm(B@control-target[:,:2],axis=1);w=np.clip(weights,.03,1)*np.minimum(1.,.25/np.maximum(residual,1e-6)) tt=np.linspace(0,length,max(4,int(np.ceil(length/.1))+1));xy=basis(tt)@control result=xy if reference.shape[1]==2 else np.c_[xy,np.interp(tt,t,reference[:,2])] result[[0,-1]]=reference[[0,-1]] if not LineString(result[:,:2]).is_simple:raise ValueError('Refinement self-intersects') return result,dict(degree=3,knots=knots.tolist(),control_xy=control.tolist(),weighted_rms_m=float(np.sqrt(np.average(residual**2,weights=np.clip(weights,.03,1))))) def refine_profile(points,field,band=2.,spacing=3.,smoothness=.6): p=resample(points,.3);t=distances(p);tangent=np.gradient(p[:,:2],axis=0);tangent/=np.maximum(np.linalg.norm(tangent,axis=1)[:,None],1e-9);normal=np.c_[-tangent[:,1],tangent[:,0]] sign=np.sign(np.mean(field.material(p[:,:2]+normal)-field.material(p[:,:2]-normal)))or 1 offsets=np.linspace(-band,band,int(band/.04)*2+1);rays=p[:,None,:2]+offsets[None,:,None]*normal[:,None,:] score,weight=field.score(rays.reshape(-1,2),np.repeat(normal,len(offsets),axis=0),sign) score=score.reshape(len(p),-1);weight=weight.reshape(len(p),-1) station_weight=np.quantile(weight,.6,axis=1);weight=np.minimum(weight,station_weight[:,None]) chosen,indices=smooth_profile_path(score,weight,offsets,float(np.mean(np.diff(t)))) target=p[:,:2]+chosen[:,None]*normal selected_weight=weight[np.arange(len(p)),indices];curve,model=clamped_spline(p,target,selected_weight,spacing,smoothness) deviation=LineString(curve[:,:2]).hausdorff_distance(LineString(p[:,:2])) if deviation>band+.1:raise ValueError('Refinement escaped its displacement band') model.update(max_displacement_m=float(deviation),median_profile_offset_m=float(np.median(chosen)),road_sign=float(sign),mean_sample_weight=float(np.mean(selected_weight)),profile_support=float(np.mean(selected_weight>.3))) return curve,model,dict(stations_m=t.tolist(),offsets_m=chosen.tolist(),target_xy=target.tolist(),weights=selected_weight.tolist()) def replace_interval(points,start,end,replacement): line=LineString(points);replacement=np.asarray(replacement,float) if not 0<=start1e-6:parts.extend(substring(line,0,start).coords) parts.extend(replacement if not parts else replacement[1:]) if end