Add vector infrastructure maps and persistent location experience

This commit is contained in:
DCCONSTRUCTIONS
2026-10-10 14:35:50 +03:00
parent e095a43f00
commit 55f64f195b
38 changed files with 2317 additions and 14 deletions
@@ -0,0 +1,29 @@
# Location experience
The worker owns bounded summaries under `state/spatial-experience`, keyed by
world + collider + robot SHA256. Exact measured visits (0.5m indexing, observed
XYZ retained) and confirmed failed attempts survive pause, return and process
restart. At most 20,000 visited cells and 1,000 attempts; oldest summaries expire
from this bounded store when capacity is reached. This is explicitly requested
location knowledge, separate from the live-only operator telemetry store.
A failure needs matching pose/simulation-time/execution identity and repeated
stationary controller rejection for 0.5 simulation seconds. Network timeouts and
stale observations never create obstacles. `no-permitted-goal` is a perception
limitation, not evidence of physical occupancy. Attempts retain origin, target,
reason, timestamps, count, run and observation identity. A successful visit to the
target from the attempted direction resolves that record. Motion control still
uses current measurements. Fresh failures only add a bounded, ten-minute-decaying
cost to already-admissible recovery choices from the same approach; they never
veto free space or authorize driving. Historical entries remain visible afterward.
A separate asynchronous writer publishes summaries every five seconds. The worker
synchronizes them through an authenticated bounded endpoint; Mission Core retains
a mirror for inspection in planning. A changed scene/collider/robot cannot silently
reuse old decisions. Corrupt persisted input is reported and ignored for navigation.
The map layer can show/hide visits and attempted directions; attempt markers expose
human-readable reasons and successful revisits.
Global transferable learning is deliberately outside this implementation. Accumulating
location records is not model training. Cross-location generalization requires a
separate situation representation, evaluation and admission process.
+6
View File
@@ -1,6 +1,7 @@
"""Package current source plus simulation adapters into a digest-addressed archive."""
import argparse
import ast
import hashlib
import json
import tarfile
@@ -23,6 +24,11 @@ for profile in (root / "simulation/ai-polygon/robots").glob("*.json"):
asset = root / json.loads(profile.read_text())["visual"]["source"]
if asset not in files:
files.append(asset)
# Reject a broken Python artifact before staging or touching the running worker.
for source in files:
if source.suffix == ".py":
ast.parse(source.read_bytes(), filename=str(source))
manifest = {
p.relative_to(root).as_posix(): hashlib.sha256(p.read_bytes()).hexdigest() for p in files
}
+110
View File
@@ -0,0 +1,110 @@
"""Worker-owned location experience with bounded asynchronous persistence."""
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from k1link.simulation.ai_polygon.spatial_experience import (
LocationExperience,
read,
save,
source_key,
)
class ExperienceAdapter:
def __init__(self, run, inputs, directory):
self.run_id = run["run_id"]
self.execution = inputs["sha256"]
self.geometry = inputs["robot"]["geometry"]
source = dict(
world_sha256=run["world"]["sha256"],
collider_sha256=run["world"]["collider_sha256"],
robot_sha256=inputs["robot"]["sha256"],
)
# Use the canonical state path supplied by the worker, not a resolved episode junction.
self.path = Path(run["_spatial_experience_root"]) / (source_key(source) + ".json")
self.publication = directory.parent / "spatial-experience.json"
self.can_persist = True
try:
document = read(self.path, source)
except FileNotFoundError:
document = None
except (ValueError, OSError):
logging.exception("Stored location experience could not be read")
document = None
self.can_persist = False
self.memory = LocationExperience(source, document)
self.writer = ThreadPoolExecutor(max_workers=1, thread_name_prefix="spatial-experience")
self.pending = None
self.stamp = -float("inf")
self.saved = -1
def observe(self, inputs, goal, result):
pose = inputs["source.pose"]
xyz = list(pose[:3])
xyz[2] -= self.geometry["body_contact_height_m"]
self.memory.observe(
xyz,
goal,
result,
inputs["source.simulation-time"],
time.time(),
self.run_id,
str(inputs.get("source.observation-id", "")),
self.execution,
pose,
)
self.flush()
def costs(self, pose, candidates):
return self.memory.costs(pose, candidates, time.time())
def flush(self, force=False):
if not self.can_persist:
return
if self.pending is not None:
if not self.pending.done():
return
try:
self.pending.result()
except OSError:
self.saved = -1
logging.exception(
"Location experience persistence failed; live sensing remains authoritative"
)
self.pending = None
if self.saved == self.memory.revision or (not force and time.monotonic() - self.stamp < 5):
return
document = self.memory.document()
# Detach mutable records before handing them to the writer.
import copy
document = copy.deepcopy(document)
def write():
save(self.path, document)
save(self.publication, document)
self.pending = self.writer.submit(write)
self.saved = self.memory.revision
self.stamp = time.monotonic()
def close(self):
if self.pending:
try:
self.pending.result()
except OSError:
self.saved = -1
logging.exception("Final location experience write failed")
self.pending = None
self.flush(force=True)
self.writer.shutdown(wait=True)
if self.pending:
try:
self.pending.result()
except OSError:
logging.exception(
"Location experience remains unsaved; navigation resources may close"
)
@@ -175,7 +175,7 @@ class ObservedGoals:
count = min(2*count, len(barriers))
return cost
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None):
def maneuver(self, points, pose, target, prior, excluded, geometry, now, candidate_mask=None, experience_cost=None):
"""Measured local destinations may temporarily move away from the task.
This removes the greedy progress constraint ONLY during a surveyed
@@ -254,6 +254,8 @@ class ObservedGoals:
score = np.linalg.norm(candidates[:, :2]-target, axis=1) + .2*turning + .15*distance
score += self.boundary_cost(candidates, geometry, now)
score += self.clearance_cost(candidates, pose, geometry, now)[0]
if experience_cost is not None:
score += np.asarray(experience_cost(pose, candidates))
# Recovery actions need a fair turn, as in Nav2's RoundRobin recovery
# subtree. Distance-to-task alone can spend every retry on almost the
# same forward approach before ever considering a measured retreat.
+11 -1
View File
@@ -380,6 +380,7 @@ class NavigationClient:
class ComposedInference:
experience = None
def __init__(self, root: Path, run, directory: Path, mission=None):
profile = json.loads((root / "models.worker-006.json").read_text())
self.graph = compose(root, run["request"].get("composition"))
@@ -433,6 +434,10 @@ class ComposedInference:
self.navigation_evidence = {}
self.pool = ThreadPoolExecutor(max_workers=2, thread_name_prefix="simulation-module")
self.directory = directory
self.experience = None
if run.get("_spatial_experience_root") and run["world"].get("collider_sha256"):
from experience_adapter import ExperienceAdapter
self.experience = ExperienceAdapter(run, self.inputs, directory)
names = self.models.labels
if self.segmenter_id == "simulation-sam3-surfaces":
from k1link.simulation.ai_polygon.concept_surfaces import LABELS
@@ -655,7 +660,8 @@ class ComposedInference:
return observed_goals.maneuver(
inputs["source.lidar"], inputs["source.pose"], target, prior, excluded,
self.geometry, time.monotonic(), self.mission.goals_permitted
if isinstance(self.mission, RoutedMission) else None)
if isinstance(self.mission, RoutedMission) else None,
experience_cost=self.experience.costs if self.experience else None)
self.goal, intent = self.mission.update(
inputs["source.pose"],
@@ -1020,6 +1026,8 @@ class ComposedInference:
# direction and this transaction's range/support gates. It does
# not use the older local translation goal retained during survey.
self.intent_captured_at = calibration["captured_at"]
if self.experience is not None:
self.experience.observe(inputs, self.goal, result)
self.navigation_evidence = {
"mission": intent,
"environment": self.environment,
@@ -1199,6 +1207,8 @@ class ComposedInference:
)
def close(self):
if self.experience is not None:
self.experience.close()
self.pool.shutdown(wait=True, cancel_futures=True)
self.models.close()
self.navigation.close()
+26
View File
@@ -93,6 +93,15 @@ def publish_previews(client, episode, run_id, stopped):
stopped.wait(1)
def publish_experience(client, episode, world_id):
"""Publish the last bounded summary, including the child writer's final flush."""
from k1link.simulation.ai_polygon.spatial_experience import read as read_experience
path = episode / "spatial-experience.json"
if path.exists():
client.request("/worker/worlds/" + world_id + "/spatial-experience", read_experience(path))
def preparation_heartbeat(client, hello, run_id):
"""One-thread lease/control pulse; reconnect only this same expired owner."""
last_poll = -float("inf")
@@ -189,6 +198,7 @@ def main():
"project_assets.py",
"decode_collision.cjs",
"navigation_client.py",
"experience_adapter.py",
"route_view.py",
"observer_camera.py",
"inference_preview.py",
@@ -384,6 +394,7 @@ def main():
raise RuntimeError("An existing episode must never be replayed")
episode = create_episode(args.state, run["run_id"], args.evidence_root)
run_file = episode / "run.json"
run["_spatial_experience_root"] = str(args.state / "spatial-experience")
write_json(run_file, run)
channel = StateChannel(episode)
channel.write("control", run)
@@ -438,6 +449,7 @@ def main():
):
raise ValueError("Saved task and simulation surface identities differ")
run["terrain_manifest"] = str(terrain_path)
run["_spatial_experience_root"] = str(args.state / "spatial-experience")
write_json(run_file, run)
with (episode / "isaac.log").open("wb") as output:
child = subprocess.Popen(
@@ -484,6 +496,8 @@ def main():
stop_deadline = None
last_snapshot = -1
experience_stamp = None
experience_checked = -float("inf")
preview_sender = threading.Thread(
target=publish_previews,
args=(client, episode, run["run_id"], preview_stopped),
@@ -531,6 +545,14 @@ def main():
if snapshot and snapshot["sequence"] > last_snapshot:
client.request("/worker/runs/" + run["run_id"] + "/snapshot", snapshot)
last_snapshot = snapshot["sequence"]
if now-experience_checked >= 5:
experience_checked = now
memory_file = episode / "spatial-experience.json"
if memory_file.exists():
stamp = memory_file.stat().st_mtime_ns
if stamp != experience_stamp:
publish_experience(client, episode, run["world"]["world_id"])
experience_stamp = stamp
except Exception as exc:
registered = False
logging.warning(
@@ -595,6 +617,10 @@ def main():
while True:
try:
client.request("/worker/register", hello)
try:
publish_experience(client, episode, run["world"]["world_id"])
except Exception:
logging.exception("Final location experience sync pending; worker copy retained")
client.request(
"/worker/runs/" + run["run_id"] + "/finish",
finish,
+13
View File
@@ -0,0 +1,13 @@
# Reuse the worker's pinned CUDA/PyTorch runtime; model assets stay outside the image.
ARG BASE_IMAGE=ndc-mission-core-m48t-upstream-parity:1.9.4-cu130
FROM ${BASE_IMAGE}
LABEL com.nodedc.product="mission-core" com.nodedc.stack="urban-mapping" \
com.nodedc.role="offline-infrastructure-detector" com.nodedc.managed-by="compose"
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=4 \
MAX_JOBS=4 TORCH_CUDA_ARCH_LIST=8.9 HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
RUN python3 -m pip uninstall --break-system-packages -y rfdetr && python3 -m pip install --break-system-packages --no-cache-dir \
gsplat==1.5.3 plyfile==1.1.3 pillow==11.3.0 opencv-python-headless==4.11.0.86 \
transformers==4.44.2 shapely==2.1.2 ninja==1.13.0 rasterio==1.4.3 ezdxf==1.4.3
WORKDIR /app
COPY *.py /app/
ENTRYPOINT ["python3", "-B", "/app/mapping.py"]
+65
View File
@@ -0,0 +1,65 @@
# Urban infrastructure mapping
Independent offline batch module. It renders a bounded Gaussian tile, runs the
pinned Mapillary Mask2Former on perspective views, projects depth-visible ground
observations into a metric atlas, and exports closed XYZ contours as JSON and 3D DXF.
The orthographic view supplies a height reference and visual inspection image;
it is not passed to the street-view semantic model. Model preprocessing is the
original downloaded processor configuration.
## Run on a GPU worker
Requires Linux containers, NVIDIA Container Toolkit, a CUDA-compatible NVIDIA GPU,
Docker Compose with GPU support, and the base CUDA/PyTorch image supplied separately.
Qualified on Worker006 (Windows/WSL Docker, RTX4090). On this worker, use
`DOCKER_BUILDKIT=0 docker compose build mapper`: its BuildKit image exporter
currently fails through a Windows credential helper in SSH sessions; the classic
builder completes from the same versioned Dockerfile without changing host settings. No CPU or Mac inference fallback.
CUDA kernels target Ada (8.9); rebuild with a suitable architecture for another GPU.
Do not schedule alongside a simulation that needs the same GPU.
1. Build `docker compose build mapper` on the worker. The default base image is
`ndc-mission-core-m48t-upstream-parity:1.9.4-cu130`; set `MAPPING_BASE_IMAGE` for a
supplied compatible runtime. The accepted base identity is recorded in qualification.
2. Set `MAPPING_INPUT`, `MAPPING_MODEL`, `MAPPING_OUTPUT` to absolute worker directories.
The first two mounts are read-only. Place the job contract in `MAPPING_OUTPUT/job.json`.
3. Run `docker compose run --rm mapper`. Runtime network is disabled. Model files
must already be downloaded and checksummed; the container does not fetch weights.
4. Run synthetic checks with `docker compose run --rm --entrypoint python3 mapper -m unittest test_mapping`.
5. Publish `urban-map.json` using the existing worker bearer credential to
`POST /api/v1/ai-polygon/worker/worlds/{world_id}/urban-map`.
The API rejects a different world or collider revision. No credentials belong in jobs.
The job uses schema `missioncore.urban-mapping-job/v1`: source PLY filename/SHA-256,
world and collider SHA-256, a rigid `source_to_world` matrix; model repository,
revision and per-file SHA-256; XY bounds; optional cell size (default 0.1 m), halo,
confidence and observation quorum; one vertical orthographic reference plus
perspective cameras with eye/target/up, image size and horizontal field of view.
Use scene-local metres with Z up. This is not a georeferenced GIS dataset.
Bounds are limited to one million cells, 32 views and 2048 pixels per dimension.
Camera placement must be reviewed: an eye inside a building is not a valid survey.
`--stage render|infer|atlas` supports repeatable phases. Every downstream phase checks
camera/source/model identity and input hashes; stale cached frames are rejected.
Source code hashes, output hashes and elapsed time are saved in the final receipt.
Retain the accepted job, receipts and previews outside Git, in simulation qualification.
## Interpretation
The 3D export currently contains ground infrastructure: carriageway, sidewalk,
pedestrian/bicycle areas, curbs, curb cuts, parking and markings. Per-view overlays
also show the model's building, pole and sign classes; these are not surveyed 3D
building footprints or a connected intersection graph. An output format compatible
with XYZ polygon features allows future providers without changing the viewer.
Labels are observations, never route permissions. Gaussian expected depth is
approximate and view-dependent. Occluded, low-confidence and conflicting areas
remain unknown; vectorization preserves holes and does not bridge gaps. Tiny
components below 0.08 square metres are omitted. The 0.1 m cell size is sampling
resolution, not a claim of 10 cm survey accuracy. Crosswalk markings can be confused
with other road markings. Review coverage and contours before route integration.
In planning, the infrastructure toggle is independent of Gaussian/collision layers.
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.
+128
View File
@@ -0,0 +1,128 @@
"""Fuse depth-visible street-view observations into a metric surface atlas."""
import numpy as np
from PIL import Image
GROUND = [2, 7, 8, 9, 10, 11, 13, 14, 15, 23, 24]
def fuse(job, output, unproject, classes, write_json):
bounds = np.asarray(job['bounds_xy'], dtype=float)
cell = job.get('cell_m', .1)
width, height = np.ceil((bounds[1] - bounds[0]) / cell).astype(int)
count = width * height
evidence = np.zeros((len(GROUND), count), np.float32)
observed = np.zeros(count, np.uint16)
zsum = np.zeros(count, np.float64)
reference = next(v for v in job['views'] if v.get('projection') == 'ortho')
gtop = np.load(output / (reference['id'] + '.geometry.npz'))
vtop, ktop = gtop['view'], gtop['intrinsics']
if not np.allclose(vtop[2, :3], [0, 0, -1], atol=1e-6):
raise ValueError('The reference atlas requires a vertical orthographic view')
yy, xx = np.indices((height, width))
xyz = np.column_stack([bounds[0, 0] + (xx.ravel() + .5) * cell,
bounds[0, 1] + (height - yy.ravel() - .5) * cell,
np.zeros(count)])
projected = xyz @ vtop[:3, :3].T + vtop[:3, 3]
uv = projected[:, :2] * np.diag(ktop)[:2] + ktop[:2, 2] - .5
col, row = np.rint(uv).astype(int).T
th, tw = gtop['depth'].shape
inside = (col >= 0) & (col < tw) & (row >= 0) & (row < th)
col, row = np.clip(col, 0, tw - 1), np.clip(row, 0, th - 1)
xyz[:, 2] = vtop[2, 3] - gtop['depth'][row, col]
reference_valid = inside & (gtop['alpha'][row, col] >= .95) & np.isfinite(xyz).all(axis=1)
# Pull each metric cell into each camera. This covers the pixel footprint without
# interpolating labels across unobserved gaps between forward-projected rays.
for spec in job['views']:
if spec.get('projection', 'pinhole') != 'pinhole':
continue
labels = np.array(Image.open(output / (spec['id'] + '.labels.png')))
confidence = np.load(output / (spec['id'] + '.confidence.npy'))
g = np.load(output / (spec['id'] + '.geometry.npz'))
local = xyz @ 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
col, row = np.rint(uv).astype(int).T
ih, iw = labels.shape
visible = reference_valid & (depth > .1) & (depth <= 30) & (col >= 0) & (col < iw) & (row >= 0) & (row < ih)
col, row = np.clip(col, 0, iw - 1), np.clip(row, 0, ih - 1)
seen_depth = g['depth'][row, col]
visible &= (g['alpha'][row, col] >= .95) & (np.abs(depth - seen_depth) <= np.maximum(.15, depth * .01))
sampled = labels[row, col]
visible &= np.isin(sampled, GROUND)
for i, label in enumerate(GROUND):
hit = visible & (sampled == label)
evidence[i, hit] += confidence[row[hit], col[hit]]
zsum[visible] += xyz[visible, 2]
observed[visible] += 1
winner = evidence.argmax(axis=0)
strength = evidence.max(axis=0) / np.maximum(evidence.sum(axis=0), 1e-6)
z = zsum / np.maximum(observed, 1)
accepted = (observed >= job.get('min_views', 1)) & (strength >= .7)
labels = np.where(accepted, np.asarray(GROUND)[winner], 255).reshape(height, width).astype(np.uint8)
z = z.reshape(height, width)
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)
rgb = np.full((height, width, 3), [25, 28, 32], np.uint8)
features = []
import rasterio.features
from affine import Affine
from shapely.geometry import shape
from shapely import make_valid
transform = Affine(cell, 0, bounds[0, 0], 0, -cell, bounds[0, 1] + height * cell)
for label in GROUND:
rgb[labels == label] = classes[label][1]
for geometry, value in rasterio.features.shapes(labels, mask=labels != 255, transform=transform, connectivity=4):
label = int(value)
# Raster diagonal contacts can produce point-touching rings. GEOS separates
# those contacts; retain only polygons and never expand into unknown cells.
candidate = make_valid(shape(geometry))
polygons = [candidate] if candidate.geom_type == 'Polygon' else [p for p in candidate.geoms if p.geom_type == 'Polygon']
def ring(coords):
result = []
for x, y in coords:
col = (x - bounds[0, 0]) / cell
row = (bounds[0, 1] + height * cell - y) / cell
adjacent = [(r, c) for r in [round(row) - 1, round(row)] for c in [round(col) - 1, round(col)]
if 0 <= r < height and 0 <= c < width and labels[r, c] == label and np.isfinite(z[r, c])]
if not adjacent:
raise ValueError('Contour vertex has no observed height support')
result.append([round(x, 4), round(y, 4), round(float(np.mean([z[r, c] for r, c in adjacent])), 4)])
return result
for polygon in polygons:
if polygon.area < .08:
continue
geometry3d = {'type': 'Polygon', 'coordinates': [ring(polygon.exterior.coords), *[ring(h.coords) for h in polygon.interiors]]}
name, color = classes[label]
features.append({'type': 'Feature', 'id': f'atlas-{label}-{len(features)}',
'properties': {'class': name, 'model_label': label, 'color': color, 'authority': 'observation-only',
'height_source': 'gaussian-depth-with-camera-visibility', 'review': 'required', 'route_permission': 'unassigned'},
'geometry': geometry3d})
Image.fromarray(rgb).save(output / 'surface-atlas.png')
document = {'schema_version': 'missioncore.urban-map/v1', 'type': 'FeatureCollection',
'coordinate_system': {'frame': 'scene-local', 'units': 'metres', 'up': 'Z', 'georeferenced': False},
'source': job['source'], 'model': job['model'], 'features': features,
'coverage': {'bounds_xy': bounds.tolist(), 'cell_m': cell, 'observed_cells': int((observed > 0).sum()),
'accepted_cells': int(accepted.sum()), 'multi_view_cells': int((accepted & (observed >= 2)).sum())},
'limitations': ['Partial observed surface; not a complete surveyed map',
'Unknown remains unknown; no hole filling', 'Crosswalk markings do not grant route permission',
'Gaussian depth is approximate; collision and live obstacles remain independent']}
write_json(output / 'urban-map.json', document)
export_dxf(document, output / 'urban-map.dxf')
return document
def export_dxf(document, path):
import ezdxf
drawing = ezdxf.new('R2013')
drawing.units = 6 # metres
for feature in document['features']:
name = feature['properties']['class']
if name not in drawing.layers:
layer = drawing.layers.new(name)
layer.rgb = tuple(feature['properties'].get('color', {'curb':[245,130,48], 'crosswalk_area':[255,225,35], 'crosswalk_marking':[255,225,35]}.get(name,[245,245,245])))
polygon = feature['geometry']['type'] == 'Polygon'
paths = feature['geometry']['coordinates'] if polygon else [feature['geometry']['coordinates']]
for ring in paths:
drawing.modelspace().add_polyline3d(ring[:-1] if polygon else ring, close=polygon, dxfattribs={'layer': name})
drawing.saveas(path)
+35
View File
@@ -0,0 +1,35 @@
name: ndc-urban-mapping
services:
mapper:
image: ndc-mission-core-urban-mapping:${MAPPING_VERSION:-v1}
build:
context: .
args:
BASE_IMAGE: ${MAPPING_BASE_IMAGE:-ndc-mission-core-m48t-upstream-parity:1.9.4-cu130}
gpus: all
cpus: 4
mem_limit: 16g
shm_size: 1g
network_mode: none
restart: "no"
labels:
com.nodedc.product: mission-core
com.nodedc.stack: urban-mapping
com.nodedc.role: offline-infrastructure-detector
com.nodedc.managed-by: compose
environment:
TORCH_EXTENSIONS_DIR: /cache/torch
volumes:
- ${MAPPING_INPUT:?set source directory}:/input:ro
- ${MAPPING_MODEL:?set model directory}:/model:ro
- ${MAPPING_OUTPUT:?set output directory}:/output
- ndc-urban-mapping-cache:/cache
command: ["--job", "/output/job.json", "--output", "/output"]
volumes:
ndc-urban-mapping-cache:
name: ndc-urban-mapping-cache
labels:
com.nodedc.product: mission-core
com.nodedc.stack: urban-mapping
com.nodedc.role: cuda-kernel-cache
com.nodedc.managed-by: compose
+102
View File
@@ -0,0 +1,102 @@
{
"schema_version": "missioncore.urban-mapping-job/v1",
"source": {
"ply": "scene.ply",
"sha256": "0000000000000000000000000000000000000000000000000000000000000000",
"world_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
"collider_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
"source_to_world": [
[
1,
0,
0,
0
],
[
0,
1,
0,
0
],
[
0,
0,
1,
0
],
[
0,
0,
0,
1
]
]
},
"bounds_xy": [
[
-10,
-10
],
[
10,
10
]
],
"halo_m": 25,
"min_confidence": 0.65,
"model": {
"repository": "facebook/mask2former-swin-large-mapillary-vistas-semantic",
"revision": "2cc022513f0012ff47d4438516284fd0946a196a",
"files": {
"config.json": "b40bec8d82de3b53ef967dce0496c37de520b69466f1a8d2f6c035700cbae9f3",
"preprocessor_config.json": "22ef0608c7add19c5e9a64f8eeba95b7d3d1237ef20bf14efead9d8bc671da9f",
"README.md": "b534d1a4be6fd8f61da29dde0887ccdffb18f866a1ab88da381fb585c9ba60c7",
"pytorch_model.bin": "8120d77b194b34527b5937a576c36291ae7e76157f57a22433480c19d71e1551"
}
},
"views": [
{
"id": "top",
"projection": "ortho",
"size": [
800,
800
],
"width_m": 20,
"eye": [
0,
0,
20
],
"target": [
0,
0,
0
],
"up": [
0,
1,
0
]
},
{
"id": "front",
"projection": "pinhole",
"size": [
800,
600
],
"eye": [
-5,
0,
1.5
],
"target": [
5,
0,
0
],
"fov_degrees": 90
}
]
}
+206
View File
@@ -0,0 +1,206 @@
"""Offline, artifact-scoped Gaussian → urban observations. Never commands a rover."""
import argparse
import hashlib
import json
import math
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
from PIL import Image
from validation import validate_job, fingerprint, phase_inputs
CLASSES = {
2: ('curb', [245, 130, 48]), 6: ('wall', [128, 100, 70]),
7: ('bike_lane', [150, 110, 220]), 8: ('crosswalk_area', [255, 225, 35]),
9: ('curb_cut', [255, 150, 80]), 10: ('parking', [140, 140, 150]),
11: ('pedestrian_area', [60, 220, 200]), 13: ('carriageway', [90, 130, 200]),
14: ('service_lane', [110, 150, 210]), 15: ('sidewalk', [60, 220, 200]),
17: ('building', [200, 120, 100]), 23: ('crosswalk_marking', [255, 225, 35]),
24: ('road_marking', [245, 245, 245]),
33: ('bench', [220, 70, 160]), 44: ('street_light', [200, 80, 220]),
45: ('pole', [180, 70, 230]), 48: ('traffic_light', [255, 80, 70]),
50: ('traffic_sign', [255, 100, 70]),
}
def digest(path):
with Path(path).open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def write_json(path, value):
temporary = path.with_suffix(path.suffix + '.tmp')
temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2))
temporary.replace(path)
def view_matrix(eye, target, up):
eye, target, up = map(lambda p: np.asarray(p, dtype=np.float64), (eye, target, up))
forward = target - eye
if np.linalg.norm(forward) < 1e-9 or np.linalg.norm(np.cross(forward, up)) < 1e-9:
raise ValueError('Degenerate camera orientation')
forward /= np.linalg.norm(forward)
right = np.cross(forward, up)
right /= np.linalg.norm(right)
down = np.cross(forward, right)
view = np.eye(4)
view[:3, :3] = [right, down, forward]
view[:3, 3] = -view[:3, :3] @ eye
return view
def camera(spec):
w, h = spec['size']
view = view_matrix(spec['eye'], spec['target'], spec.get('up', [0, 0, 1]))
model = spec.get('projection', 'pinhole')
focal = w / spec['width_m'] if model == 'ortho' else w / (2 * math.tan(math.radians(spec['fov_degrees']) / 2))
return view, np.array([[focal, 0, w / 2], [0, focal, h / 2], [0, 0, 1]], dtype=np.float32)
def unproject(pixels, depth, view, intrinsics, projection):
"""OpenCV pixels + camera-Z depth to scene-local XYZ in metres."""
uv = np.asarray(pixels, dtype=np.float64)
xy = (uv + 0.5 - intrinsics[:2, 2]) / np.diag(intrinsics)[:2]
if projection == 'pinhole':
xy *= np.asarray(depth)[:, None]
local = np.column_stack([xy, depth, np.ones(len(uv))])
return (local @ np.linalg.inv(view).T)[:, :3]
def render(job, output):
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')
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])
or not np.allclose(transform[:3, :3].T @ transform[:3, :3], np.eye(3), atol=1e-5)
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 not len(d):
raise ValueError('No Gaussians in the requested tile')
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, :]
rest_names = sorted((n for n in d.dtype.names if n.startswith('f_rest_')), key=lambda n: int(n.split('_')[-1]))
sh = torch.cat([dc, tensor(rest_names).reshape(len(d), 3, -1).transpose(1, 2)], dim=1) if rest_names else dc
degree = int(math.sqrt(sh.shape[1])) - 1
print(json.dumps({'stage': 'render', 'source_splats': len(data), 'tile_splats': len(d), 'sh_degree': degree}), flush=True)
for spec in job['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=spec.get('projection', 'pinhole'), render_mode='RGB+ED',
packed=True)
rgbd, alpha = rgbd[0].cpu().numpy(), alpha[0, :, :, 0].cpu().numpy()
rgbd[:, :, :3] += (1 - alpha[:, :, None])
Image.fromarray(np.uint8(np.clip(rgbd[:, :, :3], 0, 1) * 255)).save(output / (spec['id'] + '.png'))
np.savez_compressed(output / (spec['id'] + '.geometry.npz'), depth=rgbd[:, :, 3], alpha=alpha, view=view, intrinsics=k)
write_json(output / (spec['id'] + '.render.json'), {'inputs': phase_inputs(job, spec),
'files': {spec['id'] + ext: digest(output / (spec['id'] + ext)) for ext in ['.png', '.geometry.npz']}})
print(json.dumps({'view': spec['id'], 'opaque_fraction': float(np.mean(alpha >= .95))}), flush=True)
def infer(job, output):
import torch
from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
model_path = Path('/model')
for name, expected in job['model']['files'].items():
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()
for spec in job['views']:
if spec.get('projection', 'pinhole') != 'pinhole':
continue # Mapillary is a street-view model; orthographic views are review only.
verify_phase(output, spec['id'] + '.render.json', phase_inputs(job, spec))
image = Image.open(output / (spec['id'] + '.png')).convert('RGB')
inputs = processor(images=image, return_tensors='pt').to('cuda')
with torch.inference_mode():
result = model(**inputs)
# Same query aggregation as the upstream semantic postprocessor; retain a confidence plane.
classes = result.class_queries_logits.softmax(-1)[..., :-1]
masks = torch.nn.functional.interpolate(result.masks_queries_logits, size=(image.height, image.width), mode='bilinear', align_corners=False).sigmoid()
scores = torch.einsum('bqc,bqhw->bchw', classes, masks)[0]
value, labels = scores.max(0)
confidence = value / scores.sum(0).clamp_min(1e-6)
labels, confidence = labels.byte().cpu().numpy(), confidence.cpu().numpy()
geometry = np.load(output / (spec['id'] + '.geometry.npz'))
valid = (geometry['alpha'] >= .95) & np.isfinite(geometry['depth']) & (geometry['depth'] > 0)
labels[(confidence < job.get('min_confidence', .65)) | ~valid] = 255
Image.fromarray(labels).save(output / (spec['id'] + '.labels.png'))
np.save(output / (spec['id'] + '.confidence.npy'), confidence)
base = np.asarray(image).copy()
overlay = base.copy()
for cls, (name, color) in CLASSES.items():
overlay[labels == cls] = np.uint8(.45 * base[labels == cls] + .55 * np.array(color))
Image.fromarray(overlay).save(output / (spec['id'] + '.overlay.png'))
write_json(output / (spec['id'] + '.inference.json'), {'inputs': inference_inputs(job, spec),
'files': {spec['id'] + ext: digest(output / (spec['id'] + ext)) for ext in ['.labels.png', '.confidence.npy']}})
print(json.dumps({'view': spec['id'], 'stage': 'inference', 'pixels': {CLASSES[c][0]: int((labels == c).sum()) for c in CLASSES if np.any(labels == c)}, 'unknown': int((labels == 255).sum())}), flush=True)
def inference_inputs(job, spec):
return fingerprint({'render': phase_inputs(job, spec), 'model': job['model'], 'confidence': job.get('min_confidence', .65)})
def verify_phase(output, manifest, expected):
receipt = json.loads((output / manifest).read_text())
if receipt['inputs'] != expected or any(digest(output / name) != sha for name, sha in receipt['files'].items()):
raise ValueError('Stale or changed phase input: ' + manifest)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--job', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--stage', choices=['render', 'infer', 'atlas', 'all'], default='all')
args = parser.parse_args()
job = validate_job(json.loads(args.job.read_text()))
args.output.mkdir(parents=True, exist_ok=True)
started = time.monotonic()
from atlas import fuse
def atlas(job, output):
for spec in job['views']:
verify_phase(output, spec['id'] + '.render.json', phase_inputs(job, spec))
if spec.get('projection', 'pinhole') == 'pinhole':
verify_phase(output, spec['id'] + '.inference.json', inference_inputs(job, spec))
document = fuse(job, output, unproject, CLASSES, write_json)
print(json.dumps({'stage': 'atlas', 'features': len(document['features']), 'coverage': document['coverage']}), flush=True)
for name, fn in [('render', render), ('infer', infer), ('atlas', atlas)]:
if args.stage in ['all', name]:
fn(job, args.output)
write_json(args.output / ('receipt-' + args.stage + '.json'), {
'schema_version': 'missioncore.urban-mapping-receipt/v1', 'utc': datetime.now(timezone.utc).isoformat(),
'elapsed_s': time.monotonic() - started, 'job_sha256': digest(args.job), 'stage': args.stage,
'implementation': {p.name: digest(p) for p in Path(__file__).parent.glob('*.py')},
'files': {p.name: digest(p) for p in args.output.iterdir() if p.is_file() and not p.name.startswith('receipt-')},
})
if __name__ == '__main__':
main()
+64
View File
@@ -0,0 +1,64 @@
"""Synthetic geometry checks; these do not qualify semantic accuracy."""
import json
import tempfile
import unittest
from pathlib import Path
import numpy as np
from PIL import Image
from atlas import fuse
from mapping import CLASSES, camera, unproject, write_json, verify_phase, digest
from validation import fingerprint, filename
class MappingChecks(unittest.TestCase):
def test_camera_roundtrip(self):
for projection in ['pinhole', 'ortho']:
spec = dict(eye=[3, 4, 8], target=[10, -2, 1], size=[800, 600], fov_degrees=90, width_m=40, projection=projection)
view, k = camera(spec)
pixels = np.array([[0, 0], [200, 500], [799, 599]])
xyz = unproject(pixels, np.array([3, 8, 20]), view, k, projection)
local = xyz @ view[:3, :3].T + view[:3, 3]
uv = local[:, :2] / (local[:, 2:] if projection == 'pinhole' else 1)
np.testing.assert_allclose(uv * np.diag(k)[:2] + k[:2, 2] - .5, pixels, atol=1e-8)
def test_invalid_camera(self):
with self.assertRaises(ValueError):
camera(dict(eye=[0, 0, 0], target=[0, 0, 1], size=[100, 100], fov_degrees=90))
def test_paths_and_phase_integrity(self):
for name in ['../secret', '/absolute', 'sub/file', 'sub\\file', '..']:
with self.assertRaises(ValueError): filename(name)
with tempfile.TemporaryDirectory() as directory:
p=Path(directory);(p/'data').write_text('original')
write_json(p/'receipt.json', {'inputs':fingerprint({'a':1}), 'files':{'data':digest(p/'data')}})
verify_phase(p,'receipt.json',fingerprint({'a':1}))
with self.assertRaises(ValueError): verify_phase(p,'receipt.json',fingerprint({'a':2}))
(p/'data').write_text('changed')
with self.assertRaises(ValueError): verify_phase(p,'receipt.json',fingerprint({'a':1}))
def test_unknown_holes_and_occlusion(self):
with tempfile.TemporaryDirectory() as directory:
output=Path(directory)
job={'bounds_xy':[[-3,-3],[3,3]],'cell_m':1,'source':{},'model':{}, 'views':[
{'id':'top','projection':'ortho','eye':[0,0,10],'target':[0,0,0],'up':[0,1,0],'size':[6,6],'width_m':6},
{'id':'front','eye':[0,0,10],'target':[0,0,0],'up':[0,1,0],'size':[6,6],'fov_degrees':33.39848846798724}]}
for spec in job['views']:
view,k=camera(spec)
np.savez(output/(spec['id']+'.geometry.npz'),depth=np.full((6,6),10),alpha=np.ones((6,6)),view=view,intrinsics=k)
labels=np.full((6,6),13,np.uint8);labels[2:4,2:4]=255
Image.fromarray(labels).save(output/'front.labels.png');np.save(output/'front.confidence.npy',np.ones((6,6)))
result=fuse(job,output,unproject,CLASSES,write_json)
self.assertEqual(result['coverage']['accepted_cells'],32)
self.assertEqual(len(result['features']),1)
self.assertEqual(len(result['features'][0]['geometry']['coordinates']),2)
import ezdxf
drawing=ezdxf.readfile(output/'urban-map.dxf')
self.assertEqual(drawing.units,6)
self.assertEqual(len(drawing.modelspace().query('POLYLINE')),2)
view,k=camera(job['views'][1])
np.savez(output/'front.geometry.npz',depth=np.full((6,6),5),alpha=np.ones((6,6)),view=view,intrinsics=k)
blocked=fuse(job,output,unproject,CLASSES,write_json)
self.assertEqual(blocked['coverage']['accepted_cells'],0)
self.assertEqual(blocked['features'],[])
if __name__=='__main__': unittest.main()
+75
View File
@@ -0,0 +1,75 @@
"""Bounded job contract and phase identity; no model dependencies."""
import hashlib
import json
import math
import re
from pathlib import PurePosixPath
def fingerprint(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False).encode()).hexdigest()
def filename(value):
if not isinstance(value, str) or not value or PurePosixPath(value).name != value or "\\" in value or value in {".", ".."}:
raise ValueError('Asset names must be relative filenames')
def validate_job(job):
if job.get('schema_version') != 'missioncore.urban-mapping-job/v1':
raise ValueError('Unsupported mapping job')
source = job['source']
filename(source['ply'])
for name in ('sha256', 'world_sha256', 'collider_sha256'):
if not re.fullmatch('[0-9a-f]{64}', source[name]):
raise ValueError('A mapping job requires immutable source identities')
model = job['model']
if model['repository'] != 'facebook/mask2former-swin-large-mapillary-vistas-semantic':
raise ValueError('This provider requires Mapillary Vistas labels')
for name, sha in model['files'].items():
filename(name)
if not re.fullmatch('[0-9a-f]{64}', sha):
raise ValueError('Invalid model asset identity')
if not {'config.json', 'preprocessor_config.json', 'pytorch_model.bin'} <= model['files'].keys():
raise ValueError('Incomplete model manifest')
def vector(value, length):
if not isinstance(value, list) or len(value) != length or any(type(v) not in (int, float) or not math.isfinite(v) for v in value):
raise ValueError('Invalid finite coordinate vector')
bounds = job['bounds_xy']
if len(bounds) != 2:
raise ValueError('Invalid atlas bounds')
for point in bounds:
vector(point, 2)
cell = job.get('cell_m', .1)
if not .02 <= cell <= 1 or any(b <= a for a, b in zip(*bounds)):
raise ValueError('Invalid atlas extent or cell size')
if math.prod(math.ceil((b-a)/cell) for a, b in zip(*bounds)) > 1_000_000:
raise ValueError('Split the scene into bounded tiles (maximum 1 million cells)')
if not 0 <= job.get('halo_m', 15) <= 50 or not 0 <= job.get('min_confidence', .65) <= 1:
raise ValueError('Invalid mapping thresholds')
views = job['views']
if not 2 <= len(views) <= 32 or sum(v.get('projection', 'pinhole') == 'ortho' for v in views) != 1:
raise ValueError('Use one orthographic reference and 1–31 perspective views')
identifiers = set()
for v in views:
if not re.fullmatch('[a-zA-Z0-9_-]{1,64}', v['id']) or v['id'] in identifiers:
raise ValueError('View identifiers must be unique safe names')
identifiers.add(v['id'])
if len(v['size']) != 2 or any(type(n) is not int or not 64 <= n <= 2048 for n in v['size']):
raise ValueError('Unsupported render dimensions')
for name in ('eye', 'target'):
vector(v[name], 3)
vector(v.get('up', [0, 0, 1]), 3)
projection = v.get('projection', 'pinhole')
if projection == 'ortho':
if not 0 < v['width_m'] <= 200:
raise ValueError('Invalid orthographic width')
elif projection != 'pinhole' or not 10 <= v['fov_degrees'] <= 130:
raise ValueError('Invalid perspective camera')
if type(job.get('min_views', 1)) is not int or not 1 <= job.get('min_views', 1) < len(views):
raise ValueError('Invalid observation quorum')
return job
def phase_inputs(job, spec):
return fingerprint({'source': job['source'], 'bounds': job['bounds_xy'], 'halo': job.get('halo_m', 15), 'view': spec})
@@ -0,0 +1,6 @@
*
!Dockerfile
!*.py
!.build
!.build/vma-source.tar.gz
!.build/terrain.py
@@ -0,0 +1,2 @@
.build/
__pycache__/
@@ -0,0 +1,21 @@
ARG BASE_IMAGE=ndc/mission-core-lab-v1-goose:sg3.2.0-cu117-v1
FROM ${BASE_IMAGE}
LABEL com.nodedc.product="mission-core" com.nodedc.stack="urban-mapping" com.nodedc.role="vector-extractor" com.nodedc.managed-by="compose"
ENV PATH=/opt/conda/envs/goose/bin:$PATH PYTHONUNBUFFERED=1 OMP_NUM_THREADS=4 PYTHONDONTWRITEBYTECODE=1
RUN python -m pip install --no-cache-dir numpy==1.23.5 yapf==0.40.1 \
https://download.openmmlab.com/mmcv/dist/cu117/torch1.13.0/mmcv_full-1.7.0-cp39-cp39-manylinux1_x86_64.whl \
mmdet==2.28.2 mmsegmentation==0.30.0 shapely==1.8.5.post1 \
numba==0.57.1 scikit-image==0.19.3 scikit-learn==1.3.0 \
nuscenes-devkit==1.1.9 lyft-dataset-sdk==0.0.8 plyfile==0.7.4 \
trimesh==3.23.5 networkx==2.8.8 similaritymeasures==0.6.0 \
gdown==5.2.0 einops==0.6.1 timm==0.6.13
RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation mmdet3d==1.0.0rc6
ADD .build/vma-source.tar.gz /opt/
ENV PYTHONPATH=/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e
WORKDIR /opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e
RUN python -c "import torch,mmcv,mmdet,mmdet3d; import projects.mmdet3d_plugin; print(torch.__version__,mmcv.__version__,mmdet3d.__version__)"
ENTRYPOINT ["/opt/conda/envs/goose/bin/python"]
COPY *.py /app/
COPY .build/terrain.py /app/terrain.py
ENV PYTHONPATH=/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e
+42
View File
@@ -0,0 +1,42 @@
# Vector infrastructure module
Offline GPU batch container, separate from simulation and the Gaussian renderer.
Qualified on Worker006, NVIDIA RTX4090 / Windows Docker WSL. No Mac inference.
VMA source MIT, author repository https://github.com/hustvl/VMA, commit and public
checkpoint hashes pinned in `assets.py`. Author code is loaded unchanged. The
installed CUDA11.7 / Torch1.13.1 base is an explicit external image prerequisite;
this is portability to a similarly provisioned NVIDIA worker, not arbitrary-host support.
Prepare source on the worker: `python prepare.py --source .build`. This also
packages the canonical simulation GLB coordinate loader; it never forks it.
Build with `DOCKER_BUILDKIT=0 docker compose build vectorizer` on Worker006.
The environment workaround affects only this build command. Prepare public weights
with the built image, explicit network enabled and only the model directory mounted:
`python /app/prepare.py --weights /assets`. Runtime mounts in `compose.yaml` are
read-only except outputs; inference runs with network disabled.
Supply `VECTOR_INPUT`, `VECTOR_ASSETS`, `VECTOR_PACKAGE`, `VECTOR_OUTPUT`. Run
`docker compose run --rm vectorizer` for native 1000x1000 overlapping model crops.
Then run the same service with `/app/vector_map.py --candidates /output/candidates.json
--job /input/job.json --image /input/crossing-top.png --geometry
/input/crossing-top.geometry.npz --atlas /input/surface-atlas.npz --package /package
--output /output`. Input images, calibration, observed ground atlas and job come
from the parent mapping module. Use the parent `atlas.export_dxf` for XYZ DXF.
The measured source and collider revisions remain attached to every product.
Outputs are line objects and polygon footprints, not contours of every mask pixel.
The upstream decoder's automatic threshold relaxation is disabled. Fixed confidence
and cross-crop suppression retain empty results. Actual visible stripe paint is fit
only inside a model-detected zebra envelope; missing stripes are not invented.
Heights are intersections with the original collider, checked against rendered
visible ground. Missing/occluded sections stay open; the collider is never modified.
All products remain observation-only, unreviewed, without route permission.
Accepted engineering scope: a visually inspected 60m crossing tile, two crossing
areas and 14 stripe footprints. Arrow boxes are excluded: their paint geometry did not pass visual acceptance.
Curbs remain partial, labels may be wrong, and
Gaussian top views distort building sides. This is not a survey accuracy claim,
complete city topology, building-footprint map, or a LiDAR360MLS equivalent.
The same versioned module can process further tiles; each needs coverage and visual
acceptance before using it as a planning constraint. The UI keeps Gaussian,
collision, combined and vector-plan views in the existing scene.
@@ -0,0 +1,7 @@
"""Pinned public author releases; no private scene leaves the worker."""
COMMIT = "a6e98e8f704e72499b33da84715ba39e8705e02e"
ARCHIVE_SHA = "758fe52c4831d0a66dfd6578d789e63c8680e43a7d57ef9f51b5d6424d469b80"
WEIGHTS = {
"sd_line.pth": {"drive_id":"1hDmSJ8As5Ur-IF232knLBbjnlZZXV4PK", "sha256":"84c594317fea56118cb3e80aaf346f5eaa05c9a815c2b18022cece002ad9b54d"},
"sd_box.pth": {"drive_id":"1Sy3fD6fVSSM2oFf11z3WaKC3LH6sRy_j", "sha256":"85010253a1619b8cf493da2353a7ff57908b4915366a580d38b02a633dfb062b"},
}
@@ -0,0 +1,24 @@
name: ndc-vector-mapping
services:
vectorizer:
image: ndc-mission-core-vector-mapping:${VECTOR_VERSION:-vma3}
build:
context: .
dockerfile: Dockerfile
gpus: all
cpus: 4
mem_limit: 12g
shm_size: 1g
network_mode: none
restart: "no"
labels:
com.nodedc.product: mission-core
com.nodedc.stack: urban-mapping
com.nodedc.role: vector-extractor
com.nodedc.managed-by: compose
volumes:
- ${VECTOR_INPUT:?set rendered tile directory}:/input:ro
- ${VECTOR_ASSETS:?set pinned model directory}:/assets:ro
- ${VECTOR_PACKAGE:?set exact world package}:/package:ro
- ${VECTOR_OUTPUT:?set result directory}:/output
command: ["/app/infer_vectors.py", "--image", "/input/crossing-top.png", "--assets", "/assets", "--output", "/output"]
@@ -0,0 +1,73 @@
"""Bounded native VMA inference; no resampling, forced detections or route authority."""
import argparse, hashlib, json, time
from pathlib import Path
import numpy as np
import torch
import mmcv
from mmcv.runner import load_checkpoint
from mmdet3d.models import build_model
from PIL import Image
import projects.mmdet3d_plugin # registers the authors' detector unchanged
def sha(path):
h=hashlib.sha256()
with Path(path).open('rb') as stream:
for block in iter(lambda:stream.read(8*1024**2),b''):h.update(block)
return h.hexdigest()
def main():
p=argparse.ArgumentParser();p.add_argument('--image',type=Path,required=True)
p.add_argument('--assets',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--kinds',nargs='+',choices=['line','box'],default=['line','box'])
p.add_argument('--threshold',type=float,default=.3)
args=p.parse_args();args.output.mkdir(parents=True,exist_ok=True)
assert 0 < args.threshold <= 1, 'Invalid score threshold'
assert torch.cuda.is_available(),'GPU worker required'
torch.set_num_threads(4)
rgb=np.asarray(Image.open(args.image).convert('RGB'))
h,w=rgb.shape[:2]
assert 1000<=w<=4000 and 1000<=h<=4000,'Bounded native 1000-pixel crops required'
# Native model inputs are 1000x1000. Overlap keeps edge objects observable.
positions=[(x,y) for y in sorted(set([*range(0,h-999,800),h-1000]))
for x in sorted(set([*range(0,w-999,800),w-1000]))]
from assets import WEIGHTS
manifest=WEIGHTS
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()
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.
mean=image.new_tensor([.485,.456,.406])[:,None,None]
std=image.new_tensor([.229,.224,.225])[:,None,None]
with torch.inference_mode():
result=model(return_loss=False,rescale=True,img=((image-mean)/std)[None],
img_metas=[dict(img_shape=(1000,1000))])[0]['pts_bbox']
for i,score in enumerate(result['scores_3d'].tolist()):
if score<args.threshold:continue
label=int(result['labels_3d'][i]);points=result['pts_3d'][i].tolist()
points=[[a+x,b+y] for a,b in points]
predictions.append(dict(kind=kind,class_name=cfg.map_classes[label],score=score,
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,
elapsed_seconds=timings,authority='unreviewed-observations',features=predictions)
(args.output/'candidates.json').write_text(json.dumps(doc,indent=2,allow_nan=False))
print(json.dumps(dict(features=len(predictions),elapsed=timings)),flush=True)
if __name__=='__main__':main()
@@ -0,0 +1,32 @@
"""Explicit worker-only preparation, separate from network-isolated inference."""
import argparse, hashlib, json, urllib.request
from pathlib import Path
from assets import COMMIT, ARCHIVE_SHA, WEIGHTS
def digest(path):
h=hashlib.sha256()
with path.open('rb') as f:
for chunk in iter(lambda:f.read(8388608),b''):h.update(chunk)
return h.hexdigest()
def acquire(path, expected, download):
path.parent.mkdir(parents=True,exist_ok=True)
if path.exists() and digest(path)==expected:return
part=path.with_suffix(path.suffix+'.partial')
download(part)
if digest(part)!=expected:
part.unlink(missing_ok=True);raise ValueError('Downloaded artifact hash mismatch')
part.replace(path)
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--source',type=Path);p.add_argument('--weights',type=Path);a=p.parse_args()
if a.source:
import shutil
a.source.mkdir(parents=True,exist_ok=True)
shutil.copy2(Path(__file__).resolve().parents[2]/'ai-polygon/terrain.py',a.source/'terrain.py')
acquire(a.source/'vma-source.tar.gz',ARCHIVE_SHA,lambda path:urllib.request.urlretrieve('https://codeload.github.com/hustvl/VMA/tar.gz/'+COMMIT,path))
if a.weights:
import gdown
for name, item in WEIGHTS.items():
acquire(a.weights/name,item['sha256'],lambda path:gdown.download(id=item['drive_id'],output=str(path),quiet=False))
(a.weights/'manifest.json').write_text(json.dumps(WEIGHTS,indent=2))
@@ -0,0 +1,38 @@
"""Exact vertical intersections with the existing metric collider, bounded to a tile."""
import math
from collections import defaultdict
import numpy as np
from terrain import load_glb
class ColliderHeight:
def __init__(self,path,rotation,bounds,plane):
vertices,faces=load_glb(path,rotation)
triangles=vertices[faces];lo=triangles[:,:,:2].min(1);hi=triangles[:,:,:2].max(1)
bounds=np.asarray(bounds,float);centre=triangles.mean(1)
expected=np.column_stack([centre[:,:2],np.ones(len(centre))])@plane
normal=np.cross(triangles[:,1]-triangles[:,0],triangles[:,2]-triangles[:,0])
admit=((hi>=bounds[0]-1)&(lo<=bounds[1]+1)).all(1)&(np.abs(centre[:,2]-expected)<=.75)
admit&=np.abs(normal[:,2])>np.linalg.norm(normal,axis=1)*.5
self.triangles=triangles[admit];self.cells=defaultdict(list)
for index,triangle in enumerate(self.triangles):
low=np.maximum(np.floor(triangle[:,:2].min(0)),np.floor(bounds[0]-1)).astype(int)
high=np.minimum(np.floor(triangle[:,:2].max(0)),np.ceil(bounds[1]+1)).astype(int)
for x in range(low[0],high[0]+1):
for y in range(low[1],high[1]+1):self.cells[(x,y)].append(index)
if not len(self.triangles):raise ValueError('No collider ground in mapping tile')
def sample(self,xy,reference):
heights=np.full(len(xy),np.nan)
for i,(x,y) in enumerate(xy):
ids=self.cells.get((math.floor(x),math.floor(y)),[])
if not ids:continue
tri=self.triangles[ids];a,b,c=tri[:,0],tri[:,1],tri[:,2]
den=(b[:,1]-c[:,1])*(a[:,0]-c[:,0])+(c[:,0]-b[:,0])*(a[:,1]-c[:,1])
okay=np.abs(den)>1e-9;a,b,c,den=a[okay],b[okay],c[okay],den[okay]
u=((b[:,1]-c[:,1])*(x-c[:,0])+(c[:,0]-b[:,0])*(y-c[:,1]))/den
v=((c[:,1]-a[:,1])*(x-c[:,0])+(a[:,0]-c[:,0])*(y-c[:,1]))/den
inside=(u>=-1e-6)&(v>=-1e-6)&(u+v<=1+1e-6)
z=(u*a[:,2]+v*b[:,2]+(1-u-v)*c[:,2])[inside]
if len(z):heights[i]=z[np.argmin(np.abs(z-reference[i]))]
return heights
@@ -0,0 +1,167 @@
"""Metric object assembly from VMA; private raster evidence stays on the worker.
The height reference rejects non-ground projections, it never edits the collider.
Unknown/occluded sections are split, not filled with an invented road surface.
"""
import argparse, json, hashlib
from pathlib import Path
import numpy as np
import cv2
from PIL import Image
from shapely.geometry import LineString, Polygon
from scipy.ndimage import median_filter
CLASS_MAP={'curb':'curb','lane':'road_marking','stopline':'road_marking','Crosswalk':'crosswalk_area'}
def digest(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for b in iter(lambda:f.read(8388608),b''):h.update(b)
return h.hexdigest()
def select_objects(candidates):
"""Class-aware overlap suppression, with provenance from all agreeing crops."""
accepted=[]
for item in sorted(candidates,key=lambda f:-f['score']):
if item['class_name'] not in CLASS_MAP:continue
p=np.asarray(item['points'],float)
geom=Polygon(p[:4]) if item['kind']=='box' else LineString(p)
if not geom.is_valid or geom.is_empty:continue
duplicate=None
for keep in accepted:
if keep['kind']!=item['kind']:continue
if item['kind']=='box' and keep['class_name']!=item['class_name']:continue
other=keep['_geometry']
if item['kind']=='box':
match=geom.intersection(other).area/max(geom.union(other).area,1e-9)>.5
else:
match=(geom.intersection(other.buffer(2)).length>.85*geom.length
and geom.length<=other.length*1.25)
if match:duplicate=keep;break
if duplicate is not None:
duplicate['support_tiles'].append(item['tile_xy']);continue
accepted.append({**item,'_geometry':geom,'support_tiles':[item['tile_xy']]})
return accepted
class HeightLift:
def __init__(self,geometry,atlas):
self.depth=median_filter(geometry['depth'],size=3)
self.alpha=geometry['alpha'];self.k=geometry['intrinsics'];self.inverse=np.linalg.inv(geometry['view'])
self.height,self.width=self.depth.shape
# Robust height envelope fitted only to already observed ground returns.
z=atlas['z'];rr,cc=np.where(np.isfinite(z))
assert len(rr)>=100,'Insufficient observed ground reference'
cell=float(atlas['cell_m']);bounds=atlas['bounds'];h=z.shape[0]
x=bounds[0,0]+(cc+.5)*cell;y=bounds[0,1]+(h-rr-.5)*cell
a=np.column_stack([x,y,np.ones(len(x))]);keep=np.ones(len(x),bool)
for _ in range(4):
self.plane=np.linalg.lstsq(a[keep],z[rr[keep],cc[keep]],rcond=None)[0]
residual=np.abs(a@self.plane-z[rr,cc]);keep=residual<=max(.15,3*float(np.median(residual)))
self.reference_xy=np.column_stack([x[keep],y[keep]])
self.collider=None
def lift(self,pixels):
p=np.asarray(pixels,float);c=np.clip(np.rint(p[:,0]).astype(int),0,self.width-1);r=np.clip(np.rint(p[:,1]).astype(int),0,self.height-1)
xy=(p+.5-self.k[:2,2])/np.diag(self.k)[:2]
xyz=np.column_stack([xy,self.depth[r,c],np.ones(len(p))])@self.inverse.T
residual=np.abs(xyz[:,2]-np.column_stack([xyz[:,:2],np.ones(len(p))])@self.plane)
valid=(self.alpha[r,c]>=.5)&(residual<=.75)&np.isfinite(xyz).all(1)
if self.collider is not None:
heights=self.collider.sample(xyz[:,:2],xyz[:,2])
valid&=np.isfinite(heights)&(np.abs(heights-xyz[:,2])<=.5)
xyz[:,2]=heights
valid&=(p[:,0]>=0)&(p[:,0]<self.width)&(p[:,1]>=0)&(p[:,1]<self.height)
return xyz[:,:3],valid
def paint_stripes(rgb,quad):
"""Fit only visible stripe paint within a detected crossing envelope."""
quad=np.asarray(quad[:4],np.float32)
width=int(round(np.linalg.norm(quad[3]-quad[0])));height=int(round(np.linalg.norm(quad[1]-quad[0])))
if min(width,height)<10:return []
dest=np.float32([[0,0],[0,height-1],[width-1,height-1],[width-1,0]])
transform=cv2.getPerspectiveTransform(quad,dest)
crop=cv2.warpPerspective(rgb,transform,(width,height))
gray=cv2.cvtColor(crop,cv2.COLOR_RGB2GRAY)
# Work on actual brightness, rejecting shadow/scan gaps and thin dashed edges.
_,mask=cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,np.ones((2,2),np.uint8))
contours,_=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
boxes=[]
for contour in contours:
rect=cv2.minAreaRect(contour);a,b=sorted(rect[1]);area=cv2.contourArea(contour)
if not (a>=2 and b>=.55*min(width,height) and b/a>=3 and area/max(a*b,1)>=.5):continue
corners=cv2.boxPoints(rect)
corners=cv2.perspectiveTransform(corners[None],np.linalg.inv(transform))[0]
boxes.append(corners.tolist())
# A single white fragment cannot establish a zebra pattern.
return boxes if len(boxes)>=3 else []
def assemble(args):
candidates=json.loads(args.candidates.read_text());job=json.loads(args.job.read_text())
assert digest(args.image)==candidates['source_image_sha256'],'Different source image'
rgb=np.asarray(Image.open(args.image).convert('RGB'));lift=HeightLift(np.load(args.geometry),np.load(args.atlas))
from surface_height import ColliderHeight
terrain=json.loads((args.package/'terrain.json').read_text())
name=job['source']['collider_sha256']+'.decoded.glb'
meta=json.loads((args.package/name.replace('.glb','.json')).read_text())
assert meta['source_sha256']==job['source']['collider_sha256']
assert digest(args.package/name)==meta['sha256'],'Collider hash mismatch'
lift.collider=ColliderHeight(args.package/name,terrain['collision_rotation'],job['bounds_xy'],lift.plane)
features=[];rejected=[]
def add(item,pixels,kind,cls,role):
xyz,valid=lift.lift(pixels)
if kind=='Polygon':
if not valid.all():return
rings=[np.vstack([xyz,xyz[0]]).round(4).tolist()]
else:
rings=xyz.round(4).tolist()
identifier=hashlib.sha256(json.dumps([cls,kind,rings],sort_keys=True).encode()).hexdigest()[:16]
features.append(dict(type='Feature',id=identifier,properties=dict(
**{'class':cls},authority='observation-only',route_permission='unassigned',
source_class=item['class_name'],confidence=round(item['score'],4),
geometry_role=role,review_status='unreviewed',height_source='collider-intersection-visual-ground-checked',
support_tiles=item['support_tiles']),geometry=dict(type=kind,coordinates=rings)))
objects=select_objects(candidates['features'])
for item in objects:
if item['kind']=='box':
points=item['points'][:4]
add(item,points,'Polygon',CLASS_MAP[item['class_name']],'object-envelope')
if item['class_name']=='Crosswalk':
for stripe in paint_stripes(rgb,points):
add(item,stripe,'Polygon','crosswalk_marking','paint-footprint')
continue
curve=item['_geometry'].simplify(1.,preserve_topology=True)
# Sample every <=5cm at the native 5cm/px image resolution before lifting.
samples=np.array([curve.interpolate(d).coords[0] for d in np.linspace(0,curve.length,max(2,int(np.ceil(curve.length))+1))])
xyz,valid=lift.lift(samples)
# Split at missing/above-ground evidence; no across-gap extrapolation.
segments=np.split(np.arange(len(samples)),np.flatnonzero(np.diff(valid.astype(int)))+1)
for segment in segments:
if len(segment)<2 or not valid[segment].all():continue
segment_xyz=xyz[segment]
if np.linalg.norm(np.diff(segment_xyz[:,:2],axis=0),axis=1).sum()<1.:continue
# Metric simplification after height validation retains native shape.
simplified=LineString(segment_xyz[:,:2]).simplify(.05)
indices=[segment[np.argmin(np.linalg.norm(segment_xyz[:,:2]-xy,axis=1))] for xy in simplified.coords]
add(item,samples[indices],'LineString',CLASS_MAP[item['class_name']],'boundary' if item['class_name']=='curb' else 'paint-axis')
doc=dict(schema_version='missioncore.urban-map/v2',type='FeatureCollection',
coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False),
source=dict(world_sha256=job['source']['world_sha256'],collider_sha256=job['source']['collider_sha256'],
image_sha256=candidates['source_image_sha256'],vma_commit=candidates['vma_commit'],weights=candidates['weights']),
coverage=dict(cell_m=float(1/lift.k[0,0]),accepted_cells=0,kind='objects-only',extent_xy=job['bounds_xy']),
review_status='unreviewed',features=features)
args.output.mkdir(parents=True,exist_ok=True)
(args.output/'urban-map.json').write_text(json.dumps(doc,ensure_ascii=False,allow_nan=False,indent=2))
(args.output/'assembly.json').write_text(json.dumps(dict(raw_candidates=len(candidates['features']),objects=len(objects),
features=len(features),ground_reference_plane=lift.plane.tolist()),indent=2))
print(json.dumps(dict(features=len(features),classes={c:sum(f['properties']['class']==c for f in features) for c in set(f['properties']['class'] for f in features)})),flush=True)
if __name__=='__main__':
p=argparse.ArgumentParser()
for name in ['candidates','job','image','geometry','atlas','package','output']:p.add_argument('--'+name,type=Path,required=True)
assemble(p.parse_args())