Files
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

242 lines
11 KiB
Python

"""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
material_ranking_weight: float = .5
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')
self.material = None
self.material_valid = None
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 road_side_interface(self, uv, normal):
"""A moved candidate retains road/sidewalk adjacency at its own position.
A physical edge inside one material (paving, parking paint or a ramp)
cannot inherit the interface identity of a nearby semantic seed.
This is search eligibility; the physical score and its threshold stay
independent and are never increased by semantic agreement.
"""
n = np.broadcast_to(normal, uv.shape)
road_inside = sample(self.road, uv-n*.8/self.cell) > .5
side_outside = sample(self.side, uv+n*.8/self.cell) > .5
return road_inside & side_outside
def ranked_score(self, score, uv, normal):
"""Appearance ranks candidates but cannot invalidate physical evidence."""
if self.material is None:
return score
n = np.broadcast_to(normal, uv.shape)
inside = sample(self.material, uv-n*.8/self.cell)
outside = sample(self.material, uv+n*.8/self.cell)
contrast = inside-outside
if self.material_valid is not None:
contrast *= sample(self.material_valid, uv) >= .5
return score+self.policy.material_ranking_weight*contrast
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
# Seed normals define the search strip, not the identity of either side.
# A displaced/curved seed may have the same material on both sides, so its
# fallback sign cannot establish the orientation of an observed curb.
forward = fields.road_side_interface(uv, normal[:, None, :])
reverse = fields.road_side_interface(uv, -normal[:, None, :])
directed = np.where(forward[..., None], normal[:, None, :], -normal[:, None, :])
score, reliable = fields.measure(uv, directed)
reliable = reliable*(forward | reverse)
reward = score*reliable
# Standard first-order dynamic programming. Missing evidence has no attraction.
ranked = fields.ranked_score(score, uv, directed)*reliable
cost = -ranked+.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