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
+85
View File
@@ -63,3 +63,88 @@ In planning, the infrastructure toggle is independent of Gaussian/collision laye
Contours do not enter picking, collision or rover control. Hiding the layer leaves
the original scene and route unchanged. Delete only a map's `latest.json` pointer
to unpublish it; immutable previous versions remain available for rollback.
## Whole-location command and shared storage
The planning header command **Проанализировать инфраструктуру** creates one durable
job for the current world/collider/provider identities. The existing Worker coordinator
reserves the shared GPU using the same admission mechanism as simulation, reads the
verified complete-scene source, and launches two separate bounded containers in order:
Gaussian rendering / Mask2Former survey, then VMA object vectorization. Gaussian Pipeline
remains an independently owned module; no service is merged or restarted for this job.
The input is the existing prepared `state/project-packages/<world-sha>/` directory
(resolved through the worker's shared-cache link). Both stages bind the exact existing
files read-only. No downloads, `copy`, new PLY conversions, or source-scene files are
allowed in the analysis output. Output under `runtime/urban-mapping/jobs/<job-key>/`
contains only request/progress metadata and derived images, atlases and vectors.
Sources and receipts are checksum-verified before use. Repeated identical requests
reuse the job; retries validate and resume completed tile receipts.
The first supported source contract is an already prepared complete-scene PLY plus
its calibrated decoded collider. An imported project that exists only as native SOG
has **not** yet qualified for this command: it must not silently invoke another scene
copy or conversion. Missing shared artifacts are reported as preparation failure.
Native-source reading is a separate provider extension, not a claim of this release.
`whole_scene.py` tiles the complete collider XY bounds, independent of route A/B:
40 m core plus 10 m overlap, 60 m / 1200 px orthographic views, and up to four
800×600 perspective views per tile. The supported envelope is 256 tiles. Camera
candidates come from measured near-horizontal geometry. This is a heuristic survey;
roofs, missing ground and occlusion require inspection. All processed tiles and gaps
are recorded. “Whole-scene” describes the requested extent, not complete recognition.
`vector/whole_vectors.py` runs the pinned VMA models, uses semantic/depth evidence to
admit objects, assigns overlapping polygons to one core tile and clips lines in XYZ.
The final v2 map remains unreviewed and observation-only. It is published only when
world/collider/provider/job identities match; a failed analysis preserves the previous
map. Worker restarts reconcile exactly labelled containers before releasing the GPU.
The planning UI has independent Gaussian and collision switches, one infrastructure
switch, and a memory dropdown. Memory contains accumulated visits/attempts across
runs for a scene/collider/robot revision; the dropdown currently displays the latest
robot configuration's accumulated history. Fresh sensing remains authoritative.
## Contour consolidation
After tile assembly, **Согласование контуров** runs in the vector container.
It reads the original survey in place and retains `urban-map.raw.json` before
publishing `urban-map.json`. `contour-refinement.json` records dropped observation
IDs, overlap removal and individual joins. The map stores source IDs, inferred gap
coordinates, spline knots/control points and runtime library versions. Original
observations remain recoverable; this stage never changes the collider or route
permissions.
The geometric engine is GEOS through pinned Shapely 1.8.5.post1 (STRtree,
intersection/difference and linemerge), NetworkX connected components and SciPy
1.13.1 FITPACK cubic B-splines. There is no custom line-merging implementation.
Application policy restricts inputs to matching classes, compatible endpoint
directions/heights, unambiguous junctions and non-crossing geometry. Default
maximum gaps are 1.25 m for curbs, 0.5 m for lane paint, 0.2 m for stop lines;
gaps over 0.12 m additionally require source alpha/depth and oriented image
contrast. These are provisional metric engineering thresholds, not measurement
accuracy or autonomous-driving tolerances. Large missing sections stay open.
Duplicate overlap uses 0.15 m tolerance. Isolated weak fragments below 1.5 m are
removed only with negative image evidence on observed ground. B-spline fitting
preserves structural corners/endpoints and checks rendered XY Hausdorff deviation
<=0.12 m, height deviation <=0.08 m, length and new intersections. Height inside
an inferred bridge is explicitly labelled endpoint interpolation. Crossing areas
and zebra paint polygons are unchanged. Geometric refinement cannot establish
that every VMA classification is correct; dubious long detections are not erased
just because their image contrast is low.
Alternatives reviewed: GRASS `v.clean`/`v.generalize`, CartAGen smoothing,
momepy COINS and neatnet preprocessing. Their generic network simplification
must not collapse distinct curbs/lanes or remove legitimate dead ends. COINS
also expects non-overlapping input. For this stage the existing GEOS/SciPy
runtime avoids introducing another GIS dependency stack into legacy VMA CUDA.
Primary references:
- https://shapely.readthedocs.io/en/1.8.5/manual.html#shapely.ops.linemerge
- https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splprep.html
- https://grass.osgeo.org/grass-stable/manuals/v.clean.html
- https://cartagen.readthedocs.io/en/latest/manual.html
- https://docs.momepy.org/stable/api/momepy.COINS.html
- https://uscuni.org/neatnet/
+2
View File
@@ -63,6 +63,8 @@ def fuse(job, output, unproject, classes, write_json):
z[~accepted.reshape(height, width)] = np.nan
np.savez_compressed(output / 'surface-atlas.npz', labels=labels, z=z, views=observed.reshape(height, width),
confidence=strength.reshape(height, width), bounds=bounds, cell_m=cell)
if job.get('atlas_only'):
return {'accepted_cells': int(accepted.sum())}
rgb = np.full((height, width, 3), [25, 28, 32], np.uint8)
features = []
import rasterio.features
+55 -18
View File
@@ -69,13 +69,43 @@ def unproject(pixels, depth, view, intrinsics, projection):
return (local @ np.linalg.inv(view).T)[:, :3]
def render(job, output):
def prepare_crops(jobs):
"""One source walk per bounded batch; retain source row order and numeric operations."""
from plyfile import PlyData
if not 1 <= len(jobs) <= 4 or any(j['source'] != jobs[0]['source'] for j in jobs):
raise ValueError('A crop batch requires one source and at most four windows')
source = Path('/input') / jobs[0]['source']['ply']
transform = np.asarray(jobs[0]['source']['source_to_world'], dtype=np.float64)
data = PlyData.read(source, mmap='r')['vertex'].data
rows = [[] for _ in jobs]
for start in range(0, len(data), 250000):
d = data[start:start + 250000]
xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
for job, selected in zip(jobs, rows):
bounds = np.asarray(job['bounds_xy'], dtype=float)
mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) &
(world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1)
selected.append(d[mask].copy())
for selected in rows:
result = np.concatenate(selected)
selected.clear()
yield result
def render(job, output, prepared_rows=None):
import torch
from gsplat import rasterization
from plyfile import PlyData
source = Path('/input') / job['source']['ply']
if digest(source) != job['source']['sha256']:
raise ValueError('Gaussian source checksum mismatch')
global _verified_sources
if '_verified_sources' not in globals(): _verified_sources = set()
stat = source.stat()
identity = (str(source), stat.st_size, stat.st_mtime_ns, job['source']['sha256'])
if identity not in _verified_sources:
if digest(source) != job['source']['sha256']:
raise ValueError('Gaussian source checksum mismatch')
_verified_sources.add(identity)
transform = np.asarray(job['source']['source_to_world'], dtype=np.float64)
if (transform.shape != (4, 4) or not np.isfinite(transform).all()
or not np.allclose(transform[3], [0, 0, 0, 1])
@@ -83,18 +113,21 @@ def render(job, output):
or not np.isclose(np.linalg.det(transform[:3, :3]), 1)):
raise ValueError('Only rigid source transforms are supported; bake scale into the source')
data = PlyData.read(source, mmap='r')['vertex'].data
rows = []
bounds = np.asarray(job['bounds_xy'], dtype=float)
# Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo.
for start in range(0, len(data), 250000):
d = data[start:start + 250000]
xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) &
(world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1)
rows.append(d[mask].copy())
d = np.concatenate(rows)
del rows
if prepared_rows is None:
rows = []
bounds = np.asarray(job['bounds_xy'], dtype=float)
# Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo.
for start in range(0, len(data), 250000):
d = data[start:start + 250000]
xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']])
world = xyz @ transform[:3, :3].T + transform[:3, 3]
mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) &
(world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1)
rows.append(d[mask].copy())
d = np.concatenate(rows)
del rows
else:
d = prepared_rows
if not len(d):
raise ValueError('No Gaussians in the requested tile')
def tensor(names):
@@ -130,11 +163,15 @@ def infer(job, output):
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
model_path = Path('/model')
for name, expected in job['model']['files'].items():
global _semantic_cache
if '_semantic_cache' not in globals(): _semantic_cache = None
for name, expected in (job['model']['files'].items() if _semantic_cache is None else []):
if digest(model_path / name) != expected:
raise ValueError('Model asset checksum mismatch: ' + name)
processor = AutoImageProcessor.from_pretrained(model_path, local_files_only=True)
model = Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval()
if _semantic_cache is None:
_semantic_cache = (AutoImageProcessor.from_pretrained(model_path, local_files_only=True),
Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval())
processor, model = _semantic_cache
for spec in job['views']:
if spec.get('projection', 'pinhole') != 'pinhole':
continue # Mapillary is a street-view model; orthographic views are review only.
@@ -0,0 +1,67 @@
"""Read existing orthographic survey tiles in place; bounded four-tile cache."""
import json
from collections import OrderedDict
from pathlib import Path
import cv2
import numpy as np
from PIL import Image
class SurveyEvidence:
def __init__(self, root):
self.root = Path(root)
self.tiles = [t for t in json.loads((self.root/'tile-index.json').read_text())['tiles'] if t['status']=='surveyed']
self.cache = OrderedDict()
def load(self, tile):
key = tile['id']
if key not in self.cache:
folder = self.root/key
with np.load(folder/'top.geometry.npz') as g:
data = {k:g[k] for k in ('view','intrinsics','alpha','depth')}
rgb = np.asarray(Image.open(folder/'top.png').convert('RGB'))
data['gray'] = cv2.GaussianBlur(cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32), (3,3), .6)
self.cache[key] = data
if len(self.cache)>4:self.cache.popitem(last=False)
self.cache.move_to_end(key)
return self.cache[key]
def support(self, points, key):
"""Return observed-ground and oriented image support for each XYZ sample.
Paint needs a bright ridge, a boundary needs cross-line contrast. Image
contrast alone never proves ground: depth and alpha must also agree.
"""
p = np.asarray(points, float); n = len(p)
ground, signal = np.zeros(n, bool), np.zeros(n, bool)
tangent = np.gradient(p[:, :2], axis=0)
normal = np.column_stack([-tangent[:,1], tangent[:,0]])
normal /= np.maximum(np.linalg.norm(normal, axis=1)[:,None], 1e-9)
for tile in self.tiles:
low, high = np.asarray(tile['core_bounds'])
ids = np.flatnonzero(((p[:,:2]>=low-.1)&(p[:,:2]<=high+.1)).all(1))
if not len(ids):continue
g = self.load(tile); k = g['intrinsics']; view = g['view']; gray = g['gray']
q = p[ids]; cam = np.c_[q, np.ones(len(q))]@view.T
uv = cam[:,:2]*np.diag(k)[:2]+k[:2,2]-.5
h,w = gray.shape
valid = ((uv>6)&(uv<[w-7,h-7])).all(1)
c,r = np.rint(uv).astype(int).T; c=np.clip(c,0,w-1);r=np.clip(r,0,h-1)
valid &= (g['alpha'][r,c]>=.65)&np.isfinite(g['depth'][r,c])&(np.abs(cam[:,2]-g['depth'][r,c])<=.5)
def at(offset):
shifted = q.copy(); shifted[:,:2] += normal[ids]*offset
xy = (np.c_[shifted,np.ones(len(q))]@view.T)[:,:2]*np.diag(k)[:2]+k[:2,2]-.5
return cv2.remap(gray, xy[:,0].astype(np.float32)[None], xy[:,1].astype(np.float32)[None], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)[0]
center = np.maximum.reduce([at(x) for x in (-.05,0,.05)])
left,right = at(-.25),at(.25)
if key[0]=='road_marking':
supported = (center > np.maximum(left,right)+7)&(center>75)
else:
supported = np.maximum.reduce([np.abs(left-right), np.abs(center-left), np.abs(center-right)])>8
ground[ids] |= valid; signal[ids] |= valid&supported
return ground, signal
def bridge(self, points, key):
ground, signal = self.support(points, key)
required = .9 if key[0]=='road_marking' else .7
return bool(ground.all() and signal.mean()>=required)
@@ -0,0 +1,83 @@
"""Metric curve operations; no projection, classification or route authority."""
import warnings
import numpy as np
from scipy.interpolate import splprep, splev
from shapely.geometry import LineString, Point
def distance(points):
return np.r_[0., np.cumsum(np.linalg.norm(np.diff(points[:, :2], axis=0), axis=1))]
def sample(points, step=.15):
points = np.asarray(points, float)
d = distance(points)
keep = np.r_[True, np.diff(d) > 1e-7]
points, d = points[keep], d[keep]
if len(d) < 2:
return points
at = np.linspace(0, d[-1], max(2, int(np.ceil(d[-1] / step)) + 1))
return np.column_stack([np.interp(at, d, points[:, i]) for i in range(3)])
def lift_piece(piece, original):
"""Keep Z from the original metric curve after a planar overlap operation."""
line = LineString(original[:, :2]); d = distance(original)
xy = np.asarray(piece.coords)[:, :2]
at = [line.project(Point(p)) for p in xy]
return np.column_stack([xy, np.interp(at, d, original[:, 2])])
def end_direction(points, end):
p = sample(points if end == 0 else points[::-1], .2)
delta = p[0, :2] - p[min(4, len(p)-1), :2]
return delta / max(np.linalg.norm(delta), 1e-9)
def smooth(points, tolerance=.12):
"""Piecewise cubic B-splines, fixed endpoints/corners, bounded XYZ deviation.
The renderer consumes sampled XYZ. The actual knots/controls are retained
for CAD consumers, including linear spans where fitting is inappropriate.
"""
points = np.asarray(points, float)
line = LineString(points[:, :2])
if line.length < .3 or not line.is_simple:
return points, []
# Detect structural corners on a simplified curve, not on pixel noise.
skeleton = np.asarray(line.simplify(.12).coords)
corners = []
for i in range(1, len(skeleton)-1):
a, b = skeleton[i]-skeleton[i-1], skeleton[i+1]-skeleton[i]
if np.dot(a, b) < .766 * np.linalg.norm(a) * np.linalg.norm(b):
corners.append(int(np.argmin(np.linalg.norm(points[:, :2]-skeleton[i], axis=1))))
cuts = sorted(set([0, *corners, len(points)-1]))
result, curves = [], []
for low, high in zip(cuts, cuts[1:]):
original = points[low:high+1]
p = sample(original, .25)
reference = LineString(original[:, :2])
output = original; curve = dict(degree=1, controls=original.round(5).tolist())
if len(p) >= 4:
weights = np.ones(len(p)); weights[[0, -1]] = 1e6
for factor in (1., .25, .0625):
with warnings.catch_warnings():
warnings.simplefilter('error', RuntimeWarning)
try:
tck, _ = splprep(p.T, w=weights, s=len(p)*(.07**2)*factor, k=3)
candidate = np.asarray(splev(np.linspace(0, 1, max(4, int(reference.length/.15)+1)), tck)).T
except (ValueError, RuntimeWarning):
continue
candidate[[0, -1]] = original[[0, -1]]
fitted = LineString(candidate[:, :2])
at = distance(candidate); expected_z = np.interp(at / max(at[-1], 1e-9), distance(p)/distance(p)[-1], p[:, 2])
if (fitted.is_simple and fitted.hausdorff_distance(reference) <= tolerance
and .94 <= fitted.length/reference.length <= 1.06
and np.max(np.abs(candidate[:, 2]-expected_z)) <= .08):
output = candidate
curve = dict(degree=3, knots=np.asarray(tck[0]).round(8).tolist(),
controls=np.asarray(tck[1]).T.round(5).tolist())
break
result.extend(output if not result else output[1:])
curves.append(curve)
return np.asarray(result), curves
@@ -37,15 +37,21 @@ def main():
predictions=[];timings={}
for kind in args.kinds:
weights=args.assets/('sd_'+kind+'.pth')
assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch'
cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py')
cfg.model.pretrained=None;cfg.model.train_cfg=None
# Upstream coder relaxes its threshold until it finds a detection. Keep
# all native top-k scores and enforce a FIXED threshold after decoding.
cfg.model.pts_bbox_head.bbox_coder.score_threshold=None
model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval()
load_checkpoint(model,str(weights),map_location='cpu',strict=True)
model.cuda();start=time.monotonic()
global _models
if '_models' not in globals(): _models = {}
stat = weights.stat()
key = (str(weights), stat.st_size, stat.st_mtime_ns)
if key not in _models:
assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch'
cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py')
cfg.model.pretrained=None;cfg.model.train_cfg=None
# Fixed threshold: never relax until a detection appears.
cfg.model.pts_bbox_head.bbox_coder.score_threshold=None
model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval()
load_checkpoint(model,str(weights),map_location='cpu',strict=True)
_models[key] = (cfg, model.cuda())
cfg, model = _models[key]
start=time.monotonic()
for x,y in positions:
crop=rgb[y:y+1000,x:x+1000]
image=torch.from_numpy(crop.copy()).permute(2,0,1).float().cuda()/255.
@@ -62,7 +68,7 @@ def main():
points=points,tile_xy=[x,y]))
print(json.dumps(dict(kind=kind,tile=[x,y],detections=int((result['scores_3d']>=args.threshold).sum()))),flush=True)
timings[kind]=time.monotonic()-start
del model;torch.cuda.empty_cache()
doc=dict(schema_version='missioncore.vector-candidates/v1',source_image_sha256=sha(args.image),
vma_commit='a6e98e8f704e72499b33da84715ba39e8705e02e',weights=manifest,
input_size=[w,h],native_crop_size=1000,threshold=args.threshold,
@@ -0,0 +1,188 @@
"""Whole-location contour consolidation, independent of inference and navigation.
native detections -> same-class overlap removal -> unambiguous endpoint
graph with image-checked bridges -> corner-preserving cubic B-splines
All thresholds are metric. Missing coverage, branching, road-marking gaps and
different heights are never joined just to produce a more attractive drawing.
"""
import argparse
import hashlib
import json
from collections import defaultdict
from pathlib import Path
import numpy as np
import networkx as nx
import warnings
from scipy.spatial import cKDTree
from shapely.geometry import LineString, shape
from shapely.ops import unary_union, linemerge
from shapely.strtree import STRtree
from shapely.errors import ShapelyDeprecationWarning
from contour_geometry import distance, end_direction, lift_piece, sample, smooth
VERSION = 'missioncore.contour-consolidation/v1'
def semantic(f):
p=f['properties']
return p['class'], p.get('source_class'), p.get('geometry_role')
class SpatialLines:
"""GEOS spatial index; the pinned Shapely 1.8 returns geometry objects."""
def __init__(self, records):
self.records={id(a['line']):a for a in records}
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=ShapelyDeprecationWarning)
self.tree=STRtree([a['line'] for a in records])
def near(self, line, radius=.2):
return sorted((self.records[id(g)] for g in self.tree.query(line.buffer(radius))),
key=lambda a:(a['ids'],a['line'].wkt))
def consolidate(document, evidence=None, progress=lambda done,total:None):
"""Pure input contract: returns a new document and an auditable edit receipt."""
features=document['features']
if len(features)>20000:raise ValueError('Contour refinement exceeds feature budget')
report=dict(schema_version=VERSION, input_features=len(features),
duplicates=[], removed_noise=[], trimmed_overlap_m=0., joins=[], smoothed_curves=0)
lines=[]; other=[]; progress(0,4)
for f in features:
if f['geometry']['type']!='LineString' or f['properties']['class'] not in ('curb','road_marking'):
other.append(f);continue
p=np.asarray(f['geometry']['coordinates'],float)
p=p[np.r_[True,np.linalg.norm(np.diff(p[:,:2],axis=0),axis=1)>1e-7]]
if len(p)<2:continue
lines.append(dict(f=f,p=p,key=semantic(f),line=LineString(p[:,:2]),ids=[f['id']],gaps=[]))
# Prefer the stronger observation; remove only close, same-height overlap.
spatial=SpatialLines(lines); accepted=set(); records=[]
for a in sorted(lines,key=lambda a:(-a['f']['properties']['confidence'],-a['line'].length,a['f']['id'])):
masks=[]
for b in spatial.near(a['line']):
if id(b) not in accepted or a['key']!=b['key'] or a['line'].distance(b['line'])>.15:continue
if min(a['line'].length,b['line'].length)<1. and abs(np.dot(end_direction(a['p'],0),end_direction(b['p'],0)))<.94:continue
if abs(np.median(a['p'][:,2])-np.median(b['p'][:,2]))>.15:continue
mask=b['line'].buffer(.15,cap_style=2)
overlap=a['line'].intersection(mask).length
# A transverse crossing only occupies a tiny part of a line.
if overlap>=min(1.,.8*a['line'].length):masks.append(mask)
uncovered=a['line'].difference(unary_union(masks)) if masks else a['line']
if uncovered.length<.2*a['line'].length:
report['duplicates'].append(a['f']['id']);continue
accepted.add(id(a))
pieces=[uncovered] if uncovered.geom_type=='LineString' else list(getattr(uncovered,'geoms',[]))
report['trimmed_overlap_m']+=a['line'].length-uncovered.length
for piece in pieces:
if piece.geom_type!='LineString' or piece.length<.25:continue
p=lift_piece(piece,a['p'])
records.append({**a,'p':p,'line':LineString(p[:,:2])})
progress(1,4)
endpoints=np.array([a['p'][e] for a in records for e in (0,-1)])
tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None
# Remove isolated, short, weak fragments only when the survey also rejects them.
keep=[]
for i,a in enumerate(records):
neighbours=set(tree.query_ball_point(endpoints[2*i,:2],1.))|set(tree.query_ball_point(endpoints[2*i+1,:2],1.))
isolated=all(j//2==i for j in neighbours)
if evidence and isolated and a['line'].length<1.5 and a['f']['properties']['confidence']<.5:
ground,signal=evidence.support(sample(a['p'],.1),a['key'])
if ground.mean()>.8 and signal.mean()<.25:
report['removed_noise'].append(a['f']['id']);continue
keep.append(a)
records=keep
endpoints=np.array([a['p'][e] for a in records for e in (0,-1)])
tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None
candidates=defaultdict(list); blockers=SpatialLines(records)
openings=[shape(f['geometry']) for f in other if f['properties']['class']=='curb_cut']
for i,q in enumerate(endpoints):
a=records[i//2];va=end_direction(a['p'],i%2)
junction=[j for j in tree.query_ball_point(q[:2],.18) if records[j//2]['key']==a['key']]
if len(set(j//2 for j in junction))>2:continue
maximum=1.25 if a['key'][0]=='curb' else (.2 if a['key'][1]=='stopline' else .5)
for j in tree.query_ball_point(q[:2],maximum):
if j<=i or i//2==j//2:continue
b=records[j//2]
if a['key']!=b['key']:continue
other_junction=[k for k in tree.query_ball_point(endpoints[j,:2],.18) if records[k//2]['key']==a['key']]
if len(set(k//2 for k in other_junction))>2:continue
delta=endpoints[j,:2]-q[:2];gap=float(np.linalg.norm(delta));vb=end_direction(b['p'],j%2)
if np.dot(va,-vb)<.94 or abs(q[2]-endpoints[j,2])>.12+.12*gap:continue
if gap>.02 and min(np.dot(va,delta/gap),np.dot(-vb,delta/gap))<.85:continue
bridge=LineString([q[:2],endpoints[j,:2]])
if any(bridge.intersects(o) for o in openings):continue
if gap>.02 and any(c is not a and c is not b and bridge.crosses(c['line']) for c in blockers.near(bridge)):continue
bridge_points=sample(np.array([q,endpoints[j]]),.05) if gap>.02 else np.array([q,endpoints[j]])
if gap>.12 and (evidence is None or not evidence.bridge(bridge_points,a['key'])):continue
cost=gap+1-np.dot(va,-vb)
candidates[i].append((cost,j));candidates[j].append((cost,i))
# Mutual, separated best matches: no greedy choice at a branching/ambiguous end.
best={}
for i,options in candidates.items():
options.sort()
if len(options)==1 or options[1][0]-options[0][0]>.15:best[i]=options[0][1]
links={i:j for i,j in best.items() if best.get(j)==i}
# NetworkX identifies components; GEOS owns line assembly and orientation.
graph=nx.Graph();graph.add_nodes_from(range(len(records)))
for i,j in links.items():
if i<j:graph.add_edge(i//2,j//2,ends=(i,j))
chains=[]
for component in nx.connected_components(graph):
members=[records[i] for i in sorted(component)]
segments=[LineString(a['p']) for a in members]; gaps=[]; joins=[]
for _,_,edge in graph.subgraph(component).edges(data=True):
i,j=edge['ends'];q,p=endpoints[i],endpoints[j]
gap=float(np.linalg.norm(q[:2]-p[:2]))
if gap>1e-7:
segments.append(LineString([q,p]))
gaps.append(dict(from_xyz=q.round(4).tolist(),to_xyz=p.round(4).tolist(),length_m=round(gap,4),
evidence='image-and-ground' if gap>.12 else 'endpoint-tolerance',height_source='endpoint-interpolation'))
joins.append(dict(sources=[records[i//2]['ids'][0],records[j//2]['ids'][0]],gap_m=round(gap,4)))
merged=linemerge(segments)
if merged.geom_type!='LineString' or not merged.is_simple:
chains.extend(members);continue
report['joins'].extend(joins)
chains.append({**members[0],'p':np.asarray(merged.coords),'ids':sorted({i for a in members for i in a['ids']}),'gaps':gaps})
progress(2,4)
output=list(other)
for a in chains:
p,curves=smooth(a['p'])
original=LineString(a['p'][:,:2]); fitted=LineString(p[:,:2])
if any(fitted.crosses(b['line']) and not original.crosses(b['line']) for b in blockers.near(fitted) if not set(a['ids'])&set(b['ids'])):
p=a['p'];curves=[]
report['smoothed_curves']+=sum(c['degree']==3 for c in curves)
coordinates=p.round(4).tolist()
ident=hashlib.sha256(json.dumps([a['key'],coordinates],sort_keys=True).encode()).hexdigest()[:20]
props={**a['f']['properties'],'review_status':'unreviewed','consolidation':dict(version=VERSION,
source_ids=a['ids'],inferred_gaps=a['gaps'],max_fit_deviation_m=.12,splines=curves)}
output.append(dict(type='Feature',id='contour-'+ident,properties=props,geometry=dict(type='LineString',coordinates=coordinates)))
progress(3,4)
report.update(output_features=len(output),input_lines=len(lines),output_lines=len(output)-len(other),
inferred_gap_m=round(sum(g['length_m'] for a in chains for g in a['gaps']),4),
trimmed_overlap_m=round(report['trimmed_overlap_m'],3))
result={**document,'features':output,'analysis':{**document.get('analysis',{}),'contour_refinement':{k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}}}
progress(4,4)
return result,report
def refine_file(source, survey, output):
from contour_evidence import SurveyEvidence
output.mkdir(parents=True,exist_ok=True)
def progress(done,total):
p=output/'progress.json.tmp';p.write_text(json.dumps(dict(phase='refining',completed=done,total=total)));p.replace(output/'progress.json')
import scipy, shapely
payload=source.read_bytes()
result,report=consolidate(json.loads(payload),SurveyEvidence(survey),progress)
provenance=dict(raw_map_sha256=hashlib.sha256(payload).hexdigest(),
libraries=dict(shapely=shapely.__version__,scipy=scipy.__version__,networkx=nx.__version__))
report.update(provenance)
result['analysis']['contour_refinement'].update(provenance)
(output/'urban-map.json').write_text(json.dumps(result,ensure_ascii=False,allow_nan=False))
(output/'contour-refinement.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
print(json.dumps({k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser()
for name in ('source','survey','output'):p.add_argument('--'+name,type=Path,required=True)
a=p.parse_args();refine_file(a.source,a.survey,a.output)
@@ -0,0 +1,75 @@
"""Run native VMA over the surveyed tiles, then assemble one metric map."""
import argparse
import json
import sys
from pathlib import Path
from types import SimpleNamespace
from vector_map import assemble, digest
def merge(index, documents, request):
# Load geometry after the VMA runtime; this pinned GEOS/CUDA stack is order-sensitive.
from shapely.geometry import box, shape, mapping
features=[]
for tile,document in documents:
low,high=tile['core_bounds'];core=box(*low,*high)
for f in document['features']:
geom=shape(f['geometry'])
if geom.geom_type=='Polygon':
centre=geom.centroid
if not low[0]<=centre.x<high[0] or not low[1]<=centre.y<high[1]:continue
pieces=[geom]
else:
clipped=geom.intersection(core)
pieces=[clipped] if clipped.geom_type=='LineString' else list(getattr(clipped,'geoms',[]))
for j,piece in enumerate(pieces):
if piece.is_empty or piece.geom_type not in ('Polygon','LineString'):continue
if piece.geom_type=='LineString' and piece.length<.25:continue
features.append({**f,'id':f"{tile['id']}-{f['id']}-{j}", 'geometry':json.loads(json.dumps(mapping(piece)))})
if len(features)>20000:raise ValueError('Infrastructure result exceeds feature budget')
# Known gaps are retained as coverage facts; they never become inferred roads.
return dict(schema_version='missioncore.urban-map/v2',type='FeatureCollection',
coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False),
source={**request['source'], 'vma_commit':'a6e98e8f704e72499b33da84715ba39e8705e02e', 'weights':__import__('assets').WEIGHTS},coverage=dict(kind='objects-only',cell_m=.05,accepted_cells=0,extent_xy=index['bounds_xy']),
analysis=dict(job_key=request['key'],provider_sha256=request['identity']['provider_sha256'],scope='whole-scene',
tiles_total=len(index['tiles']),tiles_mapped=len(documents),tiles_without_ground=len(index['tiles'])-len(documents),
tiles=[{k:v for k,v in t.items() if k!='job'} for t in index['tiles']]),
review_status='unreviewed',features=features)
def run(root,assets,package,survey=None):
survey=survey or root
request=json.loads((root/'request.json').read_text());index=json.loads((survey/'tile-index.json').read_text())
from infer_vectors import main as infer
documents=[]
for i,tile in enumerate(index['tiles']):
(root/'progress.json.tmp').write_text(json.dumps(dict(phase='vectorizing',completed=i,total=len(index['tiles']))))
(root/'progress.json.tmp').replace(root/'progress.json')
if tile['status']!='surveyed':continue
folder=survey/tile['id'];out=root/tile['id']/'vectors';out.mkdir(parents=True,exist_ok=True)
receipt=out/'vector-receipt.json'
valid=False
if receipt.exists():
old=json.loads(receipt.read_text())
valid=old['source']==digest(folder/'survey-receipt.json') and digest(out/'urban-map.json')==old['result']
if not valid:
sys.argv=['infer_vectors','--image',str(folder/'top.png'),'--assets',str(assets),'--output',str(out)]
infer()
assemble(SimpleNamespace(candidates=out/'candidates.json',job=folder/'job.json',image=folder/'top.png',
geometry=folder/'top.geometry.npz',atlas=folder/'surface-atlas.npz',package=package,output=out))
receipt.write_text(json.dumps(dict(source=digest(folder/'survey-receipt.json'),result=digest(out/'urban-map.json'))))
documents.append((tile,json.loads((out/'urban-map.json').read_text())))
result=merge(index,documents,request)
raw=root/'urban-map.raw.json'
raw.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False))
from refine_contours import refine_file
refine_file(raw,survey,root)
(root/'progress.json.tmp').write_text(json.dumps(dict(phase='assembling',completed=len(index['tiles']),total=len(index['tiles']))))
(root/'progress.json.tmp').replace(root/'progress.json')
result=json.loads((root/'urban-map.json').read_text())
print(json.dumps(dict(features=len(result['features']),tiles=len(index['tiles']),mapped=len(documents))),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--assets',type=Path,required=True);p.add_argument('--package',type=Path,required=True)
p.add_argument('--survey',type=Path)
a=p.parse_args();run(a.root,a.assets,a.package,a.survey)
+92
View File
@@ -0,0 +1,92 @@
"""Bounded whole-scene survey. Tile cameras come from measured geometry, never A/B."""
import argparse
import json
import math
from pathlib import Path
import numpy as np
from mapping import render, infer, write_json, digest, unproject, CLASSES
from atlas import fuse
from terrain import load_glb
def plan_tiles(request, vertices, faces):
triangles = vertices[faces]
normals = np.cross(triangles[:,1]-triangles[:,0], triangles[:,2]-triangles[:,0])
flat = np.abs(normals[:,2]) > np.linalg.norm(normals, axis=1)*math.cos(math.radians(25))
samples = np.concatenate([triangles[flat].reshape(-1,3), triangles[flat].mean(1)])
if not len(samples):
raise ValueError('No measured near-horizontal surface in this scene')
bounds = np.array([vertices[:,:2].min(0), vertices[:,:2].max(0)])
origin = np.floor(bounds[0]/40)*40
shape = np.ceil((bounds[1]-origin)/40).astype(int)
if int(np.prod(shape)) > 256:
raise ValueError('Scene exceeds the supported 256-tile analysis envelope')
tiles=[]
for ix in range(shape[0]):
for iy in range(shape[1]):
low=origin+[ix*40,iy*40]; high=low+40; centre=(low+high)/2
local=samples[((samples[:,:2]>=low-10)&(samples[:,:2]<=high+10)).all(1)]
item=dict(id=f'tile-{ix:03d}-{iy:03d}',core_bounds=[low.tolist(),high.tolist()],bounds_xy=[(low-10).tolist(),(high+10).tolist()])
if len(local)<100:
tiles.append(dict(item,status='no-surface'));continue
# Lowest measured flat surface per 2m cell supplies camera candidates.
cells=np.floor((local[:,:2]-(low-10))/2).astype(int)
order=np.argsort(local[:,2]);_,indices=np.unique(cells[order],axis=0,return_index=True)
ground=local[order[indices]]
if len(ground)<8:
tiles.append(dict(item,status='no-surface'));continue
cameras=[];used=set()
for offset in [(-12,-12),(-12,12),(12,-12),(12,12)]:
anchor=centre+offset; index=int(np.argmin(np.linalg.norm(ground[:,:2]-anchor,axis=1)))
eye=ground[index].copy()
if index in used or np.linalg.norm(eye[:2]-anchor)>12:continue
used.add(index)
direction=centre-eye[:2]
if np.linalg.norm(direction)<1:direction=np.array([1.,0.])
direction/=np.linalg.norm(direction)
target_xy=eye[:2]+direction*12
target=ground[np.argmin(np.linalg.norm(ground[:,:2]-target_xy,axis=1))].copy()
target[:2]=target_xy;eye[2]+=1.8
cameras.append(dict(id=f'view-{len(cameras)}',projection='pinhole',size=[800,600],eye=eye.tolist(),target=target.tolist(),fov_degrees=100))
if not cameras:
tiles.append(dict(item,status='no-surface'));continue
top_z=float(local[:,2].max()+25)
top=dict(id='top',projection='ortho',size=[1200,1200],width_m=60,eye=[*centre,top_z],target=[*centre,top_z-1],up=[0,1,0])
job=dict(schema_version='missioncore.urban-mapping-job/v1',source=request['source'],model=request['model'],
bounds_xy=item['bounds_xy'],cell_m=.1,halo_m=25,min_confidence=.65,atlas_only=True,views=[top,*cameras])
tiles.append(dict(item,status='pending',job=job))
return dict(bounds_xy=bounds.tolist(),tiles=tiles)
def run(request, package, output):
terrain=json.loads((package/'terrain.json').read_text())
collider=package/(request['source']['collider_sha256']+'.decoded.glb')
meta=json.loads(collider.with_suffix('.json').read_text())
if meta['source_sha256']!=request['source']['collider_sha256'] or digest(collider)!=meta['sha256']:
raise ValueError('Collider source mismatch')
vertices,faces=load_glb(collider,terrain['collision_rotation'])
index=plan_tiles(request,vertices,faces);del vertices,faces
for i,tile in enumerate(index['tiles']):
write_json(output/'progress.json',dict(phase='survey',completed=i,total=len(index['tiles'])))
if tile['status']!='pending':continue
folder=output/tile['id'];folder.mkdir(exist_ok=True)
job=tile.pop('job');write_json(folder/'job.json',job)
receipt=folder/'survey-receipt.json'
if receipt.exists():
old=json.loads(receipt.read_text())
if old['job_sha256']==digest(folder/'job.json') and all((folder/n).exists() and digest(folder/n)==h for n,h in old['files'].items()):
tile['status']=old['status'];continue
render(job,folder)
infer(job,folder)
fuse(job,folder,unproject,CLASSES,write_json)
atlas=np.load(folder/'surface-atlas.npz',allow_pickle=False)
tile['status']='surveyed' if np.count_nonzero(np.isfinite(atlas['z']))>=100 else 'unobserved-ground'
names=['top.png','top.geometry.npz','surface-atlas.npz']
write_json(receipt,dict(job_sha256=digest(folder/'job.json'),status=tile['status'],files={n:digest(folder/n) for n in names}))
write_json(output/'tile-index.json',index)
write_json(output/'tile-index.json',index)
write_json(output/'progress.json',dict(phase='survey',completed=len(index['tiles']),total=len(index['tiles'])))
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--request',type=Path,required=True);p.add_argument('--package',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
a=p.parse_args();run(json.loads(a.request.read_text()),a.package,a.output)
@@ -0,0 +1,10 @@
{
"schema_version": "missioncore.infrastructure-worker/v1",
"platform": "windows-docker-linux-cuda",
"mapper_image": "sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0",
"vector_image": "sha256:4b5ca7b8b082e469aaffaafa34eef0595de56a3ace6bca120430438c3636ca16",
"semantic_model": "assets/mask2former-mapillary/2cc022513f0012ff47d4438516284fd0946a196a",
"vector_assets": "../urban-mapping/vma-assets",
"maximum_seconds": 21600,
"minimum_free_gib": 12
}