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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -0,0 +1,204 @@
"""Metric physical-edge anchors, followed by weighted minimum-curvature fitting.
OpenCV derivatives, SciPy sampling/Viterbi costs and a sparse smoothing solve.
Semantic masks locate a search corridor, never certify an observed curb.
No scene names, route coordinates, tile IDs or model-specific parameters.
"""
from dataclasses import dataclass, asdict
import numpy as np
import cv2
from scipy.ndimage import gaussian_filter, gaussian_filter1d, map_coordinates, maximum_filter
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve
from shapely.geometry import LineString
@dataclass(frozen=True)
class AnchorPolicy:
sample_m: float = .20
search_m: float = 3.0
search_step_m: float = .10
cross_section_m: float = .35
occluder_margin_m: float = .35
alpha_min: float = .80
minimum_support_m: float = 1.0
minimum_chain_m: float = 2.0
maximum_internal_gap_m: float = 6.0
anchor_score: float = .65
smooth_lambda_m4: float = .045
def sample(array, p):
return map_coordinates(array, [p[..., 1], p[..., 0]], order=1,
mode='constant', cval=0)
def arclength(p):
return np.r_[0., np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))]
def resample(p, step):
d = arclength(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.c_[np.interp(t, d, p[:, 0]), np.interp(t, d, p[:, 1])]
class PhysicalFields:
def __init__(self, rgb, z, alpha, occluder, road, side, cell_m,
policy=AnchorPolicy()):
self.cell = float(cell_m)
self.policy = policy
self.gray = gaussian_filter(cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)[:, :, 0].astype('float32'), .10/self.cell)
self.gx = cv2.Sobel(self.gray, cv2.CV_32F, 1, 0, ksize=3)/(8*self.cell)
self.gy = cv2.Sobel(self.gray, cv2.CV_32F, 0, 1, ksize=3)/(8*self.cell)
self.texture = np.sqrt(gaussian_filter(self.gx**2+self.gy**2, .35/self.cell))
self.alpha = np.minimum(alpha, np.isfinite(z)).astype('float32')
self.z = np.nan_to_num(z).astype('float32')
self.occluder = maximum_filter(np.asarray(occluder, 'float32'),
size=2*int(np.ceil(policy.occluder_margin_m/self.cell))+1)
self.road = np.asarray(road, 'float32')
self.side = np.asarray(side, 'float32')
def measure(self, uv, normal):
"""Normal points from road to sidewalk. Return reward and reliability."""
n = np.broadcast_to(normal, uv.shape)
plus = uv+n*self.policy.cross_section_m/self.cell
minus = uv-n*self.policy.cross_section_m/self.cell
near = sample(self.gray, plus)-sample(self.gray, minus)
far = sample(self.gray, uv+n*.8/self.cell)-sample(self.gray, uv-n*.8/self.cell)
# A material boundary persists across scales; a narrow paint ridge does not.
gray_contrast = np.clip(np.minimum(abs(near), abs(far))/18, 0, 1)*(near*far>0)
oriented_edge = np.clip(abs(sample(self.gx, uv)*n[..., 0]+sample(self.gy, uv)*n[..., 1])/55, 0, 1)
dz = sample(self.z, plus)-sample(self.z, minus)
step = np.exp(-((dz-.12)/.12)**2)*(dz>.025)*(dz<.35)
texture = np.clip((sample(self.texture, plus)-sample(self.texture, minus))/20, 0, 1)
score = .65*gray_contrast*oriented_edge+.65*step+.25*oriented_edge+.20*texture
# Broad semantics are a weak context term; no hard mask constraint.
context = .5*(sample(self.side, plus)-sample(self.side, minus)+
sample(self.road, minus)-sample(self.road, plus))
score += .10*np.clip(context, -1, 1)
alpha = np.minimum.reduce([sample(self.alpha, uv), sample(self.alpha, plus), sample(self.alpha, minus)])
blocked = np.maximum.reduce([sample(self.occluder, uv), sample(self.occluder, plus), sample(self.occluder, minus)])
reliable = (alpha >= self.policy.alpha_min)*(blocked < .25)*(abs(dz) < .45)
return score.astype('float32'), reliable.astype('float32')
def evidence_cost(scores, reliability):
"""Reward supported extent, without renormalizing away missing observations."""
scores, reliability = np.asarray(scores), np.asarray(reliability)
if not scores.size or scores.shape != reliability.shape:
raise ValueError('Matching nonempty evidence arrays required')
return -float(np.mean(np.clip(scores, -1, 1.7)*reliability))
def smooth_anchors(points, confidence, policy=AnchorPolicy(), corners=()):
"""Weighted least squares + second derivative penalty; zero weight = missing.
The positive-weight endpoint requirement prevents unsupported extrapolation.
Interior missing samples are reconstructed by the same variational spline.
Structural corners relax curvature only at their vertex, not over a radius.
"""
p = np.asarray(points, float)
w = np.asarray(confidence, float)
if len(p) < 4 or w.shape != (len(p),) or not(w[0]>0 and w[-1]>0):
raise ValueError('At least four samples and observed terminal anchors required')
ds = max(float(np.median(np.diff(arclength(p)))), policy.sample_m*.5)
D = diags([np.ones(len(p)-2), -2*np.ones(len(p)-2), np.ones(len(p)-2)],
[0, 1, 2], shape=(len(p)-2, len(p)), format='csr')
bend = np.ones(len(p)-2)
for i in corners:
if 0<i<len(p)-1:
bend[i-1] = 0
W = diags(w)
A = W+policy.smooth_lambda_m4/ds**4*(D.T@diags(bend)@D)
return spsolve(A.tocsc(), w[:, None]*p)
def mask_runs(mask):
cuts = np.r_[0, np.flatnonzero(np.diff(mask.astype(int)))+1, len(mask)]
return [(a,b) for a,b in zip(cuts[:-1], cuts[1:]) if mask[a]]
def refine_chain(seed_pixels, fields, policy=AnchorPolicy()):
"""Return supported chains, with all bounded internal interpolation recorded."""
p = resample(np.asarray(seed_pixels)*fields.cell, policy.sample_m)/fields.cell
if len(p)<12:
return []
ring = np.linalg.norm(p[0]-p[-1])*fields.cell < .05
if ring:
core=gaussian_filter1d(p[:-1],.45/policy.sample_m,axis=0,mode='wrap')
t=np.roll(core,-1,axis=0)-np.roll(core,1,axis=0)
seed=np.vstack([core,core[0]]);tangent=np.vstack([t,t[0]])
else:
seed = gaussian_filter1d(p, .45/policy.sample_m, axis=0, mode='nearest')
tangent = np.gradient(seed, axis=0)
tangent /= np.maximum(np.linalg.norm(tangent, axis=1)[:, None], 1e-8)
normal = np.c_[-tangent[:, 1], tangent[:, 0]]
orient = np.sign(np.mean(sample(fields.side, seed+normal*.6/fields.cell)-
sample(fields.side, seed-normal*.6/fields.cell))) or 1
normal *= orient
offsets = np.arange(-policy.search_m, policy.search_m+policy.search_step_m/2, policy.search_step_m)
uv = seed[:, None, :]+normal[:, None, :]*offsets[None, :, None]/fields.cell
score, reliable = fields.measure(uv, normal[:, None, :])
reward = score*reliable
# Standard first-order dynamic programming. Missing evidence has no attraction.
cost = -reward+.015*(offsets[None, :]/policy.search_m)**2
trans = 1.2*((offsets[:, None]-offsets[None, :])/.25)**2
prev = cost[0].copy()
back = np.zeros(cost.shape, np.int16)
for i in range(1, len(p)):
total = prev[:, None]+trans
back[i] = np.argmin(total, axis=0)
prev = cost[i]+total.min(0)
ix = np.zeros(len(p), int);ix[-1] = np.argmin(prev)
for i in range(len(p)-1, 0, -1):
ix[i-1] = back[i, ix[i]]
chosen = uv[np.arange(len(p)), ix]*fields.cell
evidence = reward[np.arange(len(p)), ix]
confirmed = evidence >= policy.anchor_score
# Isolated high-contrast pixels do not qualify an anchor segment.
for a,b in mask_runs(confirmed):
if (b-a)*policy.sample_m < policy.minimum_support_m:
confirmed[a:b] = False
if not confirmed.any():
return []
first,last = np.flatnonzero(confirmed)[[0,-1]]
allowed = confirmed.copy()
for a,b in mask_runs(~confirmed):
if a>first and b<=last and (b-a)*policy.sample_m <= policy.maximum_internal_gap_m:
allowed[a:b] = True
outputs=[]
for a,b in mask_runs(allowed):
if (b-a)*policy.sample_m < policy.minimum_chain_m:
continue
obs = chosen[a:b];conf = confirmed[a:b].astype(float)
# Preserve supported sharp corners indicated by metre-scale straight arms.
approx = np.asarray(LineString(obs).simplify(.35).coords)
corners=[]
for j in range(1,len(approx)-1):
v=approx[j]-approx[j-1];u=approx[j+1]-approx[j]
if min(np.linalg.norm(v),np.linalg.norm(u))<2:
continue
if v@u < .65*np.linalg.norm(v)*np.linalg.norm(u):
k=int(np.argmin(np.linalg.norm(obs-approx[j],axis=1)))
if conf[k]>0:corners.append(k)
q=smooth_anchors(obs, conf, policy, corners)
if ring and a==0 and b==len(p) and np.linalg.norm(q[0]-q[-1])<.5:
q[-1]=q[0]
if not LineString(q).is_simple:
continue
spans=[]
for i,j in mask_runs(~confirmed[a:b]):
span=q[max(0,i-1):min(len(q),j+1)]
spans.append(dict(status='inferred',method='weighted-minimum-curvature',
pixels=(span/fields.cell).tolist(),length_m=LineString(span).length))
outputs.append((q/fields.cell,dict(length_m=LineString(q).length,
anchor_fraction=float(conf.mean()),observed_anchor_length_m=float(conf.sum()*policy.sample_m),
mean_offset_m=float(np.mean(offsets[ix[a:b]])),image_edge_support=float(conf.mean()),
inferred_pixel_spans=spans,anchor_policy=asdict(policy),
terminal_extrapolation=False)))
return outputs
@@ -0,0 +1,12 @@
import numpy as np
from scipy.interpolate import make_lsq_spline
from shapely.geometry import LineString
from fit_scene import resample
def regularize(p,spacing=2.):
p=resample(p,.15);length=LineString(p).length;s=np.r_[0,np.cumsum(np.linalg.norm(np.diff(p,axis=0),axis=1))];s/=s[-1]
interior=np.arange(spacing,length-spacing/2,spacing)/length;knot=np.r_[np.zeros(4),interior,np.ones(4)];w=np.ones(len(p))
for _ in range(3):
spl=make_lsq_spline(s,p,knot,k=3,w=w,axis=0);err=np.linalg.norm(spl(s)-p,axis=1);w=np.minimum(1,.12/np.maximum(err,1e-6));w[[0,-1]]=5
q=spl(np.linspace(0,1,max(2,int(length/.12)+1)))
if not LineString(q).is_simple or np.quantile(np.linalg.norm(spl(s)-p,axis=1),.95)>.25:return p
return q
@@ -0,0 +1,57 @@
"""Road-only transfer harness; original XY extractors and fitting functions."""
from pathlib import Path
import json,time,hashlib,unittest,gc,os
import numpy as np
from scipy.ndimage import distance_transform_edt,median_filter,map_coordinates
from shapely.geometry import LineString,mapping,shape,box
from shapely.ops import unary_union
from curb_regularize import regularize
from plan_continuity import complete
S=Path('/survey');O=Path('/out');C=Path('/continuity')
start=time.monotonic()
tests=unittest.TextTestRunner(verbosity=2).run(unittest.defaultTestLoader.loadTestsFromNames(['test_plan_continuity','test_plan_junctions','test_plan_scene','test_transfer_contract','test_ortho_pass','test_multiview','test_boundary_anchors','test_gap_evidence','test_boundary_competition']))
if not tests.wasSuccessful():raise RuntimeError('Geometry tests failed')
index=json.loads((S/'tile-index.json').read_text());tiles=[t for t in index['tiles']if t['status']=='surveyed']
lo=np.min([t['bounds_xy'][0]for t in tiles],axis=0);hi=np.max([t['bounds_xy'][1]for t in tiles],axis=0);w,h=np.rint((hi-lo)/.1).astype(int)
# Same Gaussian height assembly as whole_area_map, without unrelated paint/facades.
from height_observations import observations
import cv2
zsum=np.zeros((h,w),np.float32);zw=zsum.copy()
yy,xx=np.mgrid[:600,:600];window=np.minimum(np.minimum(xx,599-xx),np.minimum(yy,599-yy));window=np.clip(window/90,.01,1).astype('float32')
for tile in tiles:
name=tile['id'];im,labels,D,g=observations(name);low,high=np.asarray(tile['bounds_xy']);x,y=np.rint([(low[0]-lo[0])/.1,(hi[1]-high[1])/.1]).astype(int);sl=np.s_[y:y+600,x:x+600]
z=g['view'][2,3]-g['depth'];native=np.load(Path('/evidence')/(name+'.normal.npz'));vehicles=native['vehicle']>.25
accepted=(cv2.resize((labels>0).astype('uint8'),(1200,1200),interpolation=cv2.INTER_NEAREST)>0)&(g['alpha']>.8)&~vehicles&np.isfinite(z)
zsmall=cv2.resize(z.astype('float32'),(600,600),interpolation=cv2.INTER_AREA);ok=cv2.resize(accepted.astype('uint8'),(600,600),interpolation=cv2.INTER_NEAREST)>0
zsum[sl]+=np.where(ok,zsmall,0)*window;zw[sl]+=ok*window
valid=zw>0;zsum/=np.maximum(zw,1e-8);del zw
nearest=distance_transform_edt(~valid,return_distances=False,return_indices=True);z=median_filter(zsum[nearest[0],nearest[1]],size=3);del nearest,zsum,valid
R=O/'regions/whole';R.mkdir(parents=True,exist_ok=True);obs=O/'observed-lines-v1';obs.mkdir(exist_ok=True)
np.savez_compressed(R/'fields.npz',bounds=np.array([lo,hi]),labels=np.zeros((h,w),np.uint8),z=z);del z;gc.collect()
source=json.loads((S/'request.json').read_text())['source']
(R/'map.constrained.json').write_text(json.dumps(dict(type='FeatureCollection',features=[],coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False),source=source)))
import observed_boundaries
observed_boundaries.main()
doc=json.loads((obs/'map.open.json').read_text())
for f in doc['features']:
p=np.array(f['geometry']['coordinates']);q=regularize(p[:,:2]);z=np.interp(np.linspace(0,1,len(q)),np.linspace(0,1,len(p)),p[:,2]);f['geometry']=mapping(LineString(np.c_[q,z]))
(obs/'map.review.json').write_text(json.dumps(doc,allow_nan=False))
fields=np.load(obs/'fields.npz');low,high=fields['bounds'];road=(fields['road']*(fields['alpha']>.8)).astype('float32');fields.close()
def occupancy(p):
uv=np.c_[(p[:,0]-low[0])/.1-.5,(high[1]-p[:,1])/.1-.5];return map_coordinates(road,[uv[:,1],uv[:,0]],order=1,mode='constant',cval=0)
domain=unary_union([box(*t['bounds_xy'][0],*t['bounds_xy'][1])for t in tiles])
candidate,audit=complete(doc,scan_domain=domain,road_occupancy=occupancy)
original_by_id={f['id']:f for f in doc['features']}
for f in candidate['features']:
for source_id in f['properties'].get('source_ids',[]):
f['properties'].setdefault('inferred_spans',[]).extend(original_by_id[source_id]['properties'].get('inferred_spans',[]))
(C/'whole.json').write_text(json.dumps(candidate,allow_nan=False));(C/'report.json').write_text(json.dumps(audit,indent=2));del road,doc,candidate;gc.collect()
import qualify_scene_junctions as qs
import qualify_scene_assembly as assembly
assembly.REVIEWED=[]
qs.q.main();assembly.assemble_scene(qs.q)
(O/'proposal-failures.json').write_text(json.dumps(qs.failures,indent=2))
result=json.loads((O/'whole-map.json').read_text());curbs=result['features']
report=dict(world=os.environ['ORTHO_SCENE'],source=source,tests_run=tests.testsRun,manual_hints=[],manual_geometry=False,review_priority=[],height_status='same Gaussian semantic height assembly; XY test, no independent Z acceptance',geometry_sha256=hashlib.sha256(json.dumps([dict(id=f['id'],geometry=f['geometry'])for f in curbs],sort_keys=True).encode()).hexdigest(),curbs=len(curbs),length_m=sum(shape(f['geometry']).length for f in curbs),seconds=time.monotonic()-start,global_parameters_changed=True,geometry_parameters_changed=True,class_overlap_policy='late class decision after weighted multiview task-class fusion',input_method='immutable multiview Mapillary semantics, physical-edge anchors, occluder rejection, weighted minimum-curvature interpolation',manual_rois=[])
(O/'transfer-report.json').write_text(json.dumps(report,indent=2));print('TRANSFER',json.dumps(report),flush=True)
@@ -0,0 +1,48 @@
from pathlib import Path
import numpy as np,cv2
from PIL import Image
from scipy.ndimage import binary_fill_holes,distance_transform_edt
S=Path('/survey');E=Path('/evidence');O=Path('/out/regions');CELL=.1
def components(mask, min_area, cell=CELL):
n,lab,stats,_=cv2.connectedComponentsWithStats(mask.astype('uint8'),8)
good=stats[:,cv2.CC_STAT_AREA]*cell*cell>=min_area;good[0]=False
return good[lab]
def observations(tile):
g=dict(np.load(S/tile/'top.geometry.npz'))
rgb=np.array(Image.open(S/tile/'top.png').convert('RGB'))
native=np.load(E/(tile+'.normal.npz')); ground=np.load(E/(tile+'.ground.npz'))
road=np.maximum(np.load(E/'road-prompt'/(tile+'.normal.npz'))['road'],native['roadway'])
side=np.maximum(native['sidewalk'],ground['sidewalk']*.85)
road=np.maximum(road,np.load(E/'road-prompt'/(tile+'.ground.npz'))['road']*.85)
semantic=O/'semantic'/(tile+'.npz')
if semantic.exists():
alt=np.load(semantic)
# Broad street provides observed surface support for side branches.
street=alt['street']>.3
accepted=components(street,10,cell=.05)
road=np.maximum(road,np.where(accepted & (side<.3),.5,0))
resize=lambda x:cv2.resize(x.astype('float32'),(600,600),interpolation=cv2.INTER_AREA)
road=resize(road);side=resize(side)
alpha=resize(g['alpha']);rgb=cv2.resize(rgb,(600,600),interpolation=cv2.INTER_AREA)
valid=(alpha>.8)
# An observation's instance confidence is not calibrated per-pixel probability.
# Use categorical evidence plus distance to boundary, not a false confidence claim.
road=components((road>.3)&valid,3)
side=components((side>.3)&valid,3)
road=binary_fill_holes(road);side=binary_fill_holes(side)
anyground=road|side
# Bounded closing addresses narrow local occlusions; large gaps stay unknown.
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(7,7))
anyground=cv2.morphologyEx(anyground.astype('uint8'),cv2.MORPH_CLOSE,kernel)>0
# Short occlusions inside a recognised surface retain the surface class.
sd=[]
for m in [~anyground,road,side]:
f=(distance_transform_edt(m)-distance_transform_edt(~m))*CELL
sd.append(np.clip(f,-1.5,1.5))
sd=np.array(sd,dtype='float32')
labels=np.argmax(sd,axis=0).astype('uint8')
costs=np.maximum(sd.max(axis=0,keepdims=True)-sd,0)/.3
no_observation=(~valid)&(~anyground)
costs[:,no_observation]=20;costs[0,no_observation]=0
return rgb,labels,costs,g
@@ -0,0 +1,31 @@
import numpy as np
from scipy.ndimage import median_filter
class HeightLift:
def __init__(self,geometry,atlas):
self.depth=median_filter(geometry['depth'],size=3)
self.alpha=geometry['alpha'];self.k=geometry['intrinsics'];self.inverse=np.linalg.inv(geometry['view'])
self.height,self.width=self.depth.shape
# Robust height envelope fitted only to already observed ground returns.
z=atlas['z'];rr,cc=np.where(np.isfinite(z))
assert len(rr)>=100,'Insufficient observed ground reference'
cell=float(atlas['cell_m']);bounds=atlas['bounds'];h=z.shape[0]
x=bounds[0,0]+(cc+.5)*cell;y=bounds[0,1]+(h-rr-.5)*cell
a=np.column_stack([x,y,np.ones(len(x))]);keep=np.ones(len(x),bool)
for _ in range(4):
self.plane=np.linalg.lstsq(a[keep],z[rr[keep],cc[keep]],rcond=None)[0]
residual=np.abs(a@self.plane-z[rr,cc]);keep=residual<=max(.15,3*float(np.median(residual)))
self.reference_xy=np.column_stack([x[keep],y[keep]])
self.collider=None
def lift(self,pixels):
p=np.asarray(pixels,float);c=np.clip(np.rint(p[:,0]).astype(int),0,self.width-1);r=np.clip(np.rint(p[:,1]).astype(int),0,self.height-1)
xy=(p+.5-self.k[:2,2])/np.diag(self.k)[:2]
xyz=np.column_stack([xy,self.depth[r,c],np.ones(len(p))])@self.inverse.T
residual=np.abs(xyz[:,2]-np.column_stack([xyz[:,:2],np.ones(len(p))])@self.plane)
valid=(self.alpha[r,c]>=.5)&(residual<=.75)&np.isfinite(xyz).all(1)
if self.collider is not None:
heights=self.collider.sample(xyz[:,:2],xyz[:,2])
valid&=np.isfinite(heights)&(np.abs(heights-xyz[:,2])<=.5)
xyz[:,2]=heights
valid&=(p[:,0]>=0)&(p[:,0]<self.width)&(p[:,1]>=0)&(p[:,1]<self.height)
return xyz[:,:3],valid
@@ -0,0 +1,106 @@
"""Extract physical open road/sidewalk interfaces, never coverage perimeters."""
from pathlib import Path
import numpy as np,cv2,json,hashlib,time
from scipy.ndimage import distance_transform_edt,gaussian_filter,gaussian_filter1d,map_coordinates,median_filter,binary_closing
from scipy.interpolate import make_splprep
from shapely.geometry import LineString,shape,mapping,Point
from PIL import Image,ImageDraw
from fit_scene import resample,project,world
from plan_boundaries import split_observed_boundary
from ortho_classes import resolve_surfaces
from boundary_anchors import PhysicalFields, refine_chain
S=Path('/survey');E=Path('/evidence');O=Path('/out/observed-lines-v1');R=Path('/out/regions/whole')
cv2.setNumThreads(3)
def sample(a,p):return map_coordinates(a,[p[...,1],p[...,0]],order=1,mode='constant',cval=0)
def chunks(points,valid,step=.1,min_length=2):
cuts=np.r_[0,np.flatnonzero(np.diff(valid.astype(int)))+1,len(valid)]
return [points[a:b] for a,b in zip(cuts[:-1],cuts[1:]) if valid[a] and b-a>2 and LineString(points[a:b]).length*step>=min_length]
def cycchunks(p,valid):
if valid.all():return [np.vstack([p,p[0]])]
if not valid.any():return []
k=np.flatnonzero(~valid)[0];return chunks(np.roll(p,-k,axis=0),np.roll(valid,-k))
def clean(mask,area=3):
n,lab,stats,_=cv2.connectedComponentsWithStats(mask.astype('uint8'),8);keep=stats[:,4]*.1**2>=area;keep[0]=False;return keep[lab]
def refine(p,rgb,z,side,road,alpha):
# Pixel units are 10 cm. Smooth only the initial normal field, not the observation.
p=resample(p*.1,.20)/.1
if len(p)<12:return None
seed=gaussian_filter1d(p,1.5,axis=0,mode='nearest');t=np.gradient(seed,axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8);n=np.c_[-t[:,1],t[:,0]]
# Orient normal from roadway toward sidewalk.
orient=np.sign(np.mean(sample(side.astype(float),seed+n*5)-sample(side.astype(float),seed-n*5))) or 1;n*=orient
offsets=np.arange(-1.,1.001,.1);uv=seed[:,None,:]+n[:,None,:]*offsets[None,:,None]/.1
left=uv+n[:,None,:]*3;right=uv-n[:,None,:]*3
# Broad material contrast across a candidate, not individual paving joints.
contrast=np.linalg.norm(sample(rgb[:,:,0],left)-sample(rgb[:,:,0],right),axis=0) if False else abs(sample(rgb[:,:,0],left)-sample(rgb[:,:,0],right))
dz=sample(z,left)-sample(z,right)
height=np.exp(-((dz-.12)/.14)**2)*(dz>.025)*(dz<.4)
support=sample(alpha,uv)>.7
cost=-np.clip(contrast/20,0,1.5)-.7*height + .25*(offsets[None,:]/.8)**2
cost+=.8*(sample(side,uv-n[:,None,:]*5))+.8*(sample(road,uv+n[:,None,:]*5))
cost[~support]+=5
trans=2*((offsets[:,None]-offsets[None,:])/.2)**2
prev=cost[0];back=np.zeros(cost.shape,np.int16)
for i in range(1,len(p)):
total=prev[:,None]+trans;back[i]=np.argmin(total,axis=0);prev=cost[i]+total.min(0)
idx=np.zeros(len(p),int);idx[-1]=np.argmin(prev)
for i in range(len(p)-1,0,-1):idx[i-1]=back[i,idx[i]]
observed=uv[np.arange(len(p)),idx]*.1
# A spline fitted to observed edge candidates, with robust outlier weights.
weights=np.ones(len(observed));weights[[0,-1]]=8
spline,u=make_splprep(observed.T,w=weights,s=len(observed)*.12**2,k=3)
q=spline(np.linspace(0,1,max(len(p),int(LineString(observed).length/.12)))).T
if not LineString(q).is_simple:return None
return q/.1,dict(length_m=LineString(q).length,mean_offset_m=float(np.mean(offsets[idx])),image_edge_support=float(np.mean(contrast[np.arange(len(p)),idx]>5)))
def main():
start=time.monotonic();base=np.load(R/'fields.npz');low,high=base['bounds'];h,w=base['labels'].shape;cell=.1
road=np.zeros((h,w),np.float32);side=road.copy();alpha=road.copy();vehicle=road.copy();z=np.zeros((h,w),np.float32);rgb=np.zeros((h,w,3),np.uint8);best=road.copy()
tiles=[x['id'] for x in json.loads((S/'tile-index.json').read_text())['tiles'] if x['status']=='surveyed']
for tile in tiles:
g=np.load(S/tile/'top.geometry.npz');job=json.loads((S/tile/'job.json').read_text());lo,hi=job['bounds_xy'];x=int(round((lo[0]-low[0])/.1));y=int(round((high[1]-hi[1])/.1));sl=np.s_[y:y+600,x:x+600]
native=np.load(E/(tile+'.normal.npz'));rp=np.load(E/'road-prompt'/(tile+'.normal.npz'))['road'];sp=native['sidewalk'].copy()
# Local predictions add observed side streets, not any inferred extension.
for folder in ['multiscale','local','whole-local']:
path=O/folder/(tile+'.npz')
if path.exists():
m=np.load(path);rp=np.maximum(rp,m['road']);sp=np.maximum(sp,m['sidewalk'])
small=lambda a:cv2.resize(a.astype('float32'),(600,600),interpolation=cv2.INTER_AREA)
rr=small(rp);ss=small(sp);aa=small(g['alpha']);rr=np.where(aa>.75,rr,0);ss=np.where(aa>.75,ss,0)
vehicle[sl]=np.maximum(vehicle[sl],small(native['vehicle']));road[sl]=np.maximum(road[sl],rr);side[sl]=np.maximum(side[sl],ss);alpha[sl]=np.maximum(alpha[sl],aa)
window=np.minimum.reduce(np.mgrid[:600,:600].tolist()+[(599-np.mgrid[:600,:600][0]),(599-np.mgrid[:600,:600][1])]);sel=window>best[sl];best[sl][sel]=window[sel]
zz=small(g['view'][2,3]-g['depth']);z[sl][sel]=zz[sel];im=np.array(Image.open(S/tile/'top.png').convert('RGB'));im=cv2.resize(im,(600,600));rgb[sl][sel]=im[sel]
road_class,side_class=resolve_surfaces(road,side)
side=clean(side_class);road=clean(road_class)
# No fill_holes, no polygonisation of unknown. Only physical two-sided boundaries.
sm=cv2.morphologyEx(side.astype('uint8'),cv2.MORPH_CLOSE,np.ones((3,3),np.uint8));sm=gaussian_filter(sm.astype(float),1)>.5
contours,_=cv2.findContours(sm.astype('uint8'),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
rd=distance_transform_edt(~road)*cell
physical_fields=PhysicalFields(rgb,z,alpha,vehicle,road,side,cell)
features=[];audit=[];candidate_count=0
for contour in contours:
p=contour[:,0].astype(float)
if len(p)<30:continue
p=resample(np.vstack([p,p[0]])*.1,.1)[:-1]/.1;t=np.gradient(gaussian_filter1d(p,3,axis=0,mode='wrap'),axis=0);t/=np.maximum(np.linalg.norm(t,axis=1)[:,None],1e-8);n=np.c_[-t[:,1],t[:,0]]
physical=(sample(rd,p)<.8)&(sample(alpha,p)>.75)
physical&=((sample(road.astype(float),p+n*6)>.5)&(sample(side.astype(float),p-n*6)>.5))|((sample(road.astype(float),p-n*6)>.5)&(sample(side.astype(float),p+n*6)>.5))
# Bridge short detection flicker on a confirmed interface; never a street end.
physical=binary_closing(physical,structure=np.ones(7))
for chain in split_observed_boundary(p,physical,sample(alpha,p)>.75,cyclic=True,minimum_length=20):
run=chain.points
candidate_count+=1
for q,stats in refine_chain(run,physical_fields):
xy=np.c_[low[0]+(q[:,0]+.5)*.1,high[1]-(q[:,1]+.5)*.1];zz=sample(base['z'],q);xyz=np.c_[xy,zz]
closed=chain.closed and np.linalg.norm(xy[0]-xy[-1])<1e-5
if closed:xyz[-1]=xyz[0]
elif np.linalg.norm(xy[0]-xy[-1])<.5:continue
inferred=[]
for span in stats.pop('inferred_pixel_spans'):
uv=np.asarray(span.pop('pixels'));span['coordinates']=np.c_[low[0]+(uv[:,0]+.5)*.1,high[1]-(uv[:,1]+.5)*.1,sample(base['z'],uv)].tolist();inferred.append(span)
ident=hashlib.sha256(xyz.round(4).tobytes()).hexdigest()[:16]
features.append(dict(type='Feature',id='observed-curb-'+ident,properties=dict(class_name='road_boundary',**{'class':'road_boundary'},adjacent_classes=['carriageway','pedestrian_area'],method='physical-anchors-minimum-curvature',closed=closed,fill=False,start_reason=chain.start_reason,end_reason=chain.end_reason,route_permission='unassigned',inferred_spans=inferred,**stats),geometry=mapping(LineString(xyz))))
audit.append(stats)
old=json.loads((R/'map.constrained.json').read_text());facades=[f for f in old['features'] if f['properties']['class']=='building_facade'];paint=[f for f in old['features'] if f['properties']['class']=='road_marking']
doc=dict(type='FeatureCollection',schema_version='missioncore.observed-plan-research/v1',features=features+facades+paint,coordinate_system=old['coordinate_system'],source=old.get('source'),review_status='unreviewed')
(O/'map.open.json').write_text(json.dumps(doc,allow_nan=False));np.savez_compressed(O/'fields.npz',road=road,side=side,bounds=base['bounds'],alpha=alpha)
report=dict(seconds=time.monotonic()-start,tiles=len(tiles),open_curbs=len(features),length_m=sum(x['length_m'] for x in audit),candidate_count=candidate_count,no_coverage_perimeters=True,no_area_fill=True,manual_geometry=False)
(O/'report.json').write_text(json.dumps(report,indent=2));print(json.dumps(report))
if __name__=='__main__':main()
@@ -0,0 +1,322 @@
"""Bounded Gaussian-only joint junction qualification on existing render cache."""
from pathlib import Path
import json,time,copy,hashlib
import cv2,numpy as np
from scipy.ndimage import gaussian_filter,map_coordinates
from scipy.optimize import minimize
from shapely.geometry import shape,LineString,Point,box,mapping
from PIL import Image,ImageDraw
from plan_shapes import fit_primitives,line_model
from boundary_anchors import PhysicalFields, evidence_cost
from plan_continuity import resample,complete,Policy,road_conflict,road_side
from plan_junctions import unit,line_intersection,build_chain,sample_primitives,bridge_short_seam,competing_fragment
S=Path('/survey');P=Path('/prior');E=Path('/evidence');O=Path('/out');cv2.setNumThreads(3)
from survey_index import surveyed_ids
CASES=surveyed_ids(S)
def project(p,g):
p=np.asarray(p,float)
if p.shape[1]==2:p=np.c_[p,np.zeros(len(p))]
q=p@g['view'][:3,:3].T+g['view'][:3,3];return q[:,:2]*np.diag(g['intrinsics'])[:2]+g['intrinsics'][:2,2]-.5
def world(uv,g):
xy=(np.asarray(uv)+.5-g['intrinsics'][:2,2])/np.diag(g['intrinsics'])[:2];inv=np.linalg.inv(g['view']);return (np.c_[xy,np.zeros(len(xy))]@inv[:3,:3].T+inv[:3,3])[:,:2]
def sample(a,p):return map_coordinates(a,[p[...,1],p[...,0]],order=1,mode='constant',cval=0)
def rot(u,a):return np.array([np.cos(a)*u[0]-np.sin(a)*u[1],np.sin(a)*u[0]+np.cos(a)*u[1]])
def serial(v):
if isinstance(v,np.ndarray):return v.tolist()
if isinstance(v,np.generic):return v.item()
if isinstance(v,dict):return{k:serial(x)for k,x in v.items()}
if isinstance(v,(tuple,list)):return[serial(x)for x in v]
return v
class Evidence:
def __init__(self,tile):
self.g=dict(np.load(S/tile/'top.geometry.npz'));self.image=np.array(Image.open(S/tile/'top.png').convert('RGB'))
gray=cv2.cvtColor(self.image,cv2.COLOR_RGB2GRAY).astype('float32');self.gray=gaussian_filter(gray,2)
self.gx=cv2.Sobel(self.gray,cv2.CV_32F,1,0,ksize=3)/8;self.gy=cv2.Sobel(self.gray,cv2.CV_32F,0,1,ksize=3)/8
self.texture=np.sqrt(gaussian_filter(self.gx**2+self.gy**2,5))
native=np.load(E/(tile+'.normal.npz'));self.vehicle=gaussian_filter(native['vehicle'].astype('float32'),7);self.side=native['sidewalk'].astype('float32')
self.road=np.load(E/'road-prompt'/(tile+'.normal.npz'))['road'].astype('float32')
self.physical=PhysicalFields(self.image,self.g['view'][2,3]-self.g['depth'],self.g['alpha'],native['vehicle'],self.road,self.side,.05)
def occupancy(self,p):return sample(self.road,project(p,self.g))
def score(self,p,n,road_sign):
uv=project(p,self.g);nu=project(p+n,self.g)-uv;nu/=np.maximum(np.linalg.norm(nu,axis=1)[:,None],1e-9);nu*=road_sign
score,weight=self.physical.measure(uv,-nu)
valid=(uv[:,0]>=3)&(uv[:,0]<1197)&(uv[:,1]>=3)&(uv[:,1]<1197);weight*=valid
return score,weight
def primitive_cost(self,m,road_sign):
p,n,_=sample_primitives([m],fixed=45);scores,w=self.score(p,n,road_sign)
return evidence_cost(scores,w)
def extract(tile,e,source):
job=json.loads((S/tile/'job.json').read_text());lo,hi=job['bounds_xy'];domain=box(lo[0]+.3,lo[1]+.3,hi[0]-.3,hi[1]-.3);records=[]
for f in source['features']:
if f['properties']['class']!='road_boundary':continue
clipped=shape(f['geometry']).intersection(domain);parts=[clipped]if clipped.geom_type=='LineString'else[x for x in getattr(clipped,'geoms',[])if x.geom_type=='LineString']
for part in parts:
if part.length<2:continue
xyz=np.array(part.coords);p=xyz[:,:2];models=fit_primitives(p,.2);records.append(dict(p=p,xyz=xyz,models=models,feature=f))
return records,domain
def main_axis(records):
lines=[m for r in records for m in r['models']if m['kind']=='line' and np.linalg.norm(m['ends'][1]-m['ends'][0])>5]
angles=np.array([np.arctan2(*m['axis'][::-1])for m in lines]);weights=np.array([np.linalg.norm(m['ends'][1]-m['ends'][0])for m in lines])
if not len(lines):return np.array([1.,0.])
scores=np.array([np.sum(weights*(abs(np.cos(a-angles))>.96))for a in angles]);a=angles[np.argmax(scores)];u=np.array([np.cos(a),np.sin(a)])
return u if u[0]>=0 else-u
def approaches(records,axis,e):
out=[]
for idx,r in enumerate(records):
lines=[m for m in r['models']if m['kind']=='line' and abs(m['axis']@axis)>.94 and np.linalg.norm(m['ends'][1]-m['ends'][0])>3]
if not lines:continue
main=max(lines,key=lambda m:np.linalg.norm(m['ends'][1]-m['ends'][0]));p=r['p'];normal=np.array([-main['axis'][1],main['axis'][0]])
offsets=abs((p[[0,-1]]-main['origin'])@normal);which=int(np.argmax(offsets));tip=p[0 if which==0 else-1];outer=p[-1 if which==0 else 0]
if offsets[which]<.65:continue
branchlines=[m for m in r['models']if m['kind']=='line' and abs(m['axis']@axis)<.78 and np.linalg.norm(m['ends'][1]-m['ends'][0])>2]
if branchlines:
branch=max(branchlines,key=lambda m:np.linalg.norm(m['ends'][1]-m['ends'][0]));u=branch['axis'].copy()
if u@(tip-main['origin'])<0:u=-u
reliable=True
else:
q=resample(p if which else p[::-1],.15);u=unit(q[-1]-q[-min(8,len(q))]);reliable=False
if abs(u@axis)>.88:u=normal*np.sign((tip-main['origin'])@normal)
direction=main['axis'].copy()
if direction@(tip-outer)<0:direction=-direction
out.append(dict(id=idx,origin=main['origin'],main=direction,tip=tip,outer=outer,branch=u,reliable=reliable,departure=float(offsets[which])))
return out
def pair_approaches(approaches,e):
possibilities=[]
for i,a in enumerate(approaches):
for b in approaches[i+1:]:
if a['main']@b['main']>-.85 or a['branch']@b['branch']<-.05:continue
if a['reliable']and b['reliable']:u=unit(a['branch']+b['branch'])
elif a['reliable']:u=a['branch']
elif b['reliable']:u=b['branch']
else:
delta=b['tip']-a['tip'];u=unit(np.array([-delta[1],delta[0]]))
if u@(a['branch']+b['branch'])<0:u=-u
n=np.array([-u[1],u[0]]);delta=b['tip']-a['tip'];width=abs(delta@n);along=abs(delta@u)
if not 2<width<13 or along>25:continue
# Both curbs must turn toward the same side of their approach street.
na=np.array([-a['main'][1],a['main'][0]])
if ((a['tip']-a['origin'])@na)*((b['tip']-b['origin'])@na)<0:continue
cost=along*.03+abs(a['branch']@b['branch']-1)+width*.015
possibilities.append((cost,a,b,u))
used=set();pairs=[]
for _,a,b,u in sorted(possibilities,key=lambda x:x[0]):
if a['id'] in used or b['id']in used:continue
used.update([a['id'],b['id']]);pairs.append((a,b,u))
return pairs
def corridor_support(a,b,u,e):
origin=(a['tip']+b['tip'])/2;n=np.array([-u[1],u[0]]);width=abs((b['tip']-a['tip'])@n)
# Local road probabilities propose a direction; they do not author a boundary.
ts=np.arange(-4,25.01,.5);offs=np.arange(-width,width+.1,.2);pp=origin+ts[:,None,None]*u+offs[None,:,None]*n
prob=e.occupancy(pp.reshape(-1,2)).reshape(len(ts),len(offs));inside=abs(offs)<width*.35;support=(prob[:,inside]>.25).mean(1)
centers=[]
for t,row in zip(ts,prob):
weights=np.clip(row-.25,0,.75)*(abs(offs)<width*.75)
if t>1 and weights.sum()>1:centers.append([t,float(np.sum(weights*offs)/weights.sum())])
if len(centers)>=8 and not(a['reliable']and b['reliable']):
q=np.asarray(centers);fit=cv2.fitLine(q.astype('float32'),cv2.DIST_HUBER,.3,.001,.001).ravel();slope=float(np.clip(fit[1]/max(abs(fit[0]),1e-5),-.18,.18));u=unit(u+slope*n);n=np.array([-u[1],u[0]])
current=max((a['tip']-origin)@u,(b['tip']-origin)@u);valid=ts[support>.45]
stop=float(max(current,valid.max()if len(valid)else current));stop=min(stop,23.)
# Require several metres of longitudinal evidence for a street hypothesis.
length_positive=float(np.count_nonzero((ts>current)&(support>.45))*.5)
short=length_positive<3 and max(a['departure'],b['departure'])<3.5
if short:stop=current
else:stop=max(stop,current+1.)
return origin,u,n,width,stop,dict(street_support_m=length_positive,short_opening=bool(short),stop_from_midpoint_m=stop)
def solve_pair(a,b,e):
origin,u,n,width,stop,report=corridor_support(a,b,a.pop('_pair_u'),e);sides=[np.sign((r['tip']-origin)@n)for r in [a,b]]
# Model parameters: common branch angle, centre, width; two main-line offsets,
# two main-line rotations, and two local radii. Geometry is continuous by construction.
oldradius=[]
for r,side in zip([a,b],sides):
x=line_intersection(r['origin'],r['main'],origin+side*width/2*n,u)
if x is None:return None
oldradius.append(float(np.clip(min(np.linalg.norm(r['tip']-x),np.linalg.norm(r['outer']-x))*.55,.5,8.)))
short=report['short_opening'];initial=np.array([0.,0.,width,0.,0.,0.,0.,*( [0.,0.]if short else oldradius)])
angle_budget=.03 if a['reliable']or b['reliable']else .15
bounds=[(-angle_budget,angle_budget),(-1.,1.),(max(2,width-1.2),min(14,width+1.2)),(-.2,.2),(-.2,.2),(-.008,.008),(-.008,.008),(0.,0.)if short else(.25,12.),(0.,0.)if short else(.25,12.)]
def construct(x):
v=rot(u,x[0]);nn=np.array([-v[1],v[0]]);center=origin+x[1]*nn;models=[];vertices=[];signs=[]
for k,(r,side)in enumerate(zip([a,b],sides)):
um=rot(r['main'],x[5+k]);nm=np.array([-um[1],um[0]]);om=r['origin']+x[3+k]*nm;ob=center+side*x[2]/2*nn
corner=line_intersection(om,um,ob,v)
if corner is None:raise ValueError('parallel approaches')
outer=om+((r['outer']-om)@um)*um
end=ob+stop*v
# The source's far branch anchor remains the minimum existing extent.
if (end-corner)@v<.1:raise ValueError('reversed branch')
chain=build_chain([outer,corner,end],[x[7+k]]);models.append(chain);vertices.append([outer,corner,end])
# Left normal of outgoing branch points toward its opposite curb iff -side.
signs.append(-side)
return models,vertices,signs
def objective(x):
try:models,_,signs=construct(x)
except ValueError:return 100.+float(np.sum((x-initial)**2))
cost=0
for chain,sign in zip(models,signs):
# Equal block weights keep long straight approaches from drowning the turn.
cost+=sum(e.primitive_cost(m,sign)for m in chain)/len(chain)
cost+=.4*x[1]**2+.45*(x[2]-width)**2+.35*np.sum(x[3:5]**2)+12*np.sum(x[5:7]**2)+3*x[0]**2
return float(cost)
seeds=[initial]
if not short:
for radius in [2.,5.,8.]:
seed=initial.copy();seed[-2:]=radius
if objective(seed)<10:seeds.append(seed)
solutions=[minimize(objective,seed,method='Powell',bounds=bounds,options=dict(maxiter=10,maxfev=1800,xtol=.006,ftol=.0008))for seed in seeds]
result=min(solutions,key=lambda r:r.fun)
models,vertices,signs=construct(result.x)
report.update(parameters=result.x.tolist(),initial=initial.tolist(),objective_before=objective(initial),objective_after=float(result.fun),evaluations=result.nfev,source_chain_ids=[a['id'],b['id']],vertices=serial(vertices),radii_m=result.x[-2:].tolist(),shared_branch_width_m=float(result.x[2]),multistart_objectives=[float(x.fun)for x in solutions])
return models,report
def fit_pockets(records,fitted,e,axis):
proposals=[];reports=[];consumed=set()
for i,r in enumerate(records):
if i in fitted:continue
models=r['models'];lines=[m for m in models if m['kind']=='line'and abs(m['axis']@axis)>.94 and np.linalg.norm(m['ends'][1]-m['ends'][0])>3]
arcs=[m for m in models if m['kind']=='arc']
if not lines or not arcs:continue
main=max(lines,key=lambda m:np.linalg.norm(m['ends'][1]-m['ends'][0]));normal=np.array([-main['axis'][1],main['axis'][0]]);p=r['p'];offsets=abs((p[[0,-1]]-main['origin'])@normal);end=int(np.argmax(offsets));tip=p[0 if end==0 else-1];outer=p[-1 if end==0 else 0]
if offsets[end]<.6:continue
u=main['axis'].copy()
if u@(tip-outer)<0:u=-u
n=np.array([-u[1],u[0]])
for j,b in enumerate(records):
if j==i or j in fitted:continue
# A short, almost straight anchor beyond an occlusion, on the same side.
line=line_model(b['p'])
if abs(line['axis']@u)<.97 or np.quantile(abs(line['error']),.9)>.2:continue
qb=b['p'];near=int(np.argmin(np.linalg.norm(qb[[0,-1]]-tip,axis=1)));anchor=qb[0 if near==0 else-1];far=qb[-1 if near==0 else 0]
gap=np.linalg.norm(anchor-tip);depth=(line['origin']-main['origin'])@n
if not .6<abs(depth)<4.5 or gap>9 or (anchor-tip)@u<-.5 or (far-anchor)@u<0:continue
# Compare signed road sides on reliable straight supports, not the occluder.
pa=resample(main['ends'],.3);pb=resample(qb,.3)
signa=np.sign(np.mean(e.occupancy(pa+n)-e.occupancy(pa-n)));signb=np.sign(np.mean(e.occupancy(pb+n)-e.occupancy(pb-n)))
if signa*signb<0:continue
center=main['origin'];aT=(outer-center)@u;bT=(far-center)@u;tipT=(tip-center)@u
arc=max(arcs,key=lambda m:len(m['p']));ts=(arc['p']-center)@u;t0=float(ts.min());t1=float(tipT)
# The diagonal ramp occupies the existing curve region; no rectangular cap.
if t1-t0<1:t0=t1-max(1.,abs(depth))
x0=np.array([t0,t1,0.,0.,.65,.65]);bounds=[(t0-2,t0+2),(t1-2,t1+2),(-.4,.4),(-.4,.4),(.1,2.),(.1,2.)]
def make(x):
oa=center+x[2]*n;ob=center+(depth+x[3])*n
return build_chain([oa+aT*u,oa+x[0]*u,ob+x[1]*u,ob+bT*u],x[4:])
sign=signa or signb or 1
def objective(x):
try:m=make(x)
except ValueError:return 100+float(np.sum((x-x0)**2))
if x[1]<=x[0]:return 100
return sum(e.primitive_cost(z,sign)for z in m)/len(m)+.5*np.sum(x[2:4]**2)+.03*np.sum((x[:2]-x0[:2])**2)+.04*np.sum((x[4:]-min(1.5,abs(depth)*.35))**2)
result=minimize(objective,x0,method='Powell',bounds=bounds,options=dict(maxiter=10,maxfev=1400,xtol=.006,ftol=.001))
try:m=make(result.x)
except ValueError:continue
if result.fun>10:continue
proposals.append((gap,i,j,m,dict(source_chain_ids=[i,j],gap_m=float(gap),depth_m=float(abs(depth)),radii_m=result.x[4:].tolist(),objective=float(result.fun),kind='parking-pocket-occlusion')))
for _,i,j,m,report in sorted(proposals,key=lambda x:x[0]):
if i in consumed or j in consumed:continue
consumed.update([i,j]);fitted[i]=m;reports.append(report)
return {r['source_chain_ids'][1]for r in reports},reports
def reconcile_short_seams(features,domain,e):
"""Join close ends of the same edge after trimming noisy terminal hooks."""
features=copy.deepcopy(features);reports=[]
while True:
proposals=[]
for i,fa in enumerate(features):
for j,fb in enumerate(features[i+1:],i+1):
if fa['properties']['method']=='unchanged-observation'and fb['properties']['method']=='unchanged-observation':continue
for ei in [0,1]:
for ej in [0,1]:
if fa['properties'].get(('start_reason','end_reason')[ei])in('scan-limit','survey-exterior','known-opening')or fb['properties'].get(('start_reason','end_reason')[ej])in('scan-limit','survey-exterior','known-opening'):continue
a=np.asarray(fa['geometry']['coordinates']);b=np.asarray(fb['geometry']['coordinates'])
a=a if ei else a[::-1];b=b[::-1]if ej else b
result=bridge_short_seam(a,b)
if result is None:continue
joined,curve,gap=result;line=LineString(curve[:,:2])
if not domain.covers(line)or road_conflict(curve,e.occupancy):continue
sa=road_side(a[-min(20,len(a)):],e.occupancy);sb=road_side(b[:min(20,len(b))],e.occupancy)
if sa*sb<0 and min(abs(sa),abs(sb))>.25:continue
if any(line.crosses(shape(f['geometry']))for k,f in enumerate(features)if k not in(i,j)):continue
proposals.append((gap,i,j,joined,curve,ei,ej))
if not proposals:break
gap,i,j,joined,curve,ei,ej=min(proposals,key=lambda v:v[0]);fa,fb=features[i],features[j]
props=fa['properties'];parts=props.get('construction_parts',[dict(id=fa['id'],method=props['method'],primitives=props.get('primitives'))])+fb['properties'].get('construction_parts',[dict(id=fb['id'],method=fb['properties']['method'],primitives=fb['properties'].get('primitives'))])
props.update(method='joint-junction-with-local-seam',primitives=None,construction_parts=parts,start_reason=fa['properties'].get(('start_reason','end_reason')[1-ei],'input-end'),end_reason=fb['properties'].get(('start_reason','end_reason')[1-ej],'input-end'))
report=dict(source_ids=[fa['id'],fb['id']],gap_m=gap,method='trimmed-cubic-hermite',coordinates=curve.tolist(),status='inferred')
reports.append(report);props.setdefault('local_seams',[]).append(report)
fa['geometry']=mapping(LineString(joined));features.pop(j)
return features,reports
def main():
old=json.loads(Path('/continuity/whole.json').read_text());allf=[];reports=[]
for case in CASES:
tile=case;start=time.monotonic();e=Evidence(tile);records,domain=extract(tile,e,old);axis=main_axis(records);apps=approaches(records,axis,e);pairs=pair_approaches(apps,e);fitted={};pairreports=[]
for a,b,u in pairs:
a=copy.deepcopy(a);b=copy.deepcopy(b);a['_pair_u']=u
result=solve_pair(a,b,e)
if result is None:continue
models,report=result;pairreports.append(report)
for item,m in zip([a,b],models):fitted[item['id']]=m
absorbed,pocketreports=fit_pockets(records,fitted,e,axis)
features=[];quarantined=[];short_fragment_audit=[]
for idx,r in enumerate(records):
if idx in absorbed:continue
if idx not in fitted and LineString(r['p']).length<8:
conflict=road_conflict(r['p'],e.occupancy)
short_fragment_audit.append(dict(id=idx,road_on_both_sides=conflict,length_m=LineString(r['p']).length))
if conflict:
quarantined.append(idx);continue
nearby=[LineString(sample_primitives(m)[0])for m in fitted.values()]
if nearby and any(max(x.distance(Point(v))for v in r['p'])<1.8 or (LineString(r['p']).length<4 and x.distance(LineString(r['p']))<.2 and max(x.distance(Point(v))for v in r['p'])<3.5)for x in nearby):
quarantined.append(idx);continue
if idx in fitted:
q,_,_=sample_primitives(fitted[idx]);method='joint-paired-junction';primitives=serial(fitted[idx])
else:
# Keep unmodelled structures, including the regression-control junction.
q=r['p'];method='unchanged-observation';primitives=None
z=np.interp(np.linspace(0,1,len(q)),np.linspace(0,1,len(r['xyz'])),r['xyz'][:,2]);props={**r['feature']['properties'],'tile':tile,'method':method,'primitives':primitives,'route_permission':'unassigned'}
features.append(dict(type='Feature',id=tile+'-'+str(idx),geometry=mapping(LineString(np.c_[q,z])),properties=props))
features,seams=reconcile_short_seams(features,domain,e)
alternatives=[]
for f in features:
if f['properties']['method']!='unchanged-observation':continue
p=np.asarray(f['geometry']['coordinates'])
if any(competing_fragment(p,g['geometry']['coordinates'])for g in features if g['id']!=f['id']and g['properties']['method']!='unchanged-observation'):
idx=int(f['id'].rsplit('-',1)[1]);alternatives.append(f['id']);quarantined.append(idx)
short_fragment_audit.append(dict(id=idx,reason='detached-parallel-alternative-near-reconstructed-curb',status='quarantined-not-semantically-deleted'))
features=[f for f in features if f['id']not in alternatives]
candidate,continuity=complete(dict(type='FeatureCollection',features=features),policy=Policy(max_gap_m=14,fit_tolerance_m=.001),scan_domain=domain,road_occupancy=e.occupancy)
source_parts={f['id']:f['properties']for f in features}
for f in candidate['features']:
parts=[dict(id=idx,construction=source_parts[idx])for idx in f['properties']['source_ids']]
f['properties'].update(construction_parts=parts,primitives=None,geometry_scope='schematic-xy',height_status='inherited-not-refitted',method='joint-junction-qualification',semantic_accuracy='unqualified')
candidate['review_status']='candidate-unreviewed';candidate['scope']='overlapping-review-window-not-whole-scene';allf+=candidate['features']
topology=dict(simple=all(shape(f['geometry']).is_simple for f in candidate['features']),closed=sum(shape(f['geometry']).is_ring for f in candidate['features']))
(O/(tile+'.quarantine.json')).write_text(json.dumps(dict(type='FeatureCollection',features=[dict(type='Feature',id=str(i),geometry=mapping(LineString(records[i]['xyz'])),properties=dict(status='quarantined-for-review',original_id=records[i]['feature'].get('id')))for i in quarantined]),allow_nan=False))
report=dict(tile=tile,seconds=time.monotonic()-start,pairs=pairreports,main_axis=axis.tolist(),approaches=serial(apps),pockets=pocketreports,short_seams=seams,topology=topology,short_fragment_audit=short_fragment_audit,quarantined_nearby_fragments=quarantined,continuity=continuity)
reports.append(report);(O/(tile+'.map.json')).write_text(json.dumps(candidate,allow_nan=False));print(tile,'paired',len(pairreports),'pockets',len(pocketreports),'seconds',round(report['seconds'],1),flush=True)
overlaps=[]
for i,ca in enumerate(CASES):
ta=ca;ja=json.loads((S/ta/'job.json').read_text());da=box(*ja['bounds_xy'][0],*ja['bounds_xy'][1])
for cb in CASES[i+1:]:
tb=cb;jb=json.loads((S/tb/'job.json').read_text());db=box(*jb['bounds_xy'][0],*jb['bounds_xy'][1]);domain=da.intersection(db).buffer(-1)
if domain.is_empty:continue
from shapely.ops import unary_union
aa=unary_union([shape(f['geometry']).intersection(domain)for f in allf if f['properties']['tile']==ta]);bb=unary_union([shape(f['geometry']).intersection(domain)for f in allf if f['properties']['tile']==tb])
overlaps.append(dict(tiles=[ta,tb],hausdorff_m=float(aa.hausdorff_distance(bb))if not aa.is_empty and not bb.is_empty else None))
(O/'overlap.json').write_text(json.dumps(overlaps,indent=2))
(O/'report.json').write_text(json.dumps(reports,indent=2));(O/'map.json').write_text(json.dumps(dict(type='FeatureCollection',features=allf,review_status='candidate-unreviewed'),allow_nan=False))
if __name__=='__main__':
import unittest
suite=unittest.defaultTestLoader.loadTestsFromName('test_plan_junctions')
result=unittest.TextTestRunner(verbosity=2).run(suite)
if not result.wasSuccessful():raise SystemExit(1)
main()