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,65 @@
Gaussian multi-view road-surface qualification
==============================================
Offline adapter for the existing road-boundary engine. It is not an installed
provider and does not replace a live map. Private paths, imagery, original scan
poses and experiment outputs remain in simulation qualification storage.
The original scanner poses supply actual camera positions. Voxel representatives
and radius thinning suppress temporal duplicates. Four perspective headings per
station cover the surroundings, with a local PCA direction used only to orient
views. It never becomes the road centreline or a manually authored curb.
mv_render.py uses original Gaussian scales, rotations, opacity and SH to render
RGB, expected camera-Z depth and alpha. It does not use a point cloud. Existing
terrain-relative orthographic images remain the geometric reference and review
background; street-level images are not clipped at the low orthographic height.
mv_infer.py supports the already pinned Mask2Former/Mapillary and SegFormer/
Cityscapes checkpoints. It retains the full distribution over six task groups:
road, sidewalk, occluder, structure, terrain and other. Every native class enters
one group; there is no per-frame winner filtering. These normalized scores are
not calibrated probabilities. Native 65/19-class tensors are aggregated before
storage; this is a road-surface contract, not a lossless general semantic archive.
Both models receive the same 800x600 images and preserve their aspect ratio.
mv_fuse.py samples Gaussian ground-layer expected depth onto a common 10-cm
reference raster, rejects heights inconsistent with local terrain and projects
those cells into the street-level images. Soft depth agreement, alpha and distance
weight observations; substantial foreground occlusion is rejected. Several
headings at one station contribute one weighted observation. Class selection is
performed after all stations are fused. A winner-only ablation uses exactly the
same cameras and scores. Unknown cells do not become sidewalks or hole boundaries.
The current reference is a single ground level; stacked roads are not qualified.
The common surfaces are cropped into the legacy geometry input contract. No old
road/sidewalk mask is mixed into them. Only the previous orthographic SAM3 vehicle
mask is reused to suppress vehicle edges in geometric fitting. The existing
straight/arc/spline, continuity and junction coefficients stay unchanged. Further
integration is private qualification code; this folder alone does not publish a map.
Dependencies are the worker's pinned mapping image: NumPy, SciPy, OpenCV, Pillow,
PyTorch, gsplat, plyfile, transformers. No download or installation is required.
Shared helpers are mapping.py and orthophoto/{ortho_terrain,coordinate_cache,
ortho_classes}. The coordinate cache accepts an output proof_path so read-only
source surveys are never modified.
Worker mounts: /candidate source, /run new scene outputs, /ortho previous clipped
Gaussian survey/evidence (read-only), /input original Gaussian bundle (read-only),
/models/mapillary and /models/cityscapes (read-only). ORTHO_SCENE identifies the
private scene record; MV_MODEL selects the model. Run mv_plan, mv_render, mv_infer,
mv_fuse in that order; render is reused by both models. Resource admission and
exact-container cleanup belong to the private operator runner.
Tests exercise scanner dwell/order invariance, original camera heights,
conservation of all native classes, suppression of repeated-heading weights,
late class choice, depth uncertainty, foreground occlusion and unknown cells.
Run python3 -B -m unittest test_multiview in the worker mapping image.
Status: four full passes completed on Pokrovka and Maroseyka using identical
parameters and two pinned models. All 71 behavior tests passed in each pass.
Mapillary produced fewer spurious chains on both scenes; neither candidate
passes visual acceptance as a finished engineering plan. Parking-related
classification errors, false pockets and gaps remain. Consult the private
comparison report; successful execution does not establish boundary accuracy.
Session: .runtime/simulation-qualifications/multiview-pass-20261011.
@@ -0,0 +1,22 @@
{
"station_spacing_m": 12.0,
"minimum_station_distance_m": 7.8,
"views_per_station": 4,
"camera_size": [
800,
600
],
"fov_degrees": 100,
"downward_pitch_degrees": 10,
"distance_m": 25,
"camera_height": "original pose Z, validated against local Gaussian ground",
"cell_m": 0.1,
"score_size": [
400,
300
],
"aggregation": "normalized class vectors; one weighted vote per station",
"manual_rois": [],
"review_priority": [],
"point_clouds": false
}
@@ -0,0 +1,20 @@
{
"mapillary": {
"id": "mask2former-mapillary65",
"revision": "2cc022513f0012ff47d4438516284fd0946a196a",
"files": {
"pytorch_model.bin": "8120d77b194b34527b5937a576c36291ae7e76157f57a22433480c19d71e1551",
"config.json": "b40bec8d82de3b53ef967dce0496c37de520b69466f1a8d2f6c035700cbae9f3",
"preprocessor_config.json": "22ef0608c7add19c5e9a64f8eeba95b7d3d1237ef20bf14efead9d8bc671da9f"
}
},
"cityscapes": {
"id": "segformer-b2-cityscapes19",
"revision": "d633b2072669ca68d8f8e309de9b52bfdbf6bf72",
"files": {
"pytorch_model.bin": "584d72ace8c17c5683c198e1a4c3eda2e1026bafc02711ac5e5a4dc097bd05fe",
"config.json": "3bafe3a84c87270732bb383f6ef33801d1cd441907da8cedc2c8a4986276945d",
"preprocessor_config.json": "d96ab2cb112985c19d5ea32f1d1f2369104fc78b1379f5ce26e33ca8646202a7"
}
}
}
@@ -0,0 +1,30 @@
"""Uniformly sampled camera diagnostic panels; never detector inputs."""
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw
from mv_io import RUN, MODEL, read, write
def camera_review():
plan = read(RUN / 'cameras.json')
views = [v for station in plan['stations'] for v in station['views']]
selected = [views[i] for i in np.linspace(0, len(views)-1, 12).astype(int)]
out = Path('/out')
colors = np.asarray([[90,130,200],[60,200,150],[240,155,75],[185,150,180],[135,165,90],[180,185,190]])
for start in range(0, len(selected), 6):
part = selected[start:start+6]
sheet = Image.new('RGB', (820, len(part)*330), '#f5f5f1')
draw = ImageDraw.Draw(sheet)
for i, spec in enumerate(part):
name = spec['id']
image = Image.open(RUN/'views'/(name+'.png')).convert('RGB').resize((400,300), Image.Resampling.LANCZOS)
p = np.load(RUN/MODEL/'scores'/(name+'.npz'))['scores']
label = p.argmax(0)
overlay = Image.fromarray(np.uint8(.45*np.asarray(image)+.55*colors[label]))
sheet.paste(image, (0, i*330+25))
sheet.paste(overlay, (410, i*330+25))
draw.text((5, i*330+5), name+' / source', fill='#263640')
draw.text((415, i*330+5), MODEL+' / task classes', fill='#263640')
sheet.save(out/f'camera-contact-{start//6+1:02d}.jpg', quality=94)
write(out/'camera-review.json', dict(views=[v['id'] for v in selected], selection='12 uniformly spaced camera indices',
used_as_detector_inputs=False, colors=dict(zip(['road','sidewalk','occluder','structure','terrain','other'], colors.tolist()))))
@@ -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)
@@ -0,0 +1,73 @@
"""Keep every task-class score, never a per-frame winner-only ground mask."""
import time
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation, SegformerForSemanticSegmentation
from mv_math import GROUPS, group_matrix
from mv_io import RUN, MODEL, config, read, write, digest, record, guard
start = time.monotonic()
cfg = config()
asset = cfg['models'][MODEL]
model_dir = Path('/models') / MODEL
for name, expected in asset['files'].items():
assert digest(model_dir / name) == expected, name
processor = AutoImageProcessor.from_pretrained(model_dir, local_files_only=True)
cls = Mask2FormerForUniversalSegmentation if MODEL == 'mapillary' else SegformerForSemanticSegmentation
model = cls.from_pretrained(model_dir, local_files_only=True).cuda().eval()
matrix = torch.tensor(group_matrix(MODEL, model.config.num_labels), device='cuda')
plan = read(RUN / 'cameras.json')
folder = RUN / MODEL / 'scores'
folder.mkdir(parents=True, exist_ok=True)
completed = 0
signature = dict(model=asset, cameras=digest(RUN / 'cameras.json'), implementation=digest(__file__),
grouping=digest(Path(__file__).with_name('mv_math.py')), input_size=[800, 600],
score_size=[400, 300], precision='autocast-bfloat16; aggregation float32')
for station in plan['stations']:
guard()
for spec in station['views']:
name = spec['id']
image_path = RUN / 'views' / (name + '.png')
receipt = folder / (name + '.json')
inputs = dict(signature, rgb_sha256=digest(image_path))
target = folder / (name + '.npz')
if receipt.exists():
cached = read(receipt)
if cached['inputs'] != inputs or digest(target) != cached['sha256']:
raise ValueError('Stale semantic cache')
completed += 1
continue
im = Image.open(image_path).convert('RGB')
tensors = processor(images=im, return_tensors='pt', size={'height': 600, 'width': 800}).to('cuda')
padded_size = tuple(tensors['pixel_values'].shape[-2:])
if not (600 <= padded_size[0] < 632 and 800 <= padded_size[1] < 832):
raise ValueError('Unexpected processor geometry: ' + str(padded_size))
if completed == 0:
record(dict(stage='processor', model=MODEL, input_size=list(padded_size), unpadded_size=[600,800]))
with torch.inference_mode(), torch.autocast('cuda', dtype=torch.bfloat16):
result = model(**tensors)
if MODEL == 'mapillary':
# Upstream semantic query aggregation, with no hard class choice.
classes = result.class_queries_logits.float().softmax(-1)[..., :-1]
masks = torch.nn.functional.interpolate(result.masks_queries_logits.float(), size=padded_size,
mode='bilinear', align_corners=False)[:, :, :600, :800]
masks = torch.nn.functional.interpolate(masks, size=(300, 400), mode='bilinear', align_corners=False).sigmoid()
all_scores = torch.einsum('bqc,bqhw->bchw', classes, masks)[0]
else:
logits = torch.nn.functional.interpolate(result.logits.float(), size=padded_size,
mode='bilinear', align_corners=False)[:, :, :600, :800]
all_scores = torch.nn.functional.interpolate(logits, size=(300, 400), mode='bilinear', align_corners=False)[0].softmax(0)
groups = torch.einsum('gc,chw->ghw', matrix, all_scores)
groups /= groups.sum(0).clamp_min(1e-8)
scores = groups.cpu().numpy().astype(np.float16)
assert np.isfinite(scores).all() and np.max(abs(scores.astype(np.float32).sum(0) - 1)) < .002
np.savez_compressed(target, scores=scores)
write(receipt, dict(inputs=inputs, sha256=digest(target), groups=GROUPS, calibrated=False))
completed += 1
del tensors, result, all_scores, groups
record(dict(stage='infer', model=MODEL, completed=completed, total=plan['view_count'], elapsed_s=time.monotonic() - start))
write(RUN / MODEL / 'inference-summary.json', dict(model=MODEL, views=completed, inputs=signature,
seconds=time.monotonic() - start, groups=GROUPS,
scores='normalized task-class mass; not calibrated probabilities'))
@@ -0,0 +1,42 @@
"""Artifact-scoped I/O for the offline qualification only."""
from pathlib import Path
import json, os, hashlib, shutil
RUN = Path('/run')
ORTHO = Path('/ortho')
SURVEY = ORTHO / 'survey'
SCENE = os.environ.get('ORTHO_SCENE', '')
MODEL = os.environ.get('MV_MODEL', 'mapillary')
def read(path):
return json.loads(Path(path).read_text())
def write(path, value):
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + '.tmp')
temporary.write_text(json.dumps(value, indent=2, allow_nan=False))
temporary.replace(path)
def digest(path):
h = hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
h.update(block)
return h.hexdigest()
def guard():
if shutil.disk_usage(RUN).free < 8 * 2**30:
raise RuntimeError('Qualification free-disk floor reached')
def record(message):
print(json.dumps(message, allow_nan=False), flush=True)
def config():
return read(RUN / 'config.json')
@@ -0,0 +1,110 @@
"""Standard voxel sampling and weighted multi-view semantic fusion primitives."""
import numpy as np
from scipy.spatial import cKDTree
GROUPS = ['road', 'sidewalk', 'occluder', 'structure', 'terrain', 'other']
MODEL_GROUPS = {
'mapillary': [[7, 8, 10, 13, 14, 23, 24], [2, 9, 11, 15],
[0, 1, 19, 20, 21, 22, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64],
[3, 4, 5, 6, 16, 17, 18, 33, 34, 38, 39, 40, 42, 44, 45, 46, 47, 48, 49, 50, 51],
[25, 26, 28, 29, 30, 31]],
'cityscapes': [[0], [1], [11, 12, 13, 14, 15, 16, 17, 18], [2, 3, 4, 5, 6, 7], [8, 9]],
}
def group_matrix(model, count):
groups = MODEL_GROUPS[model]
values = [i for g in groups for i in g]
if len(values) != len(set(values)) or max(values) >= count:
raise ValueError('Invalid class grouping')
matrix = np.zeros((6, count), np.float32)
for row, ids in enumerate(groups):
matrix[row, ids] = 1
matrix[5, matrix.sum(0) == 0] = 1
return matrix
def voxel_stations(poses, voxel_m=8., dedup_m=.25):
"""One actual pose near the spatial median; independent of dwell/order."""
poses = np.asarray(poses, np.float64)
if poses.ndim != 2 or poses.shape[1] != 3 or not np.isfinite(poses).all():
raise ValueError('Invalid scan poses')
# Exact duplicates and dense temporal repeats cannot move a station median.
unique = np.unique(poses, axis=0)
_, ids = np.unique(np.floor(unique / dedup_m).astype(np.int64), axis=0, return_index=True)
unique = unique[np.sort(ids)]
keys, inverse = np.unique(np.floor(unique[:, :2] / voxel_m).astype(np.int64), axis=0, return_inverse=True)
result = []
for i, key in enumerate(keys):
part = unique[inverse == i]
median = np.median(part, axis=0)
choice = np.argmin(np.sum((part - median) ** 2, axis=1))
result.append(part[choice])
# Remove neighbouring voxel representatives that are almost duplicates
# across a cell border. Standard radius thinning, using spatial order only.
selected = []
for point in result:
if not selected or np.min(np.linalg.norm(np.asarray(selected)[:, :2] - point[:2], axis=1)) >= voxel_m * .65:
selected.append(point)
return np.asarray(selected)
def station_views(stations, ground, radius_m=18., look_m=10., pitch_degrees=10.):
"""Four overlapping cardinal views in a local trajectory PCA frame."""
tree = cKDTree(stations[:, :2])
output = []
for i, eye in enumerate(stations):
neighbors = stations[tree.query_ball_point(eye[:2], radius_m), :2]
if len(neighbors) >= 3:
_, vectors = np.linalg.eigh(np.cov(neighbors.T))
axis = vectors[:, -1]
if axis[0] < 0 or (abs(axis[0]) < 1e-10 and axis[1] < 0):
axis = -axis
else:
axis = np.array([1., 0.])
angle = np.arctan2(axis[1], axis[0])
views = []
for j in range(4):
a = angle + j * np.pi / 2
target = eye + [look_m * np.cos(a), look_m * np.sin(a), -look_m * np.tan(np.deg2rad(pitch_degrees))]
views.append(dict(id=f'station-{i:04d}-view-{j}', projection='pinhole', size=[800, 600],
eye=eye.tolist(), target=target.tolist(), fov_degrees=100))
output.append(dict(id=f'station-{i:04d}', eye=eye.tolist(), ground_z=float(ground[i]), views=views))
return output
def visibility_weight(projected_depth, rendered_depth, alpha, distance_xy, inside):
"""Soft Gaussian-depth agreement with a hard foreground occlusion veto."""
z = np.asarray(projected_depth)
sigma = .18 + .02 * z
residual = np.asarray(rendered_depth) - z
valid = (inside & np.isfinite(z) & np.isfinite(rendered_depth) & np.isfinite(alpha)
& (z > .3) & (distance_xy <= 25) & (alpha >= .6)
& (residual >= -3 * sigma) & (residual <= 3 * sigma))
agreement = np.exp(-.5 * (residual / np.maximum(sigma, .01)) ** 2)
weight = np.clip((alpha - .6) / .35, 0, 1) * agreement / (1 + (distance_xy / 12) ** 2)
return np.where(valid, weight, 0).astype(np.float32)
def station_average(probabilities, weights):
"""One station contributes once even if several camera headings see a cell."""
p = np.asarray(probabilities, np.float32)
w = np.asarray(weights, np.float32)
if p.ndim != 3 or p.shape[0] != len(w) or p.shape[2] != w.shape[1]:
raise ValueError('Expected views x classes x cells and views x cells')
if not np.isfinite(p).all() or not np.isfinite(w).all() or (p < 0).any() or (w < 0).any():
raise ValueError('Nonfinite or negative evidence')
denominator = w.sum(0)
average = (p * w[:, None]).sum(0) / np.maximum(denominator, 1e-8)
# max, not sum: repeated directions cannot increase evidence mass.
return average, w.max(0)
def surface_scores(posterior, weight):
p = np.asarray(posterior)
if p.shape[0] != 6 or not np.isfinite(p).all():
raise ValueError('Invalid grouped distribution')
surface = np.maximum(p[0], p[1])
other = p[2:].max(0)
valid = (weight >= .08) & (surface > other) & ((p[0] + p[1]) >= .5)
return np.where(valid, p[0], 0), np.where(valid, p[1], 0)
@@ -0,0 +1,32 @@
"""Create reproducible spatial cameras from original scanner poses."""
import time
import numpy as np
from scipy.spatial import cKDTree
from ortho_terrain import sample
from mv_math import voxel_stations, station_views
from mv_io import RUN, ORTHO, SCENE, config, read, write, digest, record
start = time.monotonic()
cfg = config()
pose_path = ORTHO / cfg['scenes'][SCENE]['trajectory']
poses = np.asarray([p['T'] for p in read(pose_path)['poses']], np.float64)
field = dict(np.load(ORTHO / 'terrain-reference.npz'))
height_report = read(ORTHO / 'terrain-report.json')
assert height_report['used'] and height_report['coordinate_transform'].startswith('identity')
ground = sample(field, poses[:, :2])
sensor_height = height_report['sensor_ground_offset_m']
valid = np.isfinite(poses).all(1) & (abs(poses[:, 2] - ground - sensor_height) < 1.0)
stations = voxel_stations(poses[valid], cfg['method']['station_spacing_m'])
if not 10 <= len(stations) <= 600:
raise ValueError('Station count outside bounded qualification envelope')
views = station_views(stations, sample(field, stations[:, :2]))
nearest = cKDTree(stations[:, :2]).query(poses[valid, :2])[0]
plan = dict(schema='missioncore.multiview-cameras/v1', scene=SCENE,
pose_sha256=digest(pose_path), terrain_sha256=digest(ORTHO / 'terrain-reference.npz'),
input_poses=len(poses), rejected_height_poses=int((~valid).sum()),
stations=views, station_count=len(views), view_count=4 * len(views),
scan_to_camera_distance_m=dict(median=float(np.median(nearest)), p95=float(np.quantile(nearest,.95)), maximum=float(nearest.max())),
method=cfg['method'], coordinate_system='scene-local native LCC XYZ, Z up, metres',
manual_rois=[], seconds=time.monotonic() - start)
write(RUN / 'cameras.json', plan)
record({k: v for k, v in plan.items() if k not in ['stations', 'method']})
@@ -0,0 +1,77 @@
"""Unclipped street-level Gaussian RGB/depth views at original scan positions."""
import time, math, gc
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from plyfile import PlyData
from gsplat import rasterization
from mapping import camera
from coordinate_cache import transformed
from mv_io import RUN, SURVEY, read, write, digest, record, guard
start = time.monotonic()
plan = read(RUN / 'cameras.json')
request = read(SURVEY / 'request.json')
source = Path('/input') / request['source']['ply']
assert digest(source) == request['source']['sha256']
transform = np.asarray(request['source']['source_to_world'], np.float64)
assert transform.shape == (4, 4) and np.allclose(transform[:3, :3].T @ transform[:3, :3], np.eye(3))
data = PlyData.read(source, mmap='r')['vertex'].data
world = transformed(data, transform, str(source), proof_path=RUN / 'coordinate-cache-proof.json')
folder = RUN / 'views'
folder.mkdir(exist_ok=True)
signature = dict(source_sha256=digest(source), camera_sha256=digest(RUN / 'cameras.json'), implementation=digest(__file__))
rest = sorted([n for n in data.dtype.names if n.startswith('f_rest_')], key=lambda n: int(n.split('_')[-1]))
records = []
for station in plan['stations']:
guard()
receipt = folder / (station['id'] + '.json')
if receipt.exists():
old = read(receipt)
if old['inputs'] != signature or any(digest(folder / n) != h for n, h in old['files'].items()):
raise RuntimeError('Stale render cache')
records.append(old)
continue
eye = np.asarray(station['eye'])
mask = (abs(world[:, 0] - eye[0]) <= 35) & (abs(world[:, 1] - eye[1]) <= 35)
d = data[mask].copy()
del mask
if not len(d):
raise ValueError('No Gaussian support at scan station')
def tensor(names):
return torch.tensor(np.column_stack([d[n] for n in names]), device='cuda', dtype=torch.float32)
means = tensor(['x', 'y', 'z'])
quats = tensor([f'rot_{i}' for i in range(4)])
scales = tensor([f'scale_{i}' for i in range(3)]).exp()
opacity = tensor(['opacity']).squeeze(-1).sigmoid()
dc = tensor([f'f_dc_{i}' for i in range(3)])[:, None, :]
sh = torch.cat([dc, tensor(rest).reshape(len(d), 3, -1).transpose(1, 2)], dim=1) if rest else dc
degree = int(math.sqrt(sh.shape[1])) - 1
files = {}
for spec in station['views']:
view, k = camera(spec)
w, h = spec['size']
with torch.inference_mode():
rgbd, alpha, _ = rasterization(means, quats, scales, opacity, sh,
torch.tensor(view @ transform, device='cuda', dtype=torch.float32)[None],
torch.tensor(k, device='cuda')[None], w, h, sh_degree=degree,
camera_model='pinhole', render_mode='RGB+ED', packed=True)
rgbd = rgbd[0].cpu().numpy()
alpha = alpha[0, :, :, 0].cpu().numpy()
rgbd[:, :, :3] += 1 - alpha[:, :, None]
name = spec['id']
Image.fromarray(np.uint8(np.clip(rgbd[:, :, :3], 0, 1) * 255)).save(folder / (name + '.png'))
np.savez_compressed(folder / (name + '.geometry.npz'), depth=rgbd[:, :, 3], alpha=alpha.astype(np.float16), view=view, intrinsics=k)
for suffix in ['.png', '.geometry.npz']:
files[name + suffix] = digest(folder / (name + suffix))
del rgbd, alpha
result = dict(station=station['id'], inputs=signature, files=files, splats=len(d))
write(receipt, result)
records.append(result)
del d, means, quats, scales, opacity, dc, sh
gc.collect()
torch.cuda.empty_cache()
record(dict(stage='render', completed=len(records), stations=len(plan['stations']), elapsed_s=time.monotonic() - start))
write(RUN / 'render-summary.json', dict(stations=len(records), views=sum(len(s['views']) for s in plan['stations']),
source=request['source'], seconds=time.monotonic() - start, inputs=signature))
@@ -0,0 +1,69 @@
import unittest
import numpy as np
from mv_math import voxel_stations, station_views, group_matrix, visibility_weight, station_average, surface_scores
class MultiviewTests(unittest.TestCase):
def test_dwell_and_order_do_not_change_stations(self):
p = np.c_[np.arange(50) * .6, np.sin(np.arange(50)), np.ones(50) * 1.4]
expected = voxel_stations(p)
actual = voxel_stations(np.concatenate([p[::-1], np.repeat(p[10:11], 1000, axis=0)]))
np.testing.assert_array_equal(expected, actual)
self.assertTrue(all(np.any(np.all(p == x, axis=1)) for x in actual))
def test_invalid_poses_fail(self):
with self.assertRaises(ValueError):
voxel_stations([[0, 1, np.nan]])
def test_four_views_use_actual_pose_height(self):
stations = np.array([[0., 0, 1.4], [8, 0, 1.6], [16, 0, 1.8]])
views = station_views(stations, stations[:, 2] - 1.4)
self.assertEqual(len(views), 3)
for st, eye in zip(views, stations):
self.assertEqual(len(st['views']), 4)
for v in st['views']:
np.testing.assert_array_equal(v['eye'], eye)
self.assertLess(v['target'][2], eye[2])
def test_every_model_class_preserved_once(self):
for model, count in [('mapillary', 65), ('cityscapes', 19)]:
m = group_matrix(model, count)
np.testing.assert_array_equal(m.sum(0), np.ones(count))
def test_duplicate_headings_do_not_inflate_weight(self):
p = np.array([[[.55], [.35], [.1], [0], [0], [0]]], np.float32)
a, w = station_average(p, np.array([[.7]]))
b, v = station_average(np.repeat(p, 10, axis=0), np.full((10, 1), .7))
np.testing.assert_allclose(a, b, atol=1e-6)
np.testing.assert_allclose(w, v)
def test_losing_class_is_retained_until_fusion(self):
p = np.array([[[.51], [.49], [0], [0], [0], [0]], [[.01], [.99], [0], [0], [0], [0]]])
fused, _ = station_average(p, np.ones((2, 1)))
self.assertAlmostEqual(float(fused[1, 0]), .74, places=6)
self.assertGreater(fused[1, 0], fused[0, 0])
def test_foreground_occluder_is_not_ground_observation(self):
w = visibility_weight(np.array([10., 10., 10.]), np.array([10., 7., np.nan]),
np.ones(3), np.ones(3) * 10, np.ones(3, bool))
self.assertGreater(w[0], 0)
self.assertEqual(w[1], 0)
self.assertEqual(w[2], 0)
def test_soft_depth_residual_is_not_immediate_hole(self):
w = visibility_weight(np.array([10., 10.]), np.array([10., 10.3]), np.ones(2),
np.ones(2) * 10, np.ones(2, bool))
self.assertGreater(w[1], 0)
self.assertLess(w[1], w[0])
def test_unknown_and_vehicle_do_not_become_sidewalk(self):
p = np.array([[.2, .7, 0], [.2, .1, 0], [.6, .1, 0], [0, .1, 0], [0, 0, 0], [0, 0, 0]])
road, side = surface_scores(p, np.array([1., 1, 0]))
self.assertEqual(road[0], 0)
self.assertEqual(side[0], 0)
self.assertEqual(road[2], 0)
self.assertAlmostEqual(road[1], .7)
if __name__ == '__main__':
unittest.main()