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,179 @@
"""Fuse all street-level class vectors before exporting common road surfaces.
Gaussian depth supplies the visible reference surface. Existing SciPy image
sampling, spatial queries and weighted averaging perform the reprojection.
Unknown space and foreground occlusion never become a sidewalk observation.
"""
import time, gc, shutil
import numpy as np
import cv2
from PIL import Image
from scipy.ndimage import map_coordinates
from scipy.spatial import cKDTree
from ortho_terrain import sample as terrain_sample
from ortho_classes import resolve_surfaces
from mv_math import GROUPS, visibility_weight, station_average, surface_scores
from mv_io import RUN, ORTHO, SURVEY, MODEL, read, write, digest, record, guard
cv2.setNumThreads(3)
start = time.monotonic()
root = RUN / MODEL
evidence = root / 'evidence'
(evidence / 'road-prompt').mkdir(parents=True, exist_ok=True)
plan = read(RUN / 'cameras.json')
camera_sha = digest(RUN / 'cameras.json')
index = read(SURVEY / 'tile-index.json')
tiles = [t for t in index['tiles'] if t['status'] == 'surveyed']
low = np.min([t['bounds_xy'][0] for t in tiles], axis=0)
high = np.max([t['bounds_xy'][1] for t in tiles], axis=0)
cell = .1
w, h = np.rint((high - low) / cell).astype(int)
if w * h > 80000000:
raise ValueError('Scene exceeds bounded raster envelope')
zref = np.zeros((h, w), np.float32)
quality = np.zeros((h, w), np.float32)
field = dict(np.load(ORTHO / 'terrain-reference.npz'))
yy, xx = np.mgrid[:600, :600]
window = np.minimum.reduce([xx, yy, 599 - xx, 599 - yy])
window = np.clip(window / 80, .01, 1).astype(np.float32)
tile_slices = {}
for tile in tiles:
name = tile['id']
lo, hi = np.asarray(tile['bounds_xy'])
x, y = np.rint([(lo[0] - low[0]) / cell, (high[1] - hi[1]) / cell]).astype(int)
sl = np.s_[y:y+600, x:x+600]
tile_slices[name] = (x, y)
g = np.load(ORTHO / 'evidence' / (name + '.ground-dc.geometry.npz'))
zz = cv2.resize((g['view'][2, 3] - g['depth']).astype(np.float32), (600, 600), interpolation=cv2.INTER_AREA)
aa = cv2.resize(g['alpha'].astype(np.float32), (600, 600), interpolation=cv2.INTER_AREA)
xy = np.c_[lo[0] + (xx.ravel() + .5) * cell, hi[1] - (yy.ravel() + .5) * cell]
ground = terrain_sample(field, xy).reshape(600, 600)
valid = np.isfinite(zz) & (abs(zz - ground) <= .6) & (aa >= .6)
score = valid * aa * window
take = score > quality[sl]
quality[sl][take] = score[take]
zref[sl][take] = zz[take]
g.close()
valid = quality > 0
rows, cols = np.where(valid)
xyz = np.c_[low[0] + (cols + .5) * cell, high[1] - (rows + .5) * cell, zref[rows, cols]]
ids = np.full((h, w), -1, np.int32)
ids[rows, cols] = np.arange(len(rows), dtype=np.int32)
del quality, valid, zref, field, xy, ground
gc.collect()
if len(xyz) < 1000:
raise ValueError('Insufficient Gaussian reference surface')
tree = cKDTree(xyz[:, :2])
total = np.zeros((6, len(xyz)), np.float32)
weight_sum = np.zeros(len(xyz), np.float32)
observations = np.zeros(len(xyz), np.uint16)
early_total = total.copy()
early_weight_sum = weight_sum.copy()
model_manifest = read(root / 'inference-summary.json')
used_views = 0
for n, station in enumerate(plan['stations']):
guard()
eye = np.asarray(station['eye'])
ix = np.asarray(tree.query_ball_point(eye[:2], 25), np.int64)
if not len(ix):
continue
points = xyz[ix]
render_receipt = read(RUN / 'views' / (station['id'] + '.json'))
assert render_receipt['inputs']['camera_sha256'] == camera_sha
distance = np.linalg.norm(points[:, :2] - eye[:2], axis=1)
probabilities = []
weights = []
for spec in station['views']:
name = spec['id']
assert digest(RUN / 'views' / (name + '.geometry.npz')) == render_receipt['files'][name + '.geometry.npz']
g = np.load(RUN / 'views' / (name + '.geometry.npz'))
local = points @ g['view'][:3, :3].T + g['view'][:3, 3]
depth = local[:, 2]
uv = local[:, :2] / np.maximum(depth[:, None], .001) * np.diag(g['intrinsics'])[:2] + g['intrinsics'][:2, 2] - .5
inside = (uv[:, 0] >= 1) & (uv[:, 0] < 798) & (uv[:, 1] >= 1) & (uv[:, 1] < 598)
def sample(array, coords):
return map_coordinates(array.astype(np.float32), [coords[:, 1], coords[:, 0]], order=1, mode='constant', cval=0)
rendered_depth = sample(g['depth'], uv)
alpha = sample(g['alpha'], uv)
g.close()
weight = visibility_weight(depth, rendered_depth, alpha, distance, inside)
scores_file = root / 'scores' / (name + '.npz')
receipt = read(scores_file.with_suffix('.json'))
assert digest(scores_file) == receipt['sha256'] and receipt['groups'] == GROUPS
assert receipt['inputs']['cameras'] == camera_sha
assert receipt['inputs']['model'] == model_manifest['inputs']['model']
assert receipt['inputs']['rgb_sha256'] == render_receipt['files'][name + '.png']
scores = np.load(scores_file)['scores']
coords = (uv + .5) * .5 - .5
probability = np.asarray([sample(p, coords) for p in scores])
probability /= np.maximum(probability.sum(0), 1e-8)
probabilities.append(probability)
weights.append(weight)
used_views += 1
p = np.asarray(probabilities)
weights = np.asarray(weights)
distribution, station_weight = station_average(p, weights)
total[:, ix] += distribution * station_weight
weight_sum[ix] += station_weight
observations[ix] += (station_weight >= .05).astype(np.uint16)
# Controlled ablation: same pixels/cameras, but early winner/confidence gate.
early = np.zeros_like(p)
winner = p.argmax(1)
for k in range(6):
early[:, k] = winner == k
early_weights = weights * (p.max(1) >= .65)
early_distribution, early_station_weight = station_average(early, early_weights)
early_total[:, ix] += early_distribution * early_station_weight
early_weight_sum[ix] += early_station_weight
record(dict(stage='fuse', model=MODEL, completed=n+1, stations=len(plan['stations']), cells=len(ix), elapsed_s=time.monotonic()-start))
posterior = total / np.maximum(weight_sum, 1e-8)
early_posterior = early_total / np.maximum(early_weight_sum, 1e-8)
road, side = surface_scores(posterior, np.where(observations > 0, weight_sum, 0))
early_road, early_side = surface_scores(early_posterior, early_weight_sum)
road_class, side_class = resolve_surfaces(road, side)
early_rc, early_sc = resolve_surfaces(early_road, early_side)
accepted = road_class | side_class
early_accepted = early_rc | early_sc
np.savez_compressed(root / 'atlas-sparse.npz', rows=rows.astype(np.int32), cols=cols.astype(np.int32),
posterior=posterior.astype(np.float16), weight=weight_sum, observations=observations,
early_posterior=early_posterior.astype(np.float16), early_weight=early_weight_sum,
z=xyz[:, 2].astype(np.float32), bounds=np.asarray([low, high]), cell_m=cell, size=[w, h])
for tile in tiles:
name = tile['id']
x, y = tile_slices[name]
index_ids = ids[y:y+600, x:x+600]
known = index_ids >= 0
local_ids = np.maximum(index_ids, 0)
rr = np.where(known, road[local_ids], 0)
ss = np.where(known, side[local_ids], 0)
resize = lambda a: cv2.resize(a.astype(np.float32), (1200, 1200), interpolation=cv2.INTER_LINEAR).astype(np.float16)
rr, ss = resize(rr), resize(ss)
# Reuse only the already pinned orthographic occluder mask for edge fitting.
# Old road/sidewalk predictions are never inputs to the new surface fusion.
vehicle = np.load(ORTHO / 'evidence' / (name + '.normal.npz'))['vehicle'].astype(np.float16)
np.savez_compressed(evidence / (name + '.normal.npz'), roadway=rr, sidewalk=ss, vehicle=vehicle)
shutil.copy2(evidence / (name + '.normal.npz'), evidence / (name + '.ground.npz'))
np.savez_compressed(evidence / 'road-prompt' / (name + '.normal.npz'), road=rr)
shutil.copy2(evidence / 'road-prompt' / (name + '.normal.npz'), evidence / 'road-prompt' / (name + '.ground.npz'))
base = np.asarray(Image.open(SURVEY / name / 'top.png').convert('RGB'))
overlay = base.copy()
rc, sc = resolve_surfaces(rr.astype(np.float32), ss.astype(np.float32))
for mask, color in [(rc, [90, 130, 200]), (sc, [60, 200, 150])]:
overlay[mask] = np.uint8(.45 * base[mask] + .55 * np.asarray(color))
Image.fromarray(overlay).save(evidence / (name + '.semantic.jpg'), quality=93)
summary = dict(model=MODEL, stations=len(plan['stations']), used_views=used_views,
reference_cells=len(xyz), observed_cells=int((observations > 0).sum()),
multi_station_cells=int((observations >= 2).sum()), road_cells=int(road_class.sum()),
sidewalk_cells=int(side_class.sum()), accepted_surface_cells=int(accepted.sum()),
early_winner_surface_cells=int(early_accepted.sum()),
late_only_surface_cells=int((accepted & ~early_accepted).sum()),
early_only_surface_cells=int((early_accepted & ~accepted).sum()),
changed_surface_class_cells=int(((road_class & early_sc) | (side_class & early_rc)).sum()),
accepted_area_m2=float(accepted.sum()*cell*cell), seconds=time.monotonic()-start,
groups=GROUPS, manual_rois=[], masks='one common surface; cropped to legacy tile contract',
camera_sha256=digest(RUN/'cameras.json'), model_asset=model_manifest['inputs']['model'],
source_geometry='Gaussian ground-layer expected depth validated against local terrain',
calibration='class scores are not calibrated probabilities; no ground-truth accuracy claim')
write(root / 'fusion-summary.json', summary)
record(summary)