Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
188 lines
11 KiB
Python
188 lines
11 KiB
Python
"""Conservative primitive fitting and endpoint-graph completion of accepted seeds.
|
|
|
|
All distances are metric. SciPy splines/HiGHS and GEOS implement interpolation,
|
|
joint endpoint assignment and geometric checks. No scene-specific coordinates.
|
|
"""
|
|
from dataclasses import dataclass,asdict,replace
|
|
import numpy as np,shapely
|
|
from shapely.geometry import LineString
|
|
from scipy.spatial import cKDTree
|
|
from scipy.interpolate import CubicHermiteSpline
|
|
from scipy.optimize import milp,Bounds,LinearConstraint
|
|
from scipy.sparse import coo_matrix
|
|
from object_solver import fit_chain,sample_chain,Policy,stations
|
|
|
|
@dataclass(frozen=True)
|
|
class ContinuationPolicy:
|
|
sample_m:float=.4
|
|
max_gap_m:float=18.
|
|
max_heading_degrees:float=65.
|
|
min_support_m:float=2.
|
|
fit_max_deviation_m:float=.45
|
|
fit_residual_m:float=.24
|
|
unresolved_cost:float=2.5
|
|
maximum_terminal_revision_m:float=6.
|
|
|
|
def observed_crossing_length(curve,road_at,alpha_at,vehicle_at,step=.2):
|
|
"""Longest unoccluded road strip crossed by a proposed boundary.
|
|
|
|
An absolute local run matters: a narrow side street must not be diluted by
|
|
the length of a much longer proposed bridge. Vehicle occlusion is unknown,
|
|
not evidence for an open transport corridor.
|
|
"""
|
|
p=sample_chain(np.asarray(curve)[:,:2],step)
|
|
t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8)
|
|
n=np.c_[-t[:,1],t[:,0]]
|
|
exposed=np.ones(len(p),bool)
|
|
for offset in [-1.,0.,1.]:
|
|
q=p+offset*n
|
|
exposed&=(road_at(q)>.65)&(alpha_at(q)>.7)&(vehicle_at(q)<.25)
|
|
longest=run=0.
|
|
for visible in exposed:
|
|
run=run+step if visible else 0.
|
|
longest=max(longest,run)
|
|
return float(longest)
|
|
|
|
def regularize(points,policy=ContinuationPolicy()):
|
|
raw=np.asarray(points,float);p=sample_chain(raw[:,:2],policy.sample_m)
|
|
if len(p)<5 or LineString(p).is_ring:return raw,None
|
|
fit=fit_chain(p,np.ones(len(p)),replace(Policy(),residual_scale_m=policy.fit_residual_m,reliable_residual_limit_m=policy.fit_max_deviation_m),complexity_scale=1.3)
|
|
if fit is None:return raw,None
|
|
q=fit['points'].copy();q[[0,-1]]=raw[[0,-1],:2]
|
|
g=LineString(q);old=LineString(raw[:,:2]);deviation=float(shapely.hausdorff_distance(g,old,densify=.2))
|
|
if not g.is_simple or deviation>policy.fit_max_deviation_m or g.length>old.length*1.01:return raw,None
|
|
# Preserve Z only by the source station; this is schematic XY regularization.
|
|
if raw.shape[1]>2:
|
|
st=np.array(shapely.line_locate_point(old,shapely.points(q)));old_s=stations(raw[:,:2]);q=np.c_[q,np.interp(st,old_s,raw[:,2])]
|
|
return q,dict(primitives=fit['primitives'],maximum_change_m=deviation)
|
|
|
|
def endpoint_tangents(p,end):
|
|
q=sample_chain(np.asarray(p)[::1 if end==0 else -1,:2],.25)
|
|
s=stations(q);result=[]
|
|
for reach in [1.5,3.,6.]:
|
|
sub=q[s<=reach]
|
|
if len(sub)<5:continue
|
|
origin=sub.mean(0);_,_,v=np.linalg.svd(sub-origin,full_matrices=False);u=v[0]
|
|
if u@(sub[0]-sub[-1])<0:u=-u
|
|
n=np.array([-u[1],u[0]]);error=float(np.quantile(abs((sub-origin)@n),.9))
|
|
if error>.25:continue
|
|
if not any(u@x[0]>.995 for x in result):result.append((u,error,reach))
|
|
return result
|
|
|
|
def connect(records,evaluate=None,policy=ContinuationPolicy()):
|
|
"""Return joined chains plus all admissible/rejected endpoint alternatives.
|
|
|
|
evaluate(curve, left_arm, right_arm) provides observation evidence and rejection.
|
|
Endpoint membership is globally optimized; no assumed contour walk is used.
|
|
"""
|
|
ends=[];checks=[];options=[]
|
|
for i,r in enumerate(records):
|
|
p=np.asarray(r['points'])
|
|
if LineString(p[:,:2]).is_ring:continue
|
|
for e in [0,1]:
|
|
if r.get('reasons',[None,None])[e]in ['scan-limit','known-opening','survey-exterior']:continue
|
|
# A seam may end in an erroneous hook. Propose alternatives from
|
|
# earlier supported stations, with an explicit cost for removed tail.
|
|
s=stations(p[:,:2]);length=s[-1]
|
|
for trim in [0.,1.,2.,4.,6.]:
|
|
if trim>policy.maximum_terminal_revision_m or length-trim<max(2.,2*trim):continue
|
|
if trim==0:sub=p
|
|
else:
|
|
cut=int(np.argmin(abs(s-(trim if e==0 else length-trim))))
|
|
sub=p[cut:]if e==0 else p[:cut+1]
|
|
ts=endpoint_tangents(sub,e)
|
|
if ts:ends.append(dict(record=i,end=e,slot=2*i+e,point=sub[0 if e==0 else -1],tangents=ts,trim_m=trim,sub=sub))
|
|
if not ends:return records,dict(candidates=[],selected=[],reason='no-endpoint-support')
|
|
geometries=[LineString(r['points'][:,:2])for r in records]
|
|
pairs=sorted(cKDTree([e['point'][:2]for e in ends]).query_pairs(policy.max_gap_m))
|
|
for a,b in pairs:
|
|
ea,eb=ends[a],ends[b];i,j=ea['record'],eb['record']
|
|
if i==j:continue
|
|
ra,rb=records[i],records[j]
|
|
if ra.get('class')!=rb.get('class'):continue
|
|
pa,pb=ea['point'],eb['point'];gap=np.linalg.norm(pb[:2]-pa[:2]);check=dict(source_ids=[ra['id'],rb['id']],ends=[ea['end'],eb['end']],gap_m=float(gap),status='heading')
|
|
checks.append(check)
|
|
if gap<.03:continue
|
|
direction=(pb[:2]-pa[:2])/gap;curve_options=[]
|
|
left=ea['sub'][::1 if ea['end']==1 else -1];right=eb['sub'][::1 if eb['end']==0 else -1]
|
|
for ta,err_a,reach_a in ea['tangents']:
|
|
for tb,err_b,reach_b in eb['tangents']:
|
|
cos=np.cos(np.deg2rad(policy.max_heading_degrees))
|
|
if ta@direction<cos or -tb@direction<cos or ta@(-tb)<-.2:continue
|
|
if len(pa)>2 and abs(pa[2]-pb[2])>.5+.12*gap:continue
|
|
for factor in [.35,.7,1.]:
|
|
t=np.linspace(0,1,max(5,int(gap/.2)+1))
|
|
xy=CubicHermiteSpline([0,1],np.stack([pa[:2],pb[:2]]),np.stack([ta,-tb])*gap*factor)(t)
|
|
curve=np.c_[xy,pa[2]+t*(pb[2]-pa[2])]if len(pa)>2 else xy
|
|
line=LineString(xy);check['status']='shape'
|
|
if not line.is_simple or line.length>gap*1.2:continue
|
|
if not LineString(np.vstack([left[:,:2],xy[1:],right[1:,:2]])).is_simple:continue
|
|
if any(line.intersects(g)for k,g in enumerate(geometries)if k not in [i,j]):continue
|
|
check['status']='evidence'
|
|
ev=evaluate(curve,left,right)if evaluate else dict(allowed=True,reward=0.)
|
|
if not ev['allowed']:
|
|
check['rejection']=ev.get('reason');continue
|
|
bend=float(np.sum(np.linalg.norm(np.diff(np.diff(xy,axis=0),axis=0),axis=1)))
|
|
cost=gap/policy.max_gap_m+1.3*(2-ta@direction+tb@direction)+.2*bend-.7*ev.get('reward',0.)+.18*(ea['trim_m']+eb['trim_m'])
|
|
curve_options.append(dict(a=a,b=b,i=i,j=j,slots=[ea['slot'],eb['slot']],curve=curve,cost=float(cost),gap_m=float(gap),evidence=ev,tangent_reaches=[reach_a,reach_b]))
|
|
if not curve_options:continue
|
|
# Keep genuinely different geometric options, with the same data objective.
|
|
kept=[]
|
|
for c in sorted(curve_options,key=lambda x:x['cost']):
|
|
if any(LineString(c['curve'][:,:2]).hausdorff_distance(LineString(k['curve'][:,:2]))<.12 for k in kept):continue
|
|
kept.append(c)
|
|
if len(kept)==3:break
|
|
check.update(status='candidate',alternatives=len(kept));options.extend(kept)
|
|
if not options:return records,dict(candidates=checks,selected=[],reason='no-admissible-continuation')
|
|
rows=[];cols=[];vals=[];lb=[];ub=[]
|
|
slots=sorted(set(e['slot']for e in ends))
|
|
for slot_index,endpoint in enumerate(slots):
|
|
row=len(lb);lb.append(1);ub.append(1)
|
|
for k,o in enumerate(options):
|
|
if endpoint in o['slots']:rows.append(row);cols.append(k);vals.append(1)
|
|
rows.append(row);cols.append(len(options)+slot_index);vals.append(1)
|
|
for i,a in enumerate(options):
|
|
ga=LineString(a['curve'][:,:2])
|
|
for j,b in enumerate(options[:i]):
|
|
if set(a['slots'])&set(b['slots']):continue
|
|
if ga.intersects(LineString(b['curve'][:,:2])):
|
|
row=len(lb);lb.append(-np.inf);ub.append(1);rows.extend([row,row]);cols.extend([i,j]);vals.extend([1,1])
|
|
costs=[x['cost']for x in options]+[policy.unresolved_cost]*len(slots)
|
|
A=coo_matrix((vals,(rows,cols)),shape=(len(lb),len(costs))).tocsc()
|
|
fit=milp(costs,integrality=np.ones(len(costs)),bounds=Bounds(0,1),constraints=LinearConstraint(A,lb,ub),options={'time_limit':30,'mip_rel_gap':.001})
|
|
if fit.x is None:raise RuntimeError(fit.message)
|
|
chosen=[options[i]for i in np.flatnonzero(fit.x[:len(options)]>.5)]
|
|
# No inferred road loop closure. Preserve the lowest cost forest explicitly.
|
|
parent=list(range(len(records)));links={};selected=[];cycles=[];trimmed={}
|
|
def root(i):
|
|
while parent[i]!=i:i=parent[i]
|
|
return i
|
|
for c in sorted(chosen,key=lambda x:x['cost']):
|
|
i,j=c['i'],c['j']
|
|
if root(i)==root(j):cycles.append([records[i]['id'],records[j]['id']]);continue
|
|
parent[root(i)]=root(j);ea,eb=ends[c['a']],ends[c['b']]
|
|
links[i,ea['end']]=(j,eb['end'],c['curve']);links[j,eb['end']]=(i,ea['end'],c['curve'][::-1]);selected.append(c)
|
|
trimmed[i,ea['end']]=ea['point'];trimmed[j,eb['end']]=eb['point']
|
|
out=[];seen=set();reverted=set()
|
|
for seed in range(len(records)):
|
|
if seed in seen:continue
|
|
members=[i for i in range(len(records))if root(i)==root(seed)]
|
|
start=next(((i,e)for i in members for e in [0,1]if(i,e)not in links),None)
|
|
if start is None:
|
|
out.extend(records[i]for i in members);seen.update(members);continue
|
|
i,entry=start;pts=[];source_ids=[];spans=[]
|
|
while i not in seen:
|
|
seen.add(i);rec=records[i];p=rec['points']
|
|
lo=int(np.argmin(np.linalg.norm(p[:,:2]-trimmed[i,0][:2],axis=1)))if(i,0)in trimmed else 0
|
|
hi=int(np.argmin(np.linalg.norm(p[:,:2]-trimmed[i,1][:2],axis=1)))if(i,1)in trimmed else len(p)-1
|
|
assert lo<hi,(i,lo,hi)
|
|
p=p[lo:hi+1][::1 if entry==0 else -1]
|
|
pts.extend(p if not pts else p[1:]);source_ids.extend(rec.get('source_ids',[rec['id']]));spans.extend(rec.get('spans',[]))
|
|
if(i,1-entry)not in links:break
|
|
j,other,curve=links[i,1-entry];spans.append(curve.tolist());pts.extend(curve[1:]);i,entry=j,other
|
|
if not LineString(np.asarray(pts)[:,:2]).is_simple:
|
|
out.extend(records[j]for j in members);reverted.update(members)
|
|
else:out.append(dict(id='joined-'+'-'.join(source_ids),points=np.asarray(pts),source_ids=source_ids,spans=spans,**{'class':records[seed]['class']}))
|
|
assert all(LineString(r['points'][:,:2]).is_simple for r in out)
|
|
return out,dict(candidates=checks,selected=[dict(source_ids=[records[x['i']]['id'],records[x['j']]['id']],gap_m=x['gap_m'],terminal_revision_m=[ends[x['a']]['trim_m'],ends[x['b']]['trim_m']],coordinates=x['curve'].tolist(),evidence=x['evidence'],cost=x['cost'])for x in selected if x['i']not in reverted and x['j']not in reverted],reverted_parent_ids=[records[i]['id']for i in sorted(reverted)],cycles_rejected=cycles,solver_status=int(fit.status),solver_message=fit.message)
|