"""Offline schematic curb completion using FITPACK, Hermite splines and GEOS. Source observations are immutable. Added spans remain explicitly inferred. No extrapolation, loop closure or route authority is produced. This pass assumes its input chains already identify curbs; it is not a semantic curb detector. """ from copy import deepcopy from dataclasses import dataclass, asdict import hashlib import warnings import numpy as np from scipy.interpolate import splprep, splev, CubicHermiteSpline from scipy.spatial import cKDTree from shapely.geometry import LineString, Point, shape, mapping @dataclass(frozen=True) class Policy: max_gap_m: float = 6.0 fit_tolerance_m: float = .30 min_chain_m: float = 1.5 sample_m: float = .15 max_heading_degrees: float = 55.0 ambiguity_margin: float = .20 # Cubic Bezier handle length; None preserves the existing short-gap fit. max_tangent_handle_m: float | None = None def distances(p): return np.r_[0., np.cumsum(np.linalg.norm(np.diff(p[:, :2], axis=0), axis=1))] def resample(p, step=.15): p = np.asarray(p, float) d = distances(p) keep = np.r_[True, np.diff(d) > 1e-8] p, d = p[keep], 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 regularize(p, policy): """Pin endpoints and structural corners; bound deviation from input, in XY.""" reference = LineString(p[:, :2]) if reference.is_ring: return p.copy() skeleton = np.asarray(reference.simplify(policy.fit_tolerance_m).coords) corners = [] for i in range(1, len(skeleton) - 1): a, b = skeleton[i] - skeleton[i-1], skeleton[i+1] - skeleton[i] if a @ b < np.cos(np.deg2rad(55)) * np.linalg.norm(a) * np.linalg.norm(b): corners.append(int(np.argmin(np.linalg.norm(p[:, :2]-skeleton[i], axis=1)))) cuts = sorted(set([0, *corners, len(p)-1])); pieces = [] for low, high in zip(cuts[:-1], cuts[1:]): raw = p[low:high+1]; q = resample(raw, .2); result = raw ref = LineString(raw[:, :2]) if len(q) >= 4: d = distances(q); w = np.ones(len(q)); w[[0, -1]] = 1e5 for strength in (1., .25, .0625): try: with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) tck, _ = splprep(q[:, :2].T, u=d/d[-1], w=w, k=3, s=len(q)*(policy.fit_tolerance_m*.6)**2*strength) t = np.linspace(0, 1, max(4, int(ref.length/policy.sample_m)+1)) xy = np.asarray(splev(t, tck)).T; xy[[0,-1]] = raw[[0,-1], :2] line = LineString(xy) if line.is_simple and line.hausdorff_distance(ref) <= policy.fit_tolerance_m and .85 <= line.length/ref.length <= 1.03: result = np.column_stack([xy, *[np.interp(t*d[-1], d, q[:, j]) for j in range(2, q.shape[1])]]) break except (ValueError, RuntimeWarning): continue pieces.extend(result if not pieces else result[1:]) result = np.asarray(pieces) # Individually simple fitted pieces can intersect across a structural corner. # Fall back to the complete observed chain, never trim a location-specific loop. return result if LineString(result[:, :2]).is_simple else p.copy() def tangent(p, end): """Outward tangent plus a stability check over the last metre of a chain.""" q = resample(p if end == 0 else p[::-1], .15) if distances(q)[-1] < 1.2: return None short = q[0,:2] - q[2,:2]; long = q[0,:2] - q[min(8,len(q)-1),:2] short /= max(np.linalg.norm(short), 1e-9); long /= max(np.linalg.norm(long), 1e-9) if short @ long < np.cos(np.deg2rad(35)): return None return short def bridge_curve(p,q,ta,tb,policy): """Standard cubic Hermite with optionally bounded endpoint influence. Hermite's derivative times gap/3 is its Bezier control handle. A tangent inferred from a short observed approach must not acquire an arbitrarily long handle merely because the missing interval is long. Z remains linear. """ gap=float(np.linalg.norm(q[:2]-p[:2]));derivatives=np.stack([ta,-tb]) if policy.max_tangent_handle_m is not None: derivatives*=min(1.,3*policy.max_tangent_handle_m/gap) if len(p)==3:derivatives=np.c_[derivatives,np.full(2,(q[2]-p[2])/gap)] spline=CubicHermiteSpline([0.,gap],np.stack([p,q]),derivatives,extrapolate=False) return spline(np.linspace(0,gap,max(4,int(np.ceil(gap/policy.sample_m))+1))) def road_conflict(curve, road_occupancy): """Positive road evidence can disprove a curb; missing evidence cannot. A proposed cap has observed carriageway on both sides. Samples near its anchors are excluded because a genuine junction radius starts in a corner. """ p=resample(curve,.15)[:, :2] t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-9) normal=np.c_[-t[:,1],t[:,0]] both=(road_occupancy(p+normal)>.7)&(road_occupancy(p-normal)>.7) d=distances(p);interior=(d>.3)&(dmax(.6,d[-1]*.25)) def road_side(p, road_occupancy): """Signed material side of a directed observed anchor, not of its gap.""" p=resample(p,.15)[:,:2] t=np.gradient(p,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-9) n=np.c_[-t[:,1],t[:,0]] values=[road_occupancy(p+n*w)-road_occupancy(p-n*w) for w in (.8,1.4)] return float(np.mean(values)) def complete(document, policy=Policy(), scan_domain=None, road_occupancy=None, preserve_input=False, bridge_validator=None, trace=False, anchor_validator=None): """Return candidate and audit, preserving non-curb features and source IDs. scan_domain is the external survey envelope with internal quality holes filled. Explicit scan-limit/known-opening endpoints are never joined. A generic coverage-frontier can denote an internal Gaussian dropout and is eligible. preserve_input retains valid short residuals produced by accepted window assembly; it still rejects self-intersections. Raw noise filtering is unchanged. """ if policy.max_gap_m <= 0 or policy.fit_tolerance_m <= 0 or policy.sample_m <= 0 or policy.min_chain_m <= 0: raise ValueError('positive metric policy values required') if policy.max_tangent_handle_m is not None and policy.max_tangent_handle_m<=0: raise ValueError('positive tangent handle length required') records=[]; untouched=[]; quarantined=[] for feature in document['features']: prop=feature.get('properties',{}); cls=prop.get('class') if cls not in ('curb','road_boundary') or feature['geometry']['type'] != 'LineString': untouched.append(deepcopy(feature)); continue p=np.asarray(feature['geometry']['coordinates'],float) if p.ndim != 2 or p.shape[1] not in (2,3) or len(p)<2 or not np.isfinite(p).all(): raise ValueError('curb must contain finite XY or XYZ') if not preserve_input:p=resample(p,policy.sample_m) raw=LineString(p[:,:2]) reason='short-fragment' if raw.length < policy.min_chain_m and (not preserve_input or raw.length == 0) else ('self-intersection' if not raw.is_simple else None) if reason: quarantined.append(dict(source_id=feature.get('id'),reason=reason,length_m=raw.length)); continue q=p.copy() if preserve_input else regularize(p,policy) records.append(dict(feature=deepcopy(feature),raw=p,p=q,cls=cls)) # A fit may not introduce a crossing that was absent in the source. for i, a in enumerate(records): for b in records[i+1:]: if LineString(a['p'][:,:2]).crosses(LineString(b['p'][:,:2])) and not LineString(a['raw'][:,:2]).intersects(LineString(b['raw'][:,:2])): a['p']=a['raw']; b['p']=b['raw'] obstacles=[shape(f['geometry']) for f in untouched if f.get('properties',{}).get('class')=='building_facade'] endpoints=[]; endpoint_checks=[]; pair_checks=[] for i,r in enumerate(records): if LineString(r['p'][:,:2]).is_ring: continue prop=r['feature'].get('properties',{}) for e in (0,1): reason=prop.get(('start_reason','end_reason')[e]) if trace:endpoint_checks.append(dict(source_id=r['feature']['id'],end=e,coordinates=r['p'][0 if e==0 else -1].tolist(),source_reason=reason)) if reason in ('scan-limit','known-opening','survey-exterior'): if trace:endpoint_checks[-1]['status']='protected-'+reason continue t=tangent(r['p'],e) if trace:endpoint_checks[-1].update(status='eligible'if t is not None else'no-stable-tangent',tangent=t.tolist()if t is not None else None) if t is not None: endpoints.append((i,e,r['p'][0 if e==0 else -1],t)) candidates=[]; rejected_road=[]; cos=np.cos(np.deg2rad(policy.max_heading_degrees)) if endpoints: pairs=sorted(cKDTree([x[2][:2] for x in endpoints]).query_pairs(policy.max_gap_m)) for a,b in pairs: i,ei,p,ta=endpoints[a]; j,ej,q,tb=endpoints[b] if i==j or records[i]['cls']!=records[j]['cls'] or len(p)!=len(q): continue delta=q[:2]-p[:2]; gap=np.linalg.norm(delta) if gap<.03: continue direction=delta/gap check={} if trace: check=dict(source_ids=[records[i]['feature']['id'],records[j]['feature']['id']],ends=[ei,ej],gap_m=float(gap),endpoints=[p.tolist(),q.tolist()],status='heading',heading_degrees=[float(np.degrees(np.arccos(np.clip(x,-1,1))))for x in [ta@direction,(-tb)@direction]]) pair_checks.append(check) # This rejects caps between opposite sides, even when very close. if ta@direction < cos or (-tb)@direction < cos or ta@(-tb)<-.2: continue check['status']='height' if len(p)==3 and abs(q[2]-p[2])>.5+.15*gap: continue pa=records[i]['p'] if ei==1 else records[i]['p'][::-1] pb=records[j]['p'] if ej==0 else records[j]['p'][::-1] check['status']='unsupported-or-incompatible-anchors' if anchor_validator is not None and not anchor_validator(pa,pb):continue curve=bridge_curve(p,q,ta,tb,policy) bridge=LineString(curve[:,:2]) check['status']='shape' if not bridge.is_simple or bridge.length>1.3*gap: continue check['status']='outside-survey' if scan_domain is not None and not scan_domain.covers(bridge): continue check['status']='gap-evidence' if bridge_validator is not None and not bridge_validator(curve,gap):continue check['status']='observed-road-on-both-sides' if road_occupancy is not None and road_conflict(curve,road_occupancy): rejected_road.append(dict(source_ids=[records[i]['feature'].get('id'),records[j]['feature'].get('id')], reason='observed-road-on-both-sides',coordinates=curve.tolist())) continue pa=records[i]['p'] if ei==1 else records[i]['p'][::-1] pb=records[j]['p'] if ej==0 else records[j]['p'][::-1] if road_occupancy is not None: sa=road_side(pa[-min(15,len(pa)):],road_occupancy) sb=road_side(pb[:min(15,len(pb))],road_occupancy) if sa*sb<0 and min(abs(sa),abs(sb))>.25: check['status']='opposite-road-sides' rejected_road.append(dict(source_ids=[records[i]['feature'].get('id'),records[j]['feature'].get('id')], reason='opposite-road-sides',side_scores=[sa,sb],coordinates=curve.tolist())) continue check['status']='joined-self-intersection' if not LineString(np.vstack([pa[:,:2],curve[1:,:2],pb[1:,:2]])).is_simple: continue check['status']='other-boundary-intersection' if any(bridge.intersects(LineString(r['p'][:,:2])) for k,r in enumerate(records) if k not in (i,j)): continue check['status']='facade-intersection' if any(bridge.intersects(o) for o in obstacles): continue cost=gap/policy.max_gap_m+2*(2-ta@direction+tb@direction) check.update(status='eligible-not-selected',cost=float(cost)) candidates.append(dict(a=a,b=b,curve=curve,cost=float(cost),gap_m=float(gap),check=check)) # A unique reciprocal best continuation; ambiguity is not resolved by order. choices={} for c in candidates: for e in (c['a'],c['b']): choices.setdefault(e,[]).append(c) best={} for e,cs in choices.items(): cs.sort(key=lambda c:c['cost']) if len(cs)==1 or cs[1]['cost']-cs[0]['cost']>=policy.ambiguity_margin: best[e]=cs[0] parent=list(range(len(records))); links={}; selected=[] def root(i): while parent[i]!=i: i=parent[i] return i for c in sorted(candidates,key=lambda c:c['cost']): a,b=c['a'],c['b'] if best.get(a) is not c or best.get(b) is not c: c['check']['status']='ambiguous-or-nonreciprocal';continue i,ei,*_=endpoints[a]; j,ej,*_=endpoints[b] if root(i)==root(j): c['check']['status']='would-close-loop';continue bridge=LineString(c['curve'][:,:2]) if any(bridge.intersects(LineString(s['curve'][:,:2])) for s in selected): c['check']['status']='selected-bridge-intersection';continue c['check']['status']='selected' parent[root(i)]=root(j);links[i,ei]=(j,ej,c['curve']);links[j,ej]=(i,ei,c['curve'][::-1]);selected.append(c) visited=set(); out=[] for seed in range(len(records)): if seed in visited: continue group=[j for j in range(len(records)) if root(j)==root(seed)] starts=[(j,e) for j in group for e in (0,1) if (j,e) not in links] i,entry=min(starts); result=[]; ids=[]; inferred=[]; first=(i,entry) while True: visited.add(i); r=records[i]; ids.append(r['feature'].get('id',str(i))) p=r['p'] if entry==0 else r['p'][::-1];result.extend(p if not result else p[1:]) departure=1-entry if (i,departure) not in links: last=(i,departure);break j,e,curve=links[i,departure] inferred.append(dict(status='inferred',method='bounded-cubic-hermite'if policy.max_tangent_handle_m is not None else'cubic-hermite',coordinates=curve.tolist(),length_m=LineString(curve[:,:2]).length, source_ids=[r['feature'].get('id'),records[j]['feature'].get('id')])) result.extend(curve[1:]);i,entry=j,e p=np.asarray(result);f=deepcopy(records[first[0]]['feature']);f['geometry']=mapping(LineString(p)) f['id']='plan-'+hashlib.sha256('|'.join(sorted(ids)).encode()).hexdigest()[:16] f['properties'].update(method='schematic-continuity-v1',source_ids=ids,route_permission='unassigned',review_status='candidate-unreviewed', length_m=LineString(p[:,:2]).length,closed=LineString(p[:,:2]).is_ring, start_reason=records[first[0]]['feature']['properties'].get(('start_reason','end_reason')[first[1]],'input-end'), end_reason=records[last[0]]['feature']['properties'].get(('start_reason','end_reason')[last[1]],'input-end'), inferred_spans=inferred) if not LineString(p[:,:2]).is_simple: raise ValueError('assembled chain self-intersects') out.append(f) audit=dict(schema='missioncore.plan-continuity/v1',policy=asdict(policy),input_chains=len(records)+len(quarantined),output_chains=len(out), bridges=len(selected),interpolated_m=sum(LineString(c['curve'][:,:2]).length for c in selected),quarantined=quarantined, ambiguous_endpoints=len(choices)-len(best),semantic_accuracy='unqualified',route_permission='unassigned', road_conflicts_rejected=rejected_road, max_observed_fit_displacement_m=max((LineString(r['raw'][:,:2]).hausdorff_distance(LineString(r['p'][:,:2])) for r in records),default=0)) if trace: selected_ends={(sid,end)for c in pair_checks if c['status']=='selected'for sid,end in zip(c['source_ids'],c['ends'])} for e in endpoint_checks: key=(e['source_id'],e['end']);e['joined']=key in selected_ends related=[c for c in pair_checks if key in list(zip(c['source_ids'],c['ends']))] e['candidate_count']=len(related) e['nearest_candidates']=[{k:c[k]for k in ['source_ids','ends','gap_m','status']}for c in sorted(related,key=lambda c:c['gap_m'])[:3]] if e['status']=='eligible':e['status']='joined'if e['joined']else'no-pair-in-range'if not related else'unjoined' audit.update(endpoint_checks=endpoint_checks,pair_checks=pair_checks) candidate=deepcopy(document);candidate.update(features=untouched+out,review_status='candidate-unreviewed',continuity=audit) return candidate,audit